Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge f65e38f3d1 Remove provider environment sync effect
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 16:47:30 +00:00
HuakunandJulius Marminge d25090cf6d fix: avoid sending composer during IME enter (#2817)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:14:13 +00:00
Mika CohenandJulius Marminge ae39bacf0e Handle non-resumable pending user input (#2766)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:13:34 +00:00
Julius MarmingeandJulius Marminge 1ea17026ee [codex] fix slow websocket shutdown (#2869)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 01:39:25 +00:00
Julius Marmingeandcodex 649f4328ea [codex] Refine inline tool call timeline UI (#3052)
Co-authored-by: codex <[email protected]>
2026-06-11 18:18:27 -07:00
Magnus Alexander StrømsengandJulius Marminge 7db034905b fix(git): disable external diff for patch output (#2553)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-11 18:18:13 -07:00
Julius MarmingeandClaude Fable 5 57f6bf7edb Fix turn fold proejctions (#3041)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 23:51:43 -07:00
Julius Marmingeandcodex 0baf1986e8 [codex] Reduce Git status polling churn (#3037)
Co-authored-by: codex <[email protected]>
2026-06-10 17:10:19 -07:00
Julius Marmingeandcodex ae7e88b0e0 [codex] Sync app-server protocol, service tiers, and provider startup (#3036)
Co-authored-by: codex <[email protected]>
2026-06-10 16:24:19 -07:00
1916ac6d55 Rework message metadata, timestamps, and tool work log rows (#3022)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 14:38:42 -07:00
Julius Marmingeandcodex 343061a053 Misc chrome polish: header badges, plan sidebar, diff panel, empty state (#3027)
Co-authored-by: codex <[email protected]>
2026-06-10 12:25:03 -07:00
0b40ea62e1 Extract changed files card with compact aligned diff stats (#3023)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:27:32 +00:00
a4757c2656 Composer polish: focus ring, send/stop buttons, command menu, context meter, answer panel (#3018)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:02:32 +00:00
3efabdcd3a Polish web context menu fallback and sidebar icon actions (#3025)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 07:29:21 +00:00
c5f7cd40ba Polish branch picker trigger, scroll fade, and list layout (#3024)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-06-10 07:13:34 +00:00
e2db800f7c Provider env vars table and reworked accent color picker (#3026)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 23:27:59 -07:00
31533466b0 Model picker UI Improvements, Virtualize Model List (#3021)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 06:22:55 +00:00
7f741a56d1 Misc markdown styling improvements (#3017)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-06-09 21:21:58 -07:00
RuzbyteandJulius Marminge cc9e81ac93 fix(marketing) : marketing showing wrong icons on linux (#2696)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 20:04:36 -07:00
238715fd6f Polish dialog/alert surfaces and unauthenticated provider banner (#3016)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:52:16 -07:00
b03bc4b52d Mute icons in labeled controls and suppress popup focus rings (#3015)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:15:09 -07:00
aca14507f7 Bundle DM Sans and JetBrains Mono fonts instead of Google Fonts (#3014)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 16:57:38 -07:00
151 changed files with 13755 additions and 5017 deletions

No files matched your search

@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
Effect.orElseSucceed(() => null),
);
const dnsName =
input.statusJson === undefined
@@ -44,6 +44,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
@@ -1,53 +0,0 @@
---
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>
+1 -1
View File
@@ -47,7 +47,7 @@ import { RELEASES_URL } from "../lib/releases";
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2Line truncated
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
+4 -4
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import TuxIcon from "../components/TuxIcon.astro";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -53,7 +52,7 @@ const mobileEndorsementRows = [
>
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="hero-linux-" />
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="download-label">Download for macOS</span>
</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
@@ -360,7 +359,8 @@ const mobileEndorsementRows = [
<a id="cta-download-btn" class="btn btn-primary btn-lg" href="https://github.com/pingdotgg/t3code/releases">
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="cta-linux-" />
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="cta-download-label">Download for macOS</span>
</a>
<a class="btn btn-ghost btn-lg" href="/download">Windows · Linux · other</a>
@@ -548,7 +548,7 @@ const mobileEndorsementRows = [
:global([data-platform="mac"]) .dl-icon--apple { display: block; }
:global([data-platform="win"]) .dl-icon--windows { display: block; }
:global([data-platform="linux"]) .dl-icon--linux { display: block; }
:global(:not([data-platform])) .dl-icon--apple { display: block; }
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
/* Floating harness marks */
.hero-float {
+2 -7
View File
@@ -1,4 +1,4 @@
import { useAuth, useUser, useUserProfileModal } from "@clerk/expo";
import { useAuth, useUser } from "@clerk/expo";
import * as Notifications from "expo-notifications";
import { Link, Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
@@ -68,7 +68,6 @@ function ConfiguredSettingsRouteScreen() {
const { push } = useRouter();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
const { savedConnectionsById } = useRemoteEnvironmentState();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -266,15 +265,11 @@ function ConfiguredSettingsRouteScreen() {
push("/settings/waitlist");
return;
}
if (isUserProfileModalAvailable) {
void presentUserProfile();
return;
}
Alert.alert(
"T3 Cloud unavailable",
"Native T3 Cloud account management is not available in this build.",
);
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]);
}, [isLoaded, isSignedIn, push]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -10,7 +10,7 @@ import type {
import {
detectComposerTrigger,
replaceTextRange,
serializeComposerMentionPath,
serializeComposerFileLink,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
@@ -419,7 +419,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
let replacement = "";
if (item.type === "path") {
replacement = `@${serializeComposerMentionPath(item.path)} `;
replacement = `${serializeComposerFileLink(item.path)} `;
} else if (item.type === "skill") {
replacement = `$${item.skill.name} `;
} else if (item.type === "slash-command") {
+1 -1
View File
@@ -22,7 +22,7 @@
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
+5
View File
@@ -22,6 +22,7 @@ const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION ===
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
@@ -364,6 +365,10 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
+22
View File
@@ -0,0 +1,22 @@
import { assert, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
it("returns the selected Codex service tier id", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
{ id: "serviceTier", value: "flex" },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
});
it("keeps legacy persisted fast mode selections working", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "fastMode", value: true },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
});
+14
View File
@@ -0,0 +1,14 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
export function getCodexServiceTierOptionValue(
modelSelection: ModelSelection | null | undefined,
): string | undefined {
return (
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
);
}
+1 -1
View File
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
.statusDetailsRemote(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
@@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-lifecycle");
const turnId = TurnId.make("turn-lifecycle-1");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-tl1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-tl1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-lifecycle"),
title: "Turn lifecycle",
modelSelection: {
instanceId: ProviderInstanceId.make("claude"),
model: "claude-opus",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: CommandId.make("cmd-tl2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl2"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
},
});
// Interim assistant message completes mid-turn (commentary between
// tool calls) — the turn must stay running and unsettled.
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.make("evt-tl3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:05.000Z",
commandId: CommandId.make("cmd-tl3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-tl-interim"),
role: "assistant",
text: "interim commentary",
turnId,
streaming: false,
createdAt: "2026-01-01T00:00:05.000Z",
updatedAt: "2026-01-01T00:00:05.000Z",
},
});
yield* projectionPipeline.bootstrap;
const runningRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
// The session leaving "running" is the turn-end signal.
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:01:00.000Z",
commandId: CommandId.make("cmd-tl4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl4"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-01-01T00:01:00.000Z",
},
},
});
yield* projectionPipeline.bootstrap;
const settledRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
}),
);
it.effect("settles a superseded running turn when a new turn becomes active", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-supersede");
const oldTurnId = TurnId.make("turn-superseded");
const newTurnId = TurnId.make("turn-steer");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-ts1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-ts1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-ts1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-supersede"),
title: "Turn supersede",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "big-pickle",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
eventStore.append({
type: "thread.session-set",
eventId: EventId.make(eventId),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: updatedAt,
commandId: CommandId.make(`cmd-${eventId}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-${eventId}`),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "opencode",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt,
},
},
});
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
// A steer: a new turn becomes active without the provider ever
// completing the previous one.
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
yield* projectionPipeline.bootstrap;
const rows = yield* sql<{
readonly turnId: string;
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
ORDER BY requested_at
`;
assert.deepEqual(rows, [
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
{ turnId: newTurnId, state: "running", completedAt: null },
]);
}),
);
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -1656,6 +1877,142 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("clears stale pending user input from projected shell summaries", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-stale-user-input-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-stale-user-input"),
occurredAt: "2026-02-26T12:35:00.000Z",
commandId: CommandId.make("cmd-stale-user-input-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-stale-user-input"),
title: "Project Stale User Input",
workspaceRoot: "/tmp/project-stale-user-input",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-02-26T12:35:00.000Z",
updatedAt: "2026-02-26T12:35:00.000Z",
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-stale-user-input-2"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:01.000Z",
commandId: CommandId.make("cmd-stale-user-input-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-2"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
projectId: ProjectId.make("project-stale-user-input"),
title: "Thread Stale User Input",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T12:35:01.000Z",
updatedAt: "2026-02-26T12:35:01.000Z",
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-3"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:02.000Z",
commandId: CommandId.make("cmd-stale-user-input-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-stale-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: "2026-02-26T12:35:02.000Z",
},
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-4"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:03.000Z",
commandId: CommandId.make("cmd-stale-user-input-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-failed"),
tone: "error",
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
payload: {
requestId: "user-input-request-stale-1",
detail:
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
},
turnId: null,
createdAt: "2026-02-26T12:35:03.000Z",
},
},
});
const threadRows = yield* sql<{
readonly pendingUserInputCount: number;
}>`
SELECT pending_user_input_count AS "pendingUserInputCount"
FROM projection_threads
WHERE thread_id = 'thread-stale-user-input'
`;
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
}),
);
it.effect("ignores non-stale provider approval response failures", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -2,6 +2,7 @@ import {
ApprovalRequestId,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
type ProjectorName =
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
/**
* Turn state to settle still-running turns with when their session leaves the
* "running" status, or null while the session is (re)starting or running and
* turns must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSessionStatus,
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
interface ProjectorDefinition {
readonly name: ProjectorName;
readonly apply: (
@@ -141,7 +165,9 @@ function derivePendingUserInputCountFromActivities(
activity.kind === "provider.user-input.respond.failed" &&
detail !== null &&
(detail.includes("stale pending user-input request") ||
detail.includes("unknown pending user-input request"))
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request"))
) {
openRequestIds.delete(requestId);
}
@@ -999,9 +1025,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
if (settledTurnState === null) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
return;
}
// A new active turn supersedes any still-running turn on the same
// thread — steering can open a new turn without the provider ever
// completing the previous one.
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
otherRunningTurns.filter(
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: "completed",
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId,
@@ -1080,6 +1154,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (event.payload.turnId === null || event.payload.role !== "assistant") {
return;
}
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end
// (projected as thread.session-set leaving the "running" status).
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1088,16 +1175,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming
? existingTurn.value.state
: existingTurn.value.state === "interrupted"
state: settlesTurn
? existingTurn.value.state === "interrupted"
? "interrupted"
: existingTurn.value.state === "error"
? "error"
: "completed",
completedAt: event.payload.streaming
? existingTurn.value.completedAt
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
: "completed"
: existingTurn.value.state,
completedAt: settlesTurn
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
: existingTurn.value.completedAt,
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
});
@@ -1110,10 +1197,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
state: settlesTurn ? "completed" : "running",
requestedAt: event.payload.createdAt,
startedAt: event.payload.createdAt,
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
completedAt: settlesTurn ? event.payload.updatedAt : null,
checkpointTurnCount: null,
checkpointRef: null,
checkpointStatus: null,
@@ -1160,6 +1247,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.turn-diff-completed": {
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1175,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? existingTurn.value.state : nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
@@ -1193,7 +1289,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? "running" : nextState,
requestedAt: event.payload.completedAt,
startedAt: event.payload.completedAt,
completedAt: event.payload.completedAt,
@@ -1943,7 +1943,7 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.respondToUserInput.mockImplementation(() =>
@@ -1951,7 +1951,7 @@ describe("ProviderCommandReactor", () => {
new ProviderAdapterRequestError({
provider: ProviderDriverKind.make("claudeAgent"),
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
detail: "Unknown pending Codex user input request: user-input-request-1",
}),
),
);
@@ -141,9 +141,19 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request")
);
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
const message = Cause.pretty(cause).toLowerCase();
return (
message.includes("unknown pending user-input request") ||
message.includes("unknown pending user input request") ||
message.includes("unknown pending codex user input request")
);
}
function stalePendingRequestDetail(
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
Effect.andThen(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
branch: null,
worktreePath: null,
createdAt,
}),
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
@@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => {
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
// Steering a running turn: the server requests a new turn while the old
// one is still active, and providers like opencode open the new turn
// without ever completing the superseded one. The new turn.started must
// replace the active turn instead of being rejected as stale.
const harness = await createHarness();
const threadId = asThreadId("thread-1");
const oldTurnId = asTurnId("turn-steered-over");
const newTurnId = asTurnId("turn-from-steer");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: oldTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-steered-over"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: oldTurnId,
});
await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
2_000,
threadId,
);
// The steer: a user-requested turn start while the old turn still runs.
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-steer"),
threadId,
message: {
messageId: asMessageId("msg-steer"),
role: "user",
text: "actually, do 15 instead",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
);
// The provider session tracks the new turn before emitting turn.started
// (sendTurn updates the session first).
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: newTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-from-steer"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: newTurnId,
});
const threadAfterSteer = await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
2_000,
threadId,
);
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () {
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
// A turn.started that conflicts with the active turn is legitimate when
// the server itself has a turn start pending for this thread AND the
// provider session already tracks the event's turn as its active turn:
// steering a running turn makes some providers (e.g. opencode) open a
// new turn without ever completing the superseded one. A stale
// turn.started for some other turn id still gets rejected.
const conflictingTurnStartIsPendingTurnStart =
event.type === "turn.started" && conflictsWithActiveTurn
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
Option.isSome(
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
}),
)
: false;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
@@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () {
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn;
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
+62 -23
View File
@@ -267,37 +267,76 @@ describe("orchestration projector", () => {
),
);
const afterRunning = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
session: {
const settledAt = "2026-02-23T08:01:00.000Z";
const [afterRunning, afterReady] = await Effect.runPromise(
Effect.flatMap(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
session: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
},
},
},
}),
}),
),
(running) =>
Effect.map(
projectEvent(
running,
makeEvent({
sequence: 3,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: settledAt,
commandId: "cmd-ready",
payload: {
threadId: "thread-1",
session: {
threadId: "thread-1",
status: "ready",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: settledAt,
},
},
}),
),
(ready) => [running, ready] as const,
),
),
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
// Leaving the "running" session status settles the running turn with the
// session timestamp as the turn end.
const settledThread = afterReady.threads[0];
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
expect(settledThread?.latestTurn?.state).toBe("completed");
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
});
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
+59 -15
View File
@@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
return "completed" as const;
}
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -438,6 +461,9 @@ export function projectEvent(
"session",
);
// Leaving the "running" session status is the turn-end signal: settle
// a still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(session.status);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -461,7 +487,18 @@ export function projectEvent(
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: session.updatedAt,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -544,24 +581,31 @@ export function projectEvent(
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
.slice(-MAX_THREAD_CHECKPOINTS);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const turnStillRunning =
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
latestTurn: turnStillRunning
? thread.latestTurn
: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
@@ -890,6 +890,73 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runCollect, Effect.forkChild);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "run 5 commands",
attachments: [],
});
// Steer: a second sendTurn while the turn is still running continues
// the same turn — the message is queued into the live agent loop.
const steeredTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "actually run 15",
attachments: [],
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
harness.query.emit({
type: "assistant",
session_id: "sdk-session-steer",
uuid: "assistant-steer-1",
parent_tool_use_id: null,
message: {
id: "assistant-message-steer-1",
content: [{ type: "text", text: "Adjusting to 15." }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-steer",
uuid: "result-steer-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the steer produced no
// turn.completed/turn.started pair.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId));
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
const harness = makeHarness();
return Effect.gen(function* () {
+627 -168
View File
@@ -14,6 +14,7 @@ import {
type PermissionResult,
type PermissionUpdate,
type SDKMessage,
type SDKControlGetContextUsageResponse,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
@@ -29,6 +30,7 @@ import {
type ProviderApprovalDecision,
ProviderDriverKind,
ProviderInstanceId,
type ModelSelection,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
@@ -120,6 +122,13 @@ interface ClaudeResumeState {
interface ClaudeTurnState {
readonly turnId: TurnId;
readonly startedAt: string;
/**
* True for turns auto-started by assistant output arriving without an
* active turn (background agent/subagent responses between user prompts).
* Synthetic turns are auto-closed by the next sendTurn; real turns are
* steered instead (the queued message continues the same turn).
*/
readonly synthetic?: boolean;
readonly items: Array<unknown>;
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
@@ -159,6 +168,13 @@ interface ToolInFlight {
readonly lastEmittedInputFingerprint?: string;
}
interface ClaudeTaskState {
readonly id: string;
subject: string;
status: PlanStep["status"];
readonly blockedBy: Set<string>;
}
interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
@@ -175,9 +191,11 @@ interface ClaudeSessionContext {
items: Array<unknown>;
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
readonly claudeTasks: Map<string, ClaudeTaskState>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
lastKnownTotalProcessedTokens: number | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
stopped: boolean;
@@ -188,6 +206,7 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
readonly close: () => void;
}
@@ -337,60 +356,220 @@ function maxClaudeContextWindowFromModelUsage(
return maxContextWindow;
}
function normalizeClaudeTokenUsage(
function selectedClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): number | undefined {
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? Math.round(value)
: undefined;
}
function finitePositiveInteger(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0
? Math.round(value)
: undefined;
}
function claudeUsageInputTokens(usage: Record<string, unknown>): number {
return (
(finiteNonNegativeInteger(usage.input_tokens) ?? 0) +
(finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +
(finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)
);
}
function claudeUsageOutputTokens(usage: Record<string, unknown>): number {
return finiteNonNegativeInteger(usage.output_tokens) ?? 0;
}
function lastClaudeUsageIteration(
value: Record<string, unknown>,
): Record<string, unknown> | undefined {
const iterations = Array.isArray(value.iterations) ? value.iterations : [];
return iterations.findLast(
(iteration): iteration is Record<string, unknown> =>
iteration !== null && typeof iteration === "object" && !Array.isArray(iteration),
);
}
function claudeTotalProcessedTokens(value: unknown): number | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return undefined;
}
const usage = value as Record<string, unknown>;
const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);
if (explicitTotal !== undefined && explicitTotal > 0) {
return explicitTotal;
}
const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);
return total > 0 ? total : undefined;
}
function makeClaudeTokenUsageSnapshot(input: {
readonly activeTokens: number;
readonly inputTokens?: number;
readonly outputTokens?: number;
readonly contextWindow?: number;
readonly totalProcessedTokens?: number;
readonly lastUsedTokens?: number;
readonly compactsAutomatically?: boolean;
}): ThreadTokenUsageSnapshot | undefined {
const activeTokens = finiteNonNegativeInteger(input.activeTokens);
if (activeTokens === undefined || activeTokens <= 0) {
return undefined;
}
const maxTokens = finitePositiveInteger(input.contextWindow);
const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;
const lastUsedTokens =
finiteNonNegativeInteger(input.lastUsedTokens) ??
(maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);
const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);
const inputTokens = finiteNonNegativeInteger(input.inputTokens);
const outputTokens = finiteNonNegativeInteger(input.outputTokens);
return {
usedTokens,
lastUsedTokens,
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(input.compactsAutomatically !== undefined
? { compactsAutomatically: input.compactsAutomatically }
: {}),
};
}
function normalizeClaudeActiveTokenUsage(
value: unknown,
contextWindow?: number,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const usage = value as Record<string, unknown>;
const inputTokens =
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
? usage.input_tokens
: 0) +
(typeof usage.cache_creation_input_tokens === "number" &&
Number.isFinite(usage.cache_creation_input_tokens)
? usage.cache_creation_input_tokens
: 0) +
(typeof usage.cache_read_input_tokens === "number" &&
Number.isFinite(usage.cache_read_input_tokens)
? usage.cache_read_input_tokens
: 0);
const outputTokens =
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
? usage.output_tokens
: 0;
const derivedTotalProcessedTokens = inputTokens + outputTokens;
const totalProcessedTokens =
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
? usage.total_tokens
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
const activeUsage = lastClaudeUsageIteration(usage) ?? usage;
const inputTokens = claudeUsageInputTokens(activeUsage);
const outputTokens = claudeUsageOutputTokens(activeUsage);
const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;
if (activeTokens <= 0) {
return undefined;
}
const maxTokens =
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
? contextWindow
: undefined;
const usedTokens =
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
return makeClaudeTokenUsageSnapshot({
activeTokens,
inputTokens,
outputTokens,
...(contextWindow !== undefined ? { contextWindow } : {}),
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
});
}
function normalizeClaudeContextUsageApiSnapshot(
value: SDKControlGetContextUsageResponse,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
return makeClaudeTokenUsageSnapshot({
activeTokens: value.totalTokens,
contextWindow: value.maxTokens,
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
compactsAutomatically: value.isAutoCompactEnabled,
});
}
function compactBoundaryTokenUsageSnapshot(
message: Record<string, unknown>,
contextWindow?: number,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
const metadata = message.compact_metadata;
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
return undefined;
}
const compactMetadata = metadata as Record<string, unknown>;
const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);
if (postTokens === undefined || postTokens <= 0) {
return undefined;
}
const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);
return makeClaudeTokenUsageSnapshot({
activeTokens: postTokens,
...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
});
}
function normalizeClaudeTaskProgressTokenUsage(
value: unknown,
context: ClaudeSessionContext,
): ThreadTokenUsageSnapshot | undefined {
const totalTokens = claudeTotalProcessedTokens(value);
if (totalTokens === undefined || totalTokens <= 0) {
return undefined;
}
const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;
const activeTokens =
lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;
if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {
return undefined;
}
const usage = value as Record<string, unknown>;
const snapshot = makeClaudeTokenUsageSnapshot({
activeTokens,
...(context.lastKnownContextWindow !== undefined
? { contextWindow: context.lastKnownContextWindow }
: {}),
totalProcessedTokens: Math.max(
totalTokens,
context.lastKnownTotalProcessedTokens ?? totalTokens,
),
});
if (!snapshot) {
return undefined;
}
const toolUses = finiteNonNegativeInteger(usage.tool_uses);
const durationMs = finiteNonNegativeInteger(usage.duration_ms);
return {
usedTokens,
lastUsedTokens: usedTokens,
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
? { toolUses: usage.tool_uses }
: {}),
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
? { durationMs: usage.duration_ms }
: {}),
...snapshot,
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
};
}
@@ -539,6 +718,140 @@ function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep
}));
}
function isClaudeTaskTool(toolName: string): boolean {
return toolName === "TaskCreate" || toolName === "TaskUpdate" || toolName === "TaskList";
}
function normalizeClaudeTaskStatus(value: unknown): PlanStep["status"] {
return value === "completed" ? "completed" : value === "in_progress" ? "inProgress" : "pending";
}
function readString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function readStringArray(value: unknown): Array<string> {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
: [];
}
function readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {
if (message.type !== "user") {
return undefined;
}
const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;
return result !== null && typeof result === "object" && !Array.isArray(result)
? (result as Record<string, unknown>)
: undefined;
}
function readClaudeTaskFromResult(
result: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
const task = result?.task;
return task !== null && typeof task === "object" && !Array.isArray(task)
? (task as Record<string, unknown>)
: undefined;
}
function applyClaudeTaskToolResult(
tasks: Map<string, ClaudeTaskState>,
tool: ToolInFlight,
result: Record<string, unknown> | undefined,
): boolean {
if (!isClaudeTaskTool(tool.toolName)) {
return false;
}
let changed = false;
if (tool.toolName === "TaskList") {
const resultTasks = result?.tasks;
if (!Array.isArray(resultTasks)) {
return false;
}
tasks.clear();
for (const entry of resultTasks) {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
continue;
}
const task = entry as Record<string, unknown>;
const id = readString(task.id);
const subject = readString(task.subject);
if (!id || !subject) {
continue;
}
tasks.set(id, {
id,
subject,
status: normalizeClaudeTaskStatus(task.status),
blockedBy: new Set(readStringArray(task.blockedBy)),
});
}
return tasks.size > 0;
}
if (tool.toolName === "TaskCreate") {
const resultTask = readClaudeTaskFromResult(result);
const id = readString(resultTask?.id);
const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);
if (!id || !subject) {
return false;
}
tasks.set(id, {
id,
subject,
status: normalizeClaudeTaskStatus(tool.input.status),
blockedBy: new Set(readStringArray(tool.input.blockedBy)),
});
return true;
}
const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);
if (!taskId) {
return false;
}
const task = tasks.get(taskId);
if (!task) {
return false;
}
const subject = readString(tool.input.subject);
if (subject && task.subject !== subject) {
task.subject = subject;
changed = true;
}
if (typeof tool.input.status === "string") {
const status = normalizeClaudeTaskStatus(tool.input.status);
if (task.status !== status) {
task.status = status;
changed = true;
}
}
for (const dependency of readStringArray(tool.input.addBlockedBy)) {
if (!task.blockedBy.has(dependency)) {
task.blockedBy.add(dependency);
changed = true;
}
}
for (const dependency of readStringArray(tool.input.removeBlockedBy)) {
if (task.blockedBy.delete(dependency)) {
changed = true;
}
}
return changed;
}
function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {
return Array.from(tasks.values()).map((task) => {
const blockedBy = Array.from(task.blockedBy);
const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(", #")})` : "";
return {
step: `${task.subject}${blockedSuffix}`,
status: task.status,
};
});
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -1438,6 +1751,70 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
});
const emitThreadTokenUsage = Effect.fn("emitThreadTokenUsage")(function* (
context: ClaudeSessionContext,
usage: ThreadTokenUsageSnapshot | undefined,
options?: {
readonly rawMethod?: string;
readonly rawPayload?: unknown;
},
) {
if (!usage) {
return;
}
context.lastKnownTokenUsage = usage;
context.lastKnownTotalProcessedTokens =
usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;
const turnState = context.turnState;
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(turnState ? { turnId: turnState.turnId } : {}),
payload: {
usage,
},
providerRefs: nativeProviderRefs(context),
...(options?.rawMethod || options?.rawPayload
? {
raw: {
source: "claude.sdk.message" as const,
...(options.rawMethod ? { method: options.rawMethod } : {}),
payload: options.rawPayload,
},
}
: {}),
});
});
const queryCurrentContextUsage = Effect.fn("queryCurrentContextUsage")(function* (
context: ClaudeSessionContext,
totalProcessedTokens?: number,
) {
if (!context.query.getContextUsage) {
return undefined;
}
const usage = yield* Effect.promise(async () => {
try {
return await context.query.getContextUsage?.();
} catch {
return undefined;
}
});
if (!usage) {
return undefined;
}
context.lastKnownContextWindow = usage.maxTokens;
return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);
});
const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* (
context: ClaudeSessionContext,
input: {
@@ -1485,6 +1862,42 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
});
const emitClaudeTaskPlanUpdated = Effect.fn("emitClaudeTaskPlanUpdated")(function* (
context: ClaudeSessionContext,
input: {
readonly toolUseId: string;
readonly rawMethod: string;
readonly rawPayload: unknown;
},
) {
const plan = planStepsFromClaudeTasks(context.claudeTasks);
if (plan.length === 0) {
return;
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.plan.updated",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
payload: {
explanation: "Claude Tasks",
plan,
},
providerRefs: nativeProviderRefs(context, {
providerItemId: input.toolUseId,
}),
raw: {
source: "claude.sdk.message",
method: input.rawMethod,
payload: input.rawPayload,
},
});
});
const completeTurn = Effect.fn("completeTurn")(function* (
context: ClaudeSessionContext,
status: ProviderRuntimeTurnStatus,
@@ -1496,51 +1909,77 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.lastKnownContextWindow = resultContextWindow;
}
// The SDK result.usage contains *accumulated* totals across all API calls
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
// This does NOT represent the current context window size.
// Instead, use the last known context-window-accurate usage from task_progress
// events and treat the accumulated total as totalProcessedTokens.
const accumulatedSnapshot = normalizeClaudeTokenUsage(
result?.usage,
resultContextWindow ?? context.lastKnownContextWindow,
);
const accumulatedTotalProcessedTokens =
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
const lastGoodUsage = context.lastKnownTokenUsage;
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: accumulatedSnapshot;
const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);
if (accumulatedTotalProcessedTokens !== undefined) {
context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;
}
const contextUsageSnapshot = yield* queryCurrentContextUsage(
context,
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
);
const resultUsageRecord =
result?.usage && typeof result.usage === "object" && !Array.isArray(result.usage)
? (result.usage as Record<string, unknown>)
: undefined;
const hasResultUsageIteration =
resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;
const resultHasActiveUsage =
resultUsageRecord !== undefined &&
(hasResultUsageIteration ||
claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);
const resultTotalOnly =
resultUsageRecord !== undefined &&
!resultHasActiveUsage &&
claudeTotalProcessedTokens(resultUsageRecord) !== undefined;
const resultIterationSnapshot = resultUsageRecord
? normalizeClaudeActiveTokenUsage(
resultUsageRecord,
maxTokens,
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
)
: undefined;
const lastGoodUsage = context.lastKnownTokenUsage;
const usageSnapshot: ThreadTokenUsageSnapshot | undefined =
contextUsageSnapshot ??
(resultTotalOnly && lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: resultIterationSnapshot) ??
(lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(typeof accumulatedTotalProcessedTokens === "number" &&
Number.isFinite(accumulatedTotalProcessedTokens) &&
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
? {
totalProcessedTokens: accumulatedTotalProcessedTokens,
}
: {}),
}
: undefined);
const turnState = context.turnState;
if (!turnState) {
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
payload: {
usage: usageSnapshot,
},
providerRefs: {},
});
}
yield* emitThreadTokenUsage(context, usageSnapshot, {
rawMethod: "claude/result",
rawPayload: result ?? { status },
});
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
@@ -1611,21 +2050,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
items: [...turnState.items],
});
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
turnId: turnState.turnId,
payload: {
usage: usageSnapshot,
},
providerRefs: nativeProviderRefs(context),
});
}
yield* emitThreadTokenUsage(context, usageSnapshot, {
rawMethod: "claude/result",
rawPayload: result ?? { status },
});
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
@@ -1670,6 +2098,23 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const { event } = message;
if (event.type === "message_delta") {
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
return;
}
const snapshot = normalizeClaudeActiveTokenUsage(
event.usage,
context.lastKnownContextWindow,
context.lastKnownTotalProcessedTokens,
);
yield* emitThreadTokenUsage(context, snapshot, {
rawMethod: "claude/stream_event/message_delta",
rawPayload: message,
});
return;
}
if (event.type === "content_block_delta") {
if (
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
@@ -1932,6 +2377,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const [index, tool] = toolEntry;
const itemStatus = toolResult.isError ? "failed" : "completed";
const toolUseResult = readClaudeToolUseResult(message);
const toolData = {
toolName: tool.toolName,
input: tool.input,
@@ -2016,6 +2462,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
if (
!toolResult.isError &&
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
) {
yield* emitClaudeTaskPlanUpdated(context, {
toolUseId: tool.itemId,
rawMethod: "claude/user",
rawPayload: message,
});
}
context.inFlightTools.delete(index);
}
});
@@ -2036,6 +2493,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.turnState = {
turnId,
startedAt,
synthetic: true,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
@@ -2171,6 +2629,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "compact_boundary":
yield* emitThreadTokenUsage(
context,
compactBoundaryTokenUsageSnapshot(
message as unknown as Record<string, unknown>,
context.lastKnownContextWindow,
context.lastKnownTotalProcessedTokens,
),
{
rawMethod: "claude/system/compact_boundary",
rawPayload: message,
},
);
yield* offerRuntimeEvent({
...base,
type: "thread.state.changed",
@@ -2229,25 +2699,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "task_progress":
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
{
rawMethod: "claude/system/task_progress",
rawPayload: message,
},
);
yield* offerRuntimeEvent({
...base,
type: "task.progress",
@@ -2261,25 +2720,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
return;
case "task_notification":
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
{
rawMethod: "claude/system/task_notification",
rawPayload: message,
},
);
yield* offerRuntimeEvent({
...base,
type: "task.completed",
@@ -2669,6 +3117,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const inFlightTools = new Map<number, ToolInFlight>();
const claudeTasks = new Map<string, ClaudeTaskState>();
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
@@ -2969,6 +3418,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const caps = getClaudeModelCapabilities(modelSelection?.model);
const descriptors = getProviderOptionDescriptors({ caps });
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
const initialContextWindow = selectedClaudeContextWindow(modelSelection);
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
const fastModeSupported = descriptors.some(
@@ -3094,9 +3544,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs,
turns: [],
inFlightTools,
claudeTasks,
turnState: undefined,
lastKnownContextWindow: undefined,
lastKnownContextWindow: initialContextWindow,
lastKnownTokenUsage: undefined,
lastKnownTotalProcessedTokens: undefined,
lastAssistantUuid: resumeState?.resumeSessionAt,
lastThreadStartedId: undefined,
stopped: false,
@@ -3185,9 +3637,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
? input.modelSelection
: undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
// between user prompts) to prevent blocking the user's next turn.
// A sendTurn while a real turn is running is a steer: the message is
// queued into the live SDK agent loop and the work continues as the same
// turn — no synthetic turn boundary. Stale synthetic turns (from
// background agent responses between user prompts) are auto-closed
// instead, so they don't block the user's next turn.
const steeringTurnState =
context.turnState && context.turnState.synthetic !== true ? context.turnState : null;
if (context.turnState && steeringTurnState === null) {
yield* completeTurn(context, "completed");
}
@@ -3222,37 +3679,39 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const turnId = TurnId.make(yield* randomUUIDv4);
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
if (steeringTurnState === null) {
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
}
const message = yield* buildUserMessageEffect(input, {
fileSystem,
@@ -108,14 +108,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
@@ -142,14 +134,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
runtimeMode: "full-access",
});
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "fast",
serviceTier: "priority",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
attachments: [],
}),
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "priority",
});
}),
);
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "flex" },
],
),
attachments: [],
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "flex",
});
}).pipe(Effect.provide(customLayer));
});
+10 -11
View File
@@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import {
ProviderAdapterRequestError,
@@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
@@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.instanceId === boundInstanceId &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
...(serviceTier ? { serviceTier } : {}),
};
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
@@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const fastMode =
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
return yield* session.runtime
.sendTurn({
@@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
}
: {}),
...(fastMode === true ? { serviceTier: "fast" } : {}),
...(serviceTier ? { serviceTier } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
})
@@ -0,0 +1,104 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: [],
defaultReasoningEffort: "super-high",
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
defaultServiceTier: "flex",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
name: "Flex",
description: "Lower-cost asynchronous routing.",
},
],
supportedReasoningEfforts: [
{
description: "Maximum reasoning",
reasoningEffort: "super-high",
},
],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: [{ id: "super-high", label: "super-high", isDefault: true }],
currentValue: "super-high",
},
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard" },
{
id: "priority",
label: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
label: "Flex",
description: "Lower-cost asynchronous routing.",
isDefault: true,
},
],
currentValue: "flex",
},
]);
});
it("uses standard routing when the catalog has no default service tier", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: ["fast"],
defaultReasoningEffort: "medium",
defaultServiceTier: null,
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "1.5x speed, increased usage",
},
],
supportedReasoningEfforts: [],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard", isDefault: true },
{
id: "priority",
label: "Fast",
description: "1.5x speed, increased usage",
},
],
currentValue: "default",
},
]);
});
@@ -17,6 +17,7 @@ import type {
ServerProvider,
ServerProviderState,
ModelCapabilities,
ProviderOptionDescriptor,
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
@@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot {
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
none: "None",
minimal: "Minimal",
low: "Low",
@@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__Reasoning
xhigh: "Extra High",
};
const DEFAULT_SERVICE_TIER_ID = "default";
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
}
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account) return undefined;
if (account.type === "apiKey") return "OpenAI API Key";
@@ -93,46 +100,71 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
return account.email;
}
function mapCodexModelCapabilities(
export function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
reasoningEffort === model.defaultReasoningEffort
? {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
isDefault: true,
}
: {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
},
);
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
const serviceTiers =
model.serviceTiers && model.serviceTiers.length > 0
? model.serviceTiers
: (model.additionalSpeedTiers ?? []).map((id) => ({
id,
name: id === "fast" ? "Fast" : id,
description: "",
}));
const catalogDefaultServiceTier = serviceTiers.some(
(tier) => tier.id === model.defaultServiceTier,
)
? model.defaultServiceTier
: null;
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
const optionDescriptors: ProviderOptionDescriptor[] = [];
if (reasoningOptions.length > 0) {
optionDescriptors.push({
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
});
}
if (serviceTiers.length > 0) {
optionDescriptors.push({
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{
id: DEFAULT_SERVICE_TIER_ID,
label: "Standard",
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
},
...serviceTiers.map((tier) => ({
id: tier.id,
label: tier.name,
...(tier.description ? { description: tier.description } : {}),
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
})),
],
currentValue: defaultServiceTier,
});
}
return createModelCapabilities({
optionDescriptors: [
...(reasoningOptions.length > 0
? [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select" as const,
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
},
]
: []),
...(supportsFastMode
? [
{
id: "fastMode",
label: "Fast Mode",
type: "boolean" as const,
},
]
: []),
],
optionDescriptors,
});
}
@@ -13,6 +13,7 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { createModelSelection } from "@t3tools/shared/model";
import {
@@ -232,6 +233,82 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-steer-thread");
// Keep the first prompt in flight long enough for the steer to land.
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.takeUntil((event) => event.type === "turn.completed"),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "run 5 commands",
attachments: [],
})
.pipe(Effect.forkChild);
// Poll until the first prompt is in flight — sendTurn binds the active
// turn id before prompting. The mock agent runs on the real clock, so
// each TestClock.adjust just provides the scheduler hops for its stdio
// responses to land.
yield* Effect.gen(function* () {
for (let attempt = 0; attempt < 200; attempt += 1) {
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
if (session?.activeTurnId !== undefined) {
return;
}
yield* TestClock.adjust("10 millis");
}
throw new Error("Timed out waiting for the first prompt to be in flight.");
});
// Steer: a second sendTurn while the first prompt is still in flight
// continues the same turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
attachments: [],
});
const firstTurn = yield* Fiber.join(firstTurnFiber);
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the superseded first prompt
// resolving must not settle the merged turn.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
+142 -106
View File
@@ -132,6 +132,10 @@ interface CursorSessionContext {
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
stopped: boolean;
}
@@ -754,6 +758,7 @@ export function makeCursorAdapter(
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
stopped: false,
};
@@ -882,121 +887,152 @@ export function makeCursorAdapter(
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
// A sendTurn while a prompt is in flight is a steer: the agent folds
// the new prompt into the ongoing work, so the active turn id is
// reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; the matching
// decrement is the `ensuring` below.
ctx.promptsInFlight += 1;
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
});
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
});
}
}
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
});
}
}
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
if (turnRecord) {
turnRecord.items.push({ prompt: promptParts, result });
} else {
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another is
// in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
}).pipe(
Effect.ensuring(
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
});
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
+190 -136
View File
@@ -107,6 +107,10 @@ interface GrokSessionContext {
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
currentModelId: string | undefined;
stopped: boolean;
}
@@ -555,6 +559,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
};
@@ -664,150 +669,199 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
// A sendTurn while a prompt is in flight is a steer: the agent
// folds the new prompt into the ongoing work, so the active turn
// id is reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(
input.attachments ?? [],
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
}
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}).pipe(
Effect.tapCause(() =>
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}),
);
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
return yield* Effect.gen(function* () {
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === prepared.turnId
? {
...turn,
items: [...turn.items, { prompt: prepared.promptParts, result }],
}
: turn,
)
: [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another
// is in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
ctx.turns = [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
}).pipe(
Effect.ensuring(
Effect.sync(() => {
const liveCtx = sessions.get(input.threadId);
if (liveCtx) {
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
}
}),
),
);
});
@@ -395,6 +395,85 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
// Steer: OpenCode queues the prompt into the busy session, so the
// active turn id is reused instead of opening a new turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
assert.equal(runtimeMock.state.promptCalls.length, 2);
}),
);
it.effect("keeps the running turn when a steer prompt fails", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer-failure");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
runtimeMock.state.promptAsyncError = new Error("steer failed");
const error = yield* adapter
.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
})
.pipe(Effect.flip);
// The original turn keeps running — only the steer prompt failed.
assert.equal(error._tag, "ProviderAdapterRequestError");
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
}),
);
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
const instanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
@@ -1151,7 +1151,11 @@ export function makeOpenCodeAdapter(
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = ensureSessionContext(sessions, input.threadId);
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
// A sendTurn while a turn is active is a steer: OpenCode queues the
// prompt into the busy session and the work continues as one turn, so
// the active turn id is reused instead of opening a new turn.
const steeringTurnId = context.activeTurnId;
const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
const modelSelection =
input.modelSelection ??
(context.session.model
@@ -1206,14 +1210,16 @@ export function makeOpenCodeAdapter(
{ clearLastError: true },
);
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
if (steeringTurnId === undefined) {
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
}
yield* runOpenCodeSdk("session.promptAsync", () =>
context.client.session.promptAsync({
@@ -1225,35 +1231,38 @@ export function makeOpenCodeAdapter(
}),
).pipe(
Effect.mapError(toRequestError),
// On failure: clear active-turn state, flip the session back to ready
// with lastError set, emit turn.aborted, then let the typed error
// propagate. We don't need to rebuild the error here — `toRequestError`
// already produced the right shape.
// On failure of a fresh turn: clear active-turn state, flip the
// session back to ready with lastError set, emit turn.aborted, then
// let the typed error propagate. We don't need to rebuild the error
// here — `toRequestError` already produced the right shape. A failed
// steer leaves the still-running original turn untouched.
Effect.tapError((requestError) =>
Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
steeringTurnId !== undefined
? Effect.void
: Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
),
);
@@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
]);
});
it.effect("does not run provider probes during layer construction", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const initialProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-06-10T00:00:00.000Z",
version: null,
message: "Checking Codex provider status.",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshCalls = yield* Ref.make(0);
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(initialProvider),
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
Effect.andThen(Effect.never),
),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
}).pipe(Effect.provide(runtimeServices));
}),
);
it("persists merged provider snapshots for the providers that were refreshed", () => {
const previousProviders = [
{
@@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const providers = yield* registry.getProviders;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
}
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
);
@@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// instance and rebuild it so a fresh probe runs with the new binary.
// This test drives the real settings stream → registry reconcile →
// aggregator sync pipeline and asserts that `getProviders` reflects
// the new probe's outcome. If `syncLiveSources` stops awaiting the
// rebuilt instance's refresh (previous bug mode), the aggregator
// keeps the old snapshot and this test fails.
// the new background probe's outcome.
//
it.effect("re-probes when settings change the codex binaryPath", () =>
Effect.gen(function* () {
@@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// the two probe runs is `checkedAt` — each probe stamps a
// fresh DateTime, so we capture it and assert it advances
// after the settings mutation.
const initialProviders = yield* registry.getProviders;
let initialProviders = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
"error";
attempts += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
initialProviders = yield* registry.getProviders;
}
const initialCodex = initialProviders.find(
(provider) => provider.instanceId === "codex",
);
@@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// envelope changed because `binaryPath` differs → `entryEqual`
// is false). The registry's `Stream.runForEach(
// instanceRegistry.streamChanges, () => syncLiveSources)`
// fires `syncLiveSources`, which subscribes + awaits a fresh
// refresh on the rebuilt instance.
// fires `syncLiveSources`, which subscribes and launches a fresh
// background refresh on the rebuilt instance.
yield* serverSettings.updateSettings({
providers: {
codex: { enabled: true, binaryPath: secondMissing },
@@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
for (let attempts = 0; attempts < 60; attempts += 1) {
const providers = yield* registry.getProviders;
const codex = providers.find((provider) => provider.instanceId === "codex");
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
if (
codex !== undefined &&
codex.status === "error" &&
codex.checkedAt !== initialCheckedAt
) {
return providers;
}
yield* TestClock.adjust("50 millis");
@@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect(
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - force-refresh each newly-added/rebuilt instance and feed the
* result directly into `providersRef`, bypassing the PubSub
* attachment race that otherwise drops the initial probe;
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - prune `providersRef` of instances that no longer exist.
*
* Initial refreshes are awaited in parallel rather than forked, so
* callers (layer build; `streamChanges` watcher) see fully-probed
* state on return. This matters for layer build in particular:
* consumers reading `getProviders` immediately after layer build
* expect the probe to have already landed.
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
@@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect(
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream BEFORE kicking off refreshes — if the driver's
// own initial probe (line 140 in `makeManagedServerProvider`)
// wins the refreshSemaphore race, its PubSub publish must land
// in an active subscriber or the result is dropped.
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Force-refresh every new/rebuilt instance in parallel and wait
// for them all to complete. The refresh's result is piped
// directly into `syncProvider`, so `providersRef` is populated
// deterministically by the time this block returns — regardless
// of PubSub subscription timing. Failures are logged and
// swallowed so one bad driver can't wedge the whole registry.
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
@@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect(
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync: subscribe + kick off refreshes for every instance
// present at boot. Run synchronously so consumers pulling immediately
// after the layer build see the correct aggregator state.
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
@@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => {
Effect.forkChild,
);
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(checkCalls), 1);
yield* Deferred.succeed(releaseCheck, undefined);
@@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
+8
View File
@@ -87,6 +87,12 @@ import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
// already closes the websocket gracefully. Do not add an artificial drain before
// those finalizers get a chance to run.
const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
if (typeof Bun !== "undefined") {
@@ -116,6 +122,7 @@ const HttpServerLive = Layer.unwrap(
return BunHttpServer.layer({
port: config.port,
...(config.host ? { hostname: config.host } : {}),
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
@@ -125,6 +132,7 @@ const HttpServerLive = Layer.unwrap(
return NodeHttpServer.layer(NodeHttp.createServer, {
host: config.host,
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
});
}
}),
@@ -32,7 +32,7 @@ function makeFakeCodexBinary(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -52,7 +52,7 @@ function makeFakeCodexBinary(
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_service_tier=""',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
@@ -65,9 +65,11 @@ function makeFakeCodexBinary(
" fi",
' if [ "$1" = "--config" ]; then',
" shift",
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
' seen_fast_service_tier="1"',
" fi",
' case "$1" in',
" service_tier=*)",
' seen_service_tier="$1"',
" ;;",
" esac",
' case "$1" in',
" model_reasoning_effort=*)",
' seen_reasoning_effort="$1"',
@@ -93,10 +95,10 @@ function makeFakeCodexBinary(
"fi",
]
: []),
...(input.requireFastServiceTier
...(input.requireServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
`if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
` exit 5`,
"fi",
]
@@ -161,7 +163,7 @@ function withFakeCodexEnv<A, E, R>(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
);
it.effect(
"forwards codex fast mode and non-default reasoning effort into codex exec config",
"forwards codex service tier and non-default reasoning effort into codex exec config",
() =>
withFakeCodexEnv(
{
@@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
subject: "Add important change",
body: "",
}),
requireFastServiceTier: true,
requireServiceTier: "priority",
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
@@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
}),
),
@@ -32,10 +32,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "./TextGenerationUtils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
const command = ChildProcess.make(
codexConfig.binaryPath || "codex",
[
@@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
? ["--config", `service_tier="fast"`]
: []),
...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
+14
View File
@@ -68,6 +68,17 @@ export interface GitStatusDetails {
aheadOfDefaultCount: number;
}
export interface GitRemoteStatusDetails {
isRepo: boolean;
isDefaultBranch: boolean;
branch: string | null;
upstreamRef: string | null;
hasUpstream: boolean;
aheadCount: number;
behindCount: number;
aheadOfDefaultCount: number;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
@@ -162,6 +173,9 @@ export interface GitVcsDriverShape {
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsRemote: (
cwd: string,
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
@@ -155,6 +155,67 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("reports remote divergence without reading working-tree details", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/remote-status"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]);
yield* writeTextFile(cwd, "untracked.txt", "local-only\n");
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
assert.equal(status.isRepo, true);
assert.equal(status.branch, "feature/remote-status");
assert.equal(status.hasUpstream, true);
assert.equal(status.aheadCount, 0);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
assert.notProperty(status, "workingTree");
assert.notProperty(status, "hasWorkingTreeChanges");
}),
);
it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const upstream = yield* makeTmpDir("git-vcs-driver-upstream-");
yield* initRepoWithCommit(cwd);
yield* git(origin, ["init", "--bare"]);
yield* git(upstream, ["init", "--bare"]);
yield* git(cwd, ["branch", "-M", "main"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["remote", "add", "upstream", upstream]);
yield* git(cwd, ["push", "origin", "main"]);
yield* git(cwd, ["push", "upstream", "main"]);
yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
yield* git(cwd, ["checkout", "-b", "release"]);
yield* writeTextFile(cwd, "release.txt", "release\n");
yield* git(cwd, ["add", "release.txt"]);
yield* git(cwd, ["commit", "-m", "release commit"]);
yield* git(cwd, ["push", "-u", "upstream", "release"]);
yield* git(cwd, [
"symbolic-ref",
"refs/remotes/upstream/HEAD",
"refs/remotes/upstream/release",
]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
assert.equal(status.branch, "release");
assert.equal(status.upstreamRef, "upstream/release");
assert.equal(status.isDefaultBranch, false);
}),
);
it.effect("disables SSH askpass for background upstream status fetches", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+95 -2
View File
@@ -71,6 +71,16 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
behindCount: 0,
aheadOfDefaultCount: 0,
});
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
isRepo: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
});
type TraceTailState = {
processedChars: number;
@@ -1154,6 +1164,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
const branchResult = yield* executeGit(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
{ allowNonZeroExit: true },
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
if (branchResult === null) {
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
}
if (branchResult.exitCode !== 0) {
const stderr = branchResult.stderr.trim();
return yield* createGitCommandError(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
stderr || "git branch lookup failed",
);
}
const branchValue = branchResult.stdout.trim();
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
const upstream = yield* resolveCurrentUpstream(cwd);
const upstreamRef = upstream?.upstreamRef ?? null;
let aheadCount = 0;
let behindCount = 0;
if (upstreamRef) {
const divergence = yield* executeGit(
"GitVcsDriver.statusDetailsRemote.divergence",
cwd,
["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`],
{ allowNonZeroExit: true },
);
if (divergence.exitCode === 0) {
const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/);
const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10);
const parsedBehind = Number.parseInt(behindRaw ?? "0", 10);
aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;
behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;
}
} else if (branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.orElseSucceed(() => 0),
);
}
const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin");
const isDefaultBranch =
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master")));
const aheadOfDefaultCount =
branch && !isDefaultBranch
? upstreamRef === null
? aheadCount
: yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0))
: 0;
return {
isRepo: true,
isDefaultBranch,
branch,
upstreamRef,
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
aheadOfDefaultCount,
};
});
const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) {
const branchRecency = yield* executeGit(
"GitVcsDriver.readBranchRecency",
@@ -1356,6 +1438,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
},
);
const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn(
"statusDetailsRemote",
)(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
Effect.ignoreCause({ log: true }),
);
return yield* readStatusDetailsRemote(cwd);
});
const status: GitVcsDriver.GitVcsDriverShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
@@ -1402,7 +1494,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const stagedPatch = yield* runGitStdoutWithOptions(
"GitVcsDriver.prepareCommitContext.stagedPatch",
cwd,
["diff", "--cached", "--patch", "--minimal"],
["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"],
{
maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
@@ -1639,7 +1731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
runGitStdoutWithOptions(
"GitVcsDriver.readRangeContext.diffPatch",
cwd,
["diff", "--patch", "--minimal", range],
["diff", "--no-ext-diff", "--patch", "--minimal", range],
{
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
appendTruncationMarker: true,
@@ -2302,6 +2394,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
status,
statusDetails,
statusDetailsLocal,
statusDetailsRemote,
prepareCommitContext,
commit,
pushCurrentBranch,
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type {
VcsStatusLocalResult,
VcsStatusRemoteResult,
@@ -310,6 +311,48 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
const scope = yield* Scope.make();
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
),
(event) =>
event._tag === "snapshot"
? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(snapshotDeferred);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
yield* TestClock.adjust(Duration.seconds(59));
assert.equal(state.remoteStatusCalls, 1);
yield* TestClock.adjust(Duration.seconds(1));
yield* Effect.yieldNow;
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.remoteInvalidationCalls, 1);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
});
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
assert.equal(
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
+15 -2
View File
@@ -257,6 +257,7 @@ export const layer = Layer.effect(
const makeRemoteRefreshLoop = (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) => {
return Effect.gen(function* () {
const consecutiveFailuresRef = yield* Ref.make(0);
@@ -289,6 +290,15 @@ export const layer = Layer.effect(
return nextDelay;
});
if (!refreshImmediately) {
const configuredInterval = yield* automaticRemoteRefreshInterval;
yield* Effect.sleep(
Duration.isZero(configuredInterval)
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
: configuredInterval,
);
}
return yield* refreshRemoteStatusIfEnabled.pipe(
Effect.repeat(
Schedule.identity<Duration.Duration>().pipe(
@@ -303,6 +313,7 @@ export const layer = Layer.effect(
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
@@ -315,7 +326,7 @@ export const layer = Layer.effect(
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
@@ -363,11 +374,13 @@ export const layer = Layer.effect(
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
const cachedStatus = yield* getCachedStatus(cwd);
const initialRemote = cachedStatus?.remote?.value ?? null;
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
+2 -1
View File
@@ -22,6 +22,7 @@
"hooks": "~/hooks"
},
"registries": {
"@coss": "https://coss.com/ui/r/{name}.json"
"@coss": "https://coss.com/ui/r/{name}.json",
"@spell": "https://spell.sh/r/{name}.json"
}
}
+1 -6
View File
@@ -48,6 +48,7 @@
background: #ffffff;
color: #262626;
font-family:
"DM Sans Variable",
"DM Sans",
-apple-system,
BlinkMacSystemFont,
@@ -83,12 +84,6 @@
object-fit: contain;
}
</style>
<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:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
rel="stylesheet"
/>
<title>T3 Code (Alpha)</title>
</head>
<body>
+5
View File
@@ -21,6 +21,8 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@effect/atom-react": "catalog:",
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "3.0.0-beta.44",
"@lexical/react": "^0.41.0",
@@ -41,6 +43,9 @@
"react": "19.2.6",
"react-dom": "19.2.6",
"react-markdown": "^10.1.0",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
@@ -1,11 +1,12 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, GitBranchIcon, SearchIcon } from "lucide-react";
import {
useCallback,
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useOptimistic,
useRef,
@@ -37,7 +38,6 @@ import {
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxListVirtualized,
ComboboxPopup,
ComboboxStatus,
@@ -281,7 +281,6 @@ export function BranchToolbarBranchSelector({
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchRefState.data?.totalCount ?? 0;
const branchStatusText = isInitialBranchesLoadPending
? "Loading refs..."
@@ -421,7 +420,9 @@ export function BranchToolbarBranchSelector({
[branchRefTarget],
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const branchListScrollElementRef = useRef<HTMLElement | null>(null);
const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
const fetchNextBranchPage = useCallback(() => {
if (!hasNextPage || isFetchingNextPage) {
return;
@@ -451,44 +452,61 @@ export function BranchToolbarBranchSelector({
fetchNextBranchPage();
}, [fetchNextBranchPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListRef = useRef<LegendListRef | null>(null);
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
const updateBranchListScrollFades = useCallback(() => {
const scrollElement = branchListRef.current?.getScrollableNode?.();
if (!(scrollElement instanceof HTMLElement)) {
return;
}
branchListScrollElementRef.current = scrollElement;
const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
setShowTopBranchScrollFade(scrollElement.scrollTop > 1);
setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
}, []);
useEffect(() => {
if (isBranchMenuOpen) {
return;
}
setShowTopBranchScrollFade(false);
setShowBottomBranchScrollFade(false);
}, [isBranchMenuOpen]);
useLayoutEffect(() => {
if (!isBranchMenuOpen) {
return;
}
setShowTopBranchScrollFade(false);
setShowBottomBranchScrollFade(filteredBranchPickerItems.length > 8);
let nestedFrame = 0;
const frame = requestAnimationFrame(() => {
updateBranchListScrollFades();
nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
});
return () => {
cancelAnimationFrame(frame);
cancelAnimationFrame(nestedFrame);
};
}, [
deferredTrimmedBranchQuery,
filteredBranchPickerItems.length,
isBranchMenuOpen,
updateBranchListScrollFades,
]);
useEffect(() => {
if (!isBranchMenuOpen) {
return;
}
if (shouldVirtualizeBranchList) {
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
} else {
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement || !isBranchMenuOpen) {
return;
}
const handleScroll = () => {
maybeFetchNextBranchPage();
};
scrollElement.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
return () => {
scrollElement.removeEventListener("scroll", handleScroll);
};
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
useEffect(() => {
if (shouldVirtualizeBranchList) return;
maybeFetchNextBranchPage();
}, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
}, [refs.length, maybeFetchNextBranchPage]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
@@ -504,6 +522,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className="pe-2"
onClick={() => {
if (!prReference || !onCheckoutPullRequestRequest) {
return;
@@ -533,6 +552,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className="pe-1.5"
onClick={() => createRef(trimmedBranchQuery)}
>
<span className="truncate">Create new ref &quot;{trimmedBranchQuery}&quot;</span>
@@ -560,10 +580,11 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className="pe-1.5"
onClick={() => selectBranch(refName)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="min-w-0 flex-1 truncate">{itemValue}</span>
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
</div>
</ComboboxItem>
@@ -575,7 +596,7 @@ export function BranchToolbarBranchSelector({
items={branchPickerItems}
filteredItems={filteredBranchPickerItems}
autoHighlight
virtualized={shouldVirtualizeBranchList}
virtualized
onItemHighlighted={(_value, eventDetails) => {
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
return;
@@ -594,48 +615,64 @@ export function BranchToolbarBranchSelector({
className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)}
disabled={isInitialBranchesLoadPending || isBranchActionPending}
>
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="shrink-0" />
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-80">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search refs..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No refs found.</ComboboxEmpty>
{shouldVirtualizeBranchList ? (
<ComboboxListVirtualized>
<LegendList<string>
ref={branchListRef}
data={filteredBranchPickerItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextBranchPage();
}
}}
style={{ maxHeight: "14rem" }}
<ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
<div className="shrink-0 px-3 pt-2.5">
<div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
<SearchIcon
aria-hidden="true"
className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
/>
</ComboboxListVirtualized>
) : (
<ComboboxList ref={setBranchListRef} className="max-h-56">
{filteredBranchPickerItems.map((itemValue, index) =>
renderPickerItem(itemValue, index),
)}
</ComboboxList>
)}
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
<ComboboxInput
className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm"
placeholder="Search refs..."
showTrigger={false}
size="sm"
unstyled
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<ComboboxEmpty>No refs found.</ComboboxEmpty>
<div className="relative min-h-0 w-full max-h-56 flex-1 overflow-hidden">
<ComboboxListVirtualized className="size-full min-w-0 p-0">
<LegendList<string>
ref={branchListRef}
data={filteredBranchPickerItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextBranchPage();
}
}}
onLayout={() => {
updateBranchListScrollFades();
maybeFetchNextBranchPage();
}}
onScroll={() => {
updateBranchListScrollFades();
maybeFetchNextBranchPage();
}}
className={cn(
"scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 pt-2 pb-1 [--fade-size:1.5rem]",
showTopBranchScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]",
showBottomBranchScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]",
)}
style={{ maxHeight: "14rem" }}
/>
</ComboboxListVirtualized>
</div>
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</div>
</ComboboxPopup>
</Combobox>
);
@@ -24,6 +24,7 @@ vi.mock("../localApi", () => ({
}));
import ChatMarkdown from "./ChatMarkdown";
import { serializeTableElementToCsv, serializeTableElementToMarkdown } from "../markdown-clipboard";
describe("ChatMarkdown", () => {
afterEach(() => {
@@ -134,8 +135,550 @@ describe("ChatMarkdown", () => {
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", "https://openai.com/docs");
await expect.element(link).toHaveAttribute("target", "_blank");
const favicon = link.element().querySelector<HTMLElement>(".chat-markdown-link-favicon");
const leading = link.element().querySelector<HTMLElement>(".chat-markdown-link-leading");
expect(favicon).not.toBeNull();
expect(leading).not.toBeNull();
expect(leading?.contains(favicon)).toBe(true);
expect(getComputedStyle(leading!).display).toBe("inline");
expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap");
expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline");
expect(leading?.textContent).toBe("O");
expect(link.element().textContent).toBe("OpenAI");
expect(getComputedStyle(link.element()).textDecorationLine).toBe("none");
expect(link.element().querySelector("img, svg")?.getBoundingClientRect().width).toBe(14);
await link.hover();
expect(getComputedStyle(link.element()).backgroundImage).not.toBe("none");
await expect.element(page.getByText("https://openai.com/docs")).toBeVisible();
} finally {
await screen.unmount();
}
});
it("keeps a favicon with the leading segment of a wrapping URL", async () => {
const url = "https://github.com/pingdotgg/t3code/pull/3017/changes";
const screen = await render(
<div style={{ width: 180 }}>
<ChatMarkdown text={`[${url}](${url})`} cwd="/repo/project" />
</div>,
);
try {
const link = page.getByRole("link", { name: url });
const leading = link.element().querySelector<HTMLElement>(".chat-markdown-link-leading");
const favicon = link.element().querySelector<HTMLElement>(".chat-markdown-link-favicon");
expect(leading).not.toBeNull();
expect(favicon).not.toBeNull();
expect(leading?.contains(favicon)).toBe(true);
expect(leading?.textContent).toBe("https://");
expect(getComputedStyle(leading!).display).toBe("inline");
expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap");
expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline");
expect(link.element().textContent).toBe(url);
expect(link.element().querySelectorAll("wbr").length).toBeGreaterThan(0);
const markdownRoot = link.element().closest<HTMLElement>(".chat-markdown");
expect(markdownRoot).not.toBeNull();
expect(markdownRoot!.scrollWidth).toBeLessThanOrEqual(markdownRoot!.clientWidth);
} finally {
await screen.unmount();
}
});
it("renders file links with the shared file tag chip treatment", async () => {
const screen = await render(
<ChatMarkdown text="[package.json](path/to/package.json)" cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "package.json" });
await expect.element(link).toHaveClass(/chat-markdown-file-link/);
const element = document.querySelector<HTMLElement>(".chat-markdown-file-link");
expect(element?.querySelector("img, svg")).not.toBeNull();
expect(getComputedStyle(element!).display).toBe("inline-flex");
expect(getComputedStyle(element!).textDecorationLine).toBe("none");
expect(getComputedStyle(element!).borderStyle).toBe("solid");
expect(getComputedStyle(element!).userSelect).not.toBe("none");
} finally {
await screen.unmount();
}
});
it("renders sanitized details with the design-system collapsible", async () => {
const source = [
"<details open>",
"<summary>Expandable details section</summary>",
"",
"This content includes **formatted text**.",
"",
'<span title="native tooltip should be stripped">Safe inline HTML</span>',
"<script>window.__unsafeMarkdownScript = true</script>",
"</details>",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const details = document.querySelector<HTMLElement>("[data-markdown-details]");
const trigger = page.getByRole("button", { name: "Expandable details section" });
expect(details).not.toBeNull();
expect(details?.tagName).toBe("DIV");
await expect.element(trigger).toHaveAttribute("aria-expanded", "true");
expect(details?.querySelector("strong")?.textContent).toBe("formatted text");
expect(details?.querySelector("script")).toBeNull();
expect(details?.querySelector("[title]")).toBeNull();
await trigger.click();
await expect.element(trigger).toHaveAttribute("aria-expanded", "false");
await trigger.click();
await expect.element(trigger).toHaveAttribute("aria-expanded", "true");
} finally {
await screen.unmount();
}
});
it("renders footnotes as same-document references", async () => {
const source = [
"A claim with supporting context.[^context]",
"",
"[^context]: Supporting **footnote text**.",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const reference = document.querySelector<HTMLAnchorElement>(
'.chat-markdown a[data-footnote-ref=""]',
);
const footnotes = document.querySelector<HTMLElement>(
".chat-markdown section[data-footnotes]",
);
expect(reference).not.toBeNull();
expect(reference?.getAttribute("href")).toMatch(/^#user-content-fn-/);
expect(reference?.hasAttribute("target")).toBe(false);
expect(footnotes).not.toBeNull();
expect(footnotes?.querySelector("strong")?.textContent).toBe("footnote text");
expect(footnotes?.querySelector<HTMLAnchorElement>("a[data-footnote-backref]")?.target).toBe(
"",
);
} finally {
await screen.unmount();
}
});
it("navigates hash links within the clicked markdown message", async () => {
const source = [
"A claim with supporting context.[^context]",
"",
"[^context]: Supporting footnote text.",
].join("\n");
const originalUrl = window.location.href;
const scrollIntoView = vi
.spyOn(HTMLElement.prototype, "scrollIntoView")
.mockImplementation(() => undefined);
const screen = await render(
<div>
<ChatMarkdown text={source} cwd="/repo/project" />
<ChatMarkdown text={source} cwd="/repo/project" />
</div>,
);
try {
const markdownRoots = document.querySelectorAll<HTMLElement>(".chat-markdown");
const secondRoot = markdownRoots[1];
const secondReference =
secondRoot?.querySelector<HTMLAnchorElement>('a[data-footnote-ref=""]');
const secondFootnote = secondRoot?.querySelector<HTMLElement>(
"section[data-footnotes] li[id]",
);
expect(secondReference).not.toBeNull();
expect(secondFootnote).not.toBeNull();
secondReference?.click();
expect(scrollIntoView).toHaveBeenCalledTimes(1);
expect(scrollIntoView.mock.instances[0]).toBe(secondFootnote);
expect(window.location.hash).toBe(secondReference?.hash);
const secondBackref = secondRoot?.querySelector<HTMLAnchorElement>(
"a[data-footnote-backref]",
);
expect(secondBackref).not.toBeNull();
secondBackref?.click();
const secondReferenceTarget = secondReference?.closest<HTMLElement>("[id]");
expect(scrollIntoView).toHaveBeenCalledTimes(2);
expect(scrollIntoView.mock.instances[1]).toBe(secondReferenceTarget);
} finally {
scrollIntoView.mockRestore();
window.history.replaceState(window.history.state, "", originalUrl);
await screen.unmount();
}
});
describe("code block chrome", () => {
it("shows icon-only language titles, text fallbacks, and filename overrides", async () => {
const source = [
"```ts",
"const a = 1;",
"```",
"",
'```ts title="src/main.ts"',
"const b = 2;",
"```",
"",
"```text",
"plain",
"```",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const titles = [...document.querySelectorAll(".chat-markdown-codeblock-title")];
expect(titles).toHaveLength(3);
// Language with a known icon: icon XOR text — never the redundant pair.
const languageOnly = titles[0]!;
const hasIcon = languageOnly.querySelector("img") != null;
const hasText = (languageOnly.textContent ?? "").includes("ts");
expect(hasIcon || hasText).toBe(true);
expect(hasIcon && hasText).toBe(false);
if (hasIcon) {
const languageTrigger = page.getByLabelText("Language: ts").first();
await languageTrigger.hover();
await vi.waitFor(() => {
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
expect(tooltip?.textContent).toContain("ts");
});
}
// Explicit filename: text always shown.
expect(titles[1]!.textContent).toBe("src/main.ts");
// Unknown language: no icon attempt, text label.
expect(titles[2]!.querySelector("img")).toBeNull();
expect(titles[2]!.textContent).toBe("text");
} finally {
await screen.unmount();
}
});
it("toggles line wrapping per block", async () => {
const screen = await render(
<ChatMarkdown text={'```ts\nconst x = "long";\n```'} cwd="/repo/project" />,
);
try {
const block = document.querySelector(".chat-markdown-codeblock");
expect(block?.getAttribute("data-wrap")).toBe("false");
const toggle = page.getByRole("button", { name: "Wrap lines" });
await expect.element(toggle).not.toHaveAttribute("title");
await toggle.hover();
await vi.waitFor(() => {
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
expect(tooltip?.textContent).toContain("Wrap lines");
});
await toggle.click();
expect(block?.getAttribute("data-wrap")).toBe("true");
await page.getByRole("button", { name: "Disable line wrap" }).click();
expect(block?.getAttribute("data-wrap")).toBe("false");
} finally {
await screen.unmount();
}
});
});
it("scrolls wide tables horizontally instead of letter-wrapping cells", async () => {
const header = `| ${Array.from({ length: 8 }, (_, i) => `ColumnHeading${i}`).join(" | ")} |`;
const separator = `| ${Array.from({ length: 8 }, () => "---").join(" | ")} |`;
const row = `| ${Array.from({ length: 8 }, () => "[email protected]").join(" | ")} |`;
const screen = await render(
<ChatMarkdown text={[header, separator, row].join("\n")} cwd="/repo/project" />,
);
try {
const viewport = document.querySelector(
'.chat-markdown-table-container [data-slot="scroll-area-viewport"]',
);
expect(viewport).not.toBeNull();
expect(viewport!.querySelector("table")).not.toBeNull();
// Content exceeds the container — the scroll-fade viewport scrolls
// horizontally rather than squishing columns.
expect(viewport!.scrollWidth).toBeGreaterThan(viewport!.clientWidth);
// And cells keep their longest word intact instead of breaking mid-word.
const cell = viewport!.querySelector("td");
expect(cell!.getBoundingClientRect().width).toBeGreaterThan(100);
} finally {
await screen.unmount();
}
});
describe("table chrome", () => {
const longCell =
"This service has been experiencing intermittent latency spikes during peak traffic hours and the on-call team is investigating.";
it("truncates cells by default and expands them from the footer toggle", async () => {
const source = ["| Name | Notes |", "| --- | --- |", `| api | ${longCell} |`].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const container = document.querySelector(".chat-markdown-table-container");
expect(container?.getAttribute("data-expanded")).toBe("false");
const noteCell = [...document.querySelectorAll(".chat-markdown td")].at(-1)!;
expect(getComputedStyle(noteCell).whiteSpace).toBe("nowrap");
expect(noteCell.scrollWidth).toBeGreaterThan(noteCell.clientWidth);
const expandButton = page.getByRole("button", { name: "Expand table cells" });
await expect.element(expandButton).not.toHaveAttribute("title");
await expandButton.hover();
await vi.waitFor(() => {
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
expect(tooltip?.textContent).toContain("Expand table cells");
});
await expandButton.click();
expect(container?.getAttribute("data-expanded")).toBe("true");
expect(getComputedStyle(noteCell).whiteSpace).not.toBe("nowrap");
await page.getByRole("button", { name: "Collapse table cells" }).click();
expect(container?.getAttribute("data-expanded")).toBe("false");
const copyButton = page.getByRole("button", { name: "Copy table" });
await expect.element(copyButton).not.toHaveAttribute("title");
await copyButton.hover();
await vi.waitFor(() => {
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
expect(tooltip?.textContent).toContain("Copy table");
});
expect(document.querySelector(".chat-markdown [title]")).toBeNull();
} finally {
await screen.unmount();
}
});
it("retains column widths when cells expand", async () => {
const source = [
"| ID | Owner | Status | Priority | Region | Summary | Long Description | Metrics | Payload | Notes |",
"| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |",
'| 1001 | Ada Lovelace | Active | High | us-west-2 | Payment workflow migration | This cell has enough text to wrap across several lines when expanded without shrinking its column. | Requests: 128,440; Error rate: 0.04%; P95: 212ms | `{ "feature": "billing", "version": 3 }` | Needs post-release monitoring for 24 hours. |',
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const viewport = document.querySelector(
'.chat-markdown-table-container [data-slot="scroll-area-viewport"]',
)!;
const table = viewport.querySelector("table")!;
const collapsedWidths = [...table.querySelectorAll("thead th")].map(
(cell) => cell.getBoundingClientRect().width,
);
expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
await page.getByRole("button", { name: "Expand table cells" }).click();
const expandedWidths = [...table.querySelectorAll("thead th")].map(
(cell) => cell.getBoundingClientRect().width,
);
expect(expandedWidths).toHaveLength(collapsedWidths.length);
expandedWidths.forEach((width, index) => {
expect(width).toBeGreaterThanOrEqual(collapsedWidths[index]! - 1);
});
expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
} finally {
await screen.unmount();
}
});
it("exports tables as markdown and csv", async () => {
const source = [
"| Name | Count |",
"| --- | ---: |",
'| widget, "deluxe" | 2 |',
"| plain | 1 |",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const table = document.querySelector(".chat-markdown table")!;
expect(serializeTableElementToMarkdown(table)).toBe(
["| Name | Count |", "| --- | ---: |", '| widget, "deluxe" | 2 |', "| plain | 1 |"].join(
"\n",
),
);
expect(serializeTableElementToCsv(table)).toBe(
["Name,Count", '"widget, ""deluxe""",2', "plain,1"].join("\n"),
);
} finally {
await screen.unmount();
}
});
});
describe("copying rendered markdown", () => {
function copySelectedMarkdown(): { text: string; html: string } {
const root = document.querySelector(".chat-markdown");
if (!root) throw new Error("chat-markdown root not rendered");
const selection = window.getSelection();
if (!selection) throw new Error("selection unavailable");
selection.removeAllRanges();
const range = document.createRange();
range.selectNodeContents(root);
selection.addRange(range);
const clipboardData = new DataTransfer();
root.dispatchEvent(
new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true }),
);
selection.removeAllRanges();
return {
text: clipboardData.getData("text/plain"),
html: clipboardData.getData("text/html"),
};
}
it("round-trips links, emphasis, and inline code", async () => {
const screen = await render(
<ChatMarkdown
text="Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`."
cwd="/repo/project"
/>,
);
try {
const { text, html } = copySelectedMarkdown();
expect(text).toBe(
"Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`.",
);
expect(html).toContain('href="https://anthropic.com"');
} finally {
await screen.unmount();
}
});
it("round-trips block structure: headings, lists, quotes, and fences", async () => {
const source = [
"## Heading",
"",
"- first",
"- second",
" - nested",
"",
"1. one",
"2. two",
"",
"- [x] done",
"- [ ] todo",
"",
"> quoted",
"",
"```ts",
"const x = 1;",
"",
"const y = 2;",
"```",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const { text } = copySelectedMarkdown();
expect(text).toBe(source);
} finally {
await screen.unmount();
}
});
it("round-trips tables with alignment", async () => {
const source = ["| Name | Count |", "| --- | ---: |", "| a | 1 |", "| b | 2 |"].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const { text } = copySelectedMarkdown();
expect(text).toBe(source);
} finally {
await screen.unmount();
}
});
it("round-trips details rendered through the collapsible", async () => {
const source = [
"<details open>",
"<summary>Expandable details section</summary>",
"",
"This content includes **formatted text**.",
"</details>",
].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const { text } = copySelectedMarkdown();
expect(text).toBe(source);
} finally {
await screen.unmount();
}
});
it("excludes the code block header chrome from copied markdown", async () => {
const source = ["```ts", "const x = 1;", "```"].join("\n");
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
try {
const { text } = copySelectedMarkdown();
expect(text).toBe(source);
} finally {
await screen.unmount();
}
});
it("copies file links as markdown and skips UI affordances", async () => {
const filePath = "/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown
text={`See [PermissionRule.ts](file://${filePath}) for details.`}
cwd="/repo/project"
/>,
);
try {
const { text, html } = copySelectedMarkdown();
expect(text).toBe(
`See [PermissionRule.ts](/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts) for details.`,
);
expect(html).toContain("PermissionRule.ts");
expect(html).not.toContain("<img");
} finally {
await screen.unmount();
}
});
it("copies skill and file chips with source encodings that recreate composer chips", async () => {
const source =
"Use $agent-browser with [package.json](path/to/package.json) before continuing.";
const screen = await render(
<ChatMarkdown
text={source}
cwd="/repo/project"
skills={[{ name: "agent-browser", displayName: "Agent Browser" }]}
/>,
);
try {
const root = document.querySelector(".chat-markdown")!;
const selection = window.getSelection()!;
selection.removeAllRanges();
const range = document.createRange();
range.selectNodeContents(root);
selection.addRange(range);
expect(selection.toString()).toContain("Agent Browser");
expect(selection.toString()).toContain("package.json");
selection.removeAllRanges();
const { text, html } = copySelectedMarkdown();
expect(text).toBe(source);
expect(html).toContain("Agent Browser");
expect(html).toContain("package.json");
expect(html).not.toContain("<img");
} finally {
await screen.unmount();
}
});
});
});
+676 -34
View File
@@ -1,9 +1,18 @@
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
import { CheckIcon, CopyIcon } from "lucide-react";
import {
CheckIcon,
ChevronRightIcon,
CopyIcon,
GlobeIcon,
Maximize2Icon,
Minimize2Icon,
WrapTextIcon,
} from "lucide-react";
import type { ServerProviderSkill } from "@t3tools/contracts";
import React, {
Children,
Suspense,
type ClipboardEvent as ReactClipboardEvent,
type MouseEvent as ReactMouseEvent,
isValidElement,
use,
@@ -18,16 +27,34 @@ import React, {
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
import {
getVscodeIconUrlForEntry,
hasSpecificVscodeIconForFileName,
syntheticFileNameForLanguageId,
} from "../vscode-icons";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Button } from "./ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible";
import { ScrollArea } from "./ui/scroll-area";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import {
chatMarkdownClipboardPayload,
serializeTableElementToCsv,
serializeTableElementToMarkdown,
} from "../markdown-clipboard";
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
@@ -62,6 +89,9 @@ interface ChatMarkdownProps {
cwd: string | undefined;
isStreaming?: boolean;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
className?: string;
/** Treat single newlines as hard breaks — chat-style user input. */
lineBreaks?: boolean;
}
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
@@ -74,6 +104,18 @@ const highlightedCodeCache = new LRUCache<string>(
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
);
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta"],
},
protocols: {
...defaultSchema.protocols,
href: [...(defaultSchema.protocols?.href ?? []), "file"],
},
} satisfies Parameters<typeof rehypeSanitize>[0];
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
@@ -82,6 +124,64 @@ function extractFenceLanguage(className: string | undefined): string {
return raw === "gitignore" ? "ini" : raw;
}
const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i;
const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/;
/** Pulls a filename out of fence meta: ```ts title="x.ts" / ```ts src/main.ts */
function extractFenceTitle(meta: string | undefined): string | null {
if (!meta) return null;
const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta);
const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3];
if (attrTitle) return attrTitle;
return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null;
}
function extractPreCodeMeta(node: unknown): string | undefined {
const children = (
node as
| {
children?: Array<{
type?: string;
tagName?: string;
data?: { meta?: unknown };
properties?: { dataCodeMeta?: unknown };
}>;
}
| undefined
)?.children;
const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code");
const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta;
return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
}
type MarkdownAstNode = {
type?: string;
meta?: unknown;
data?: {
hProperties?: Record<string, unknown>;
};
children?: MarkdownAstNode[];
};
function remarkPreserveCodeMeta() {
return (tree: MarkdownAstNode) => {
const visit = (node: MarkdownAstNode) => {
if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
node.data = {
...node.data,
hProperties: {
...node.data?.hProperties,
dataCodeMeta: node.meta.trim(),
},
};
}
node.children?.forEach(visit);
};
visit(tree);
};
}
function nodeToPlainText(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") {
return String(node);
@@ -146,9 +246,254 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
return promise;
}
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
const containerRef = useRef<HTMLDivElement | null>(null);
const tableRef = useRef<HTMLTableElement | null>(null);
const [expanded, setExpanded] = useState(false);
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
const copyLabel = copied ? "Copied" : "Copy table";
function toggleExpanded() {
const table = tableRef.current;
if (!table) return;
if (!expanded) {
const rows = [...table.rows];
const columnWidths = rows.reduce<number[]>((widths, row) => {
[...row.cells].forEach((cell, columnIndex) => {
widths[columnIndex] = Math.max(
widths[columnIndex] ?? 0,
cell.getBoundingClientRect().width,
);
});
return widths;
}, []);
[...(table.tHead?.rows[0]?.cells ?? [])].forEach((cell, columnIndex) => {
cell.style.minWidth = `${columnWidths[columnIndex] ?? cell.getBoundingClientRect().width}px`;
});
}
setExpanded((value) => !value);
}
const handleCopy = useCallback((format: "markdown" | "csv") => {
const table = containerRef.current?.querySelector("table");
if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
return;
}
const text =
format === "markdown"
? serializeTableElementToMarkdown(table)
: serializeTableElementToCsv(table);
void navigator.clipboard
.writeText(text)
.then(() => {
if (copiedTimerRef.current != null) {
clearTimeout(copiedTimerRef.current);
}
setCopied(true);
copiedTimerRef.current = setTimeout(() => {
setCopied(false);
copiedTimerRef.current = null;
}, 1200);
})
.catch(() => undefined);
}, []);
useEffect(
() => () => {
if (copiedTimerRef.current != null) {
clearTimeout(copiedTimerRef.current);
copiedTimerRef.current = null;
}
},
[],
);
return (
<div
ref={containerRef}
className="chat-markdown-table-container"
data-expanded={expanded ? "true" : "false"}
>
<ScrollArea
chainVerticalScroll
scrollFade
hideScrollbars
className="w-full max-w-full rounded-none"
>
<table ref={tableRef} {...props}>
{children}
</table>
</ScrollArea>
<div className="chat-markdown-table-footer select-none">
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="chat-markdown-chrome-action"
aria-pressed={expanded}
onClick={toggleExpanded}
aria-label={expandLabel}
/>
}
>
{expanded ? <Minimize2Icon className="size-3" /> : <Maximize2Icon className="size-3" />}
</TooltipTrigger>
<TooltipPopup side="top">{expandLabel}</TooltipPopup>
</Tooltip>
<Menu>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="chat-markdown-chrome-action"
aria-label={copyLabel}
/>
}
/>
}
>
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
</TooltipTrigger>
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
</Tooltip>
<MenuPopup align="end">
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
</MenuPopup>
</Menu>
</div>
</div>
);
}
function MarkdownDetails({
children,
open = false,
}: Pick<React.ComponentProps<"details">, "children" | "open">) {
const [isOpen, setIsOpen] = useState(open);
const childNodes = Children.toArray(children);
const summaryIndex = childNodes.findIndex(
(child) => isValidElement(child) && child.type === "summary",
);
const summaryNode = summaryIndex >= 0 ? childNodes[summaryIndex] : null;
const summary =
isValidElement<{ children?: ReactNode }>(summaryNode) && summaryNode.props.children
? summaryNode.props.children
: "Details";
const content = childNodes.filter((_, index) => index !== summaryIndex);
return (
<Collapsible
defaultOpen={open}
onOpenChange={setIsOpen}
className="chat-markdown-details my-2 border-y border-border/60"
data-markdown-details=""
data-markdown-details-open={isOpen ? "true" : "false"}
>
<CollapsibleTrigger
className="flex w-full items-center gap-2 py-2 text-left text-sm font-medium text-foreground data-panel-open:[&_svg]:rotate-90"
data-markdown-details-summary=""
>
<ChevronRightIcon
className="size-4 shrink-0 text-muted-foreground transition-transform"
aria-hidden
/>
<span>{summary}</span>
</CollapsibleTrigger>
<CollapsiblePanel>
<div className="pb-3 ps-6 text-foreground/80" data-markdown-details-content="">
{content}
</div>
</CollapsiblePanel>
</Collapsible>
);
}
/**
* Filename titles render icon + text; language-only titles render just the
* icon (redundant next to its own name) and fall back to the language text
* when no specific icon exists or it fails to load.
*/
function MarkdownCodeBlockTitleContent({
fenceTitle,
language,
theme,
}: {
fenceTitle: string | null;
language: string;
theme: "light" | "dark";
}) {
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
if (fenceTitle) {
return (
<>
<VscodeEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
<span className="truncate">{fenceTitle}</span>
</>
);
}
const fileName = syntheticFileNameForLanguageId(language);
const iconUrl = hasSpecificVscodeIconForFileName(fileName, theme)
? getVscodeIconUrlForEntry(fileName, "file", theme)
: null;
if (!iconUrl || failedIconUrl === iconUrl) {
return <span className="truncate">{language}</span>;
}
return (
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
}
>
<img
src={iconUrl}
alt=""
aria-hidden
className="size-3.5 shrink-0"
loading="lazy"
draggable={false}
onError={() => setFailedIconUrl(iconUrl)}
/>
</TooltipTrigger>
<TooltipPopup side="top">{language}</TooltipPopup>
</Tooltip>
);
}
function MarkdownCodeBlock({
code,
language,
fenceTitle,
theme,
children,
}: {
code: string;
language: string;
fenceTitle: string | null;
theme: "light" | "dark";
children: ReactNode;
}) {
const [copied, setCopied] = useState(false);
const [wrapped, setWrapped] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
const copyLabel = copied ? "Copied" : "Copy code";
const handleCopy = useCallback(() => {
if (typeof navigator === "undefined" || navigator.clipboard == null) {
return;
@@ -179,16 +524,57 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
);
return (
<div className="chat-markdown-codeblock leading-snug">
<button
type="button"
className="chat-markdown-copy-button"
onClick={handleCopy}
title={copied ? "Copied" : "Copy code"}
aria-label={copied ? "Copied" : "Copy code"}
>
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
</button>
<div
className="chat-markdown-codeblock leading-snug"
data-language={language}
data-wrap={wrapped ? "true" : "false"}
>
<div className="chat-markdown-codeblock-header select-none">
<span className="chat-markdown-codeblock-title">
<MarkdownCodeBlockTitleContent
fenceTitle={fenceTitle}
language={language}
theme={theme}
/>
</span>
<span className="flex items-center gap-0.5">
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="chat-markdown-chrome-action"
aria-pressed={wrapped}
onClick={() => setWrapped((value) => !value)}
aria-label={wrapLabel}
/>
}
>
<WrapTextIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-xs"
className="chat-markdown-chrome-action"
onClick={handleCopy}
aria-label={copyLabel}
/>
}
>
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
</TooltipTrigger>
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
</Tooltip>
</span>
</div>
{children}
</div>
);
@@ -279,18 +665,17 @@ function UncachedShikiCodeBlock({
interface MarkdownFileLinkProps {
href: string;
targetPath: string;
iconPath: string;
displayPath: string;
filePath: string;
label: string;
copyMarkdown: string;
theme: "light" | "dark";
className?: string | undefined;
}
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link relative top-[2px] max-w-full no-underline";
const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
function pathParentSegments(path: string): string[] {
const normalized = path.replaceAll("\\", "/");
@@ -367,12 +752,197 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
}
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
const failedFaviconHosts = new Set<string>();
function resolveExternalLinkHost(href: string | undefined): string | null {
if (!href) return null;
try {
const url = new URL(href);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return url.hostname || null;
} catch {
return null;
}
}
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
const [failedHost, setFailedHost] = useState<string | null>(null);
return (
<span className="chat-markdown-link-favicon" aria-hidden>
{failedHost === host || failedFaviconHosts.has(host) ? (
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
) : (
<img
src={`https://www.google.com/s2/favicons?domain=${encodeURIComponent(host)}&sz=32`}
alt=""
loading="lazy"
draggable={false}
className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
onError={() => {
failedFaviconHosts.add(host);
setFailedHost(host);
}}
/>
)}
</span>
);
});
function leadingExternalLinkTextLength(text: string): number {
const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0];
if (protocol) return protocol.length;
return Math.min(text.length, 1);
}
function breakableExternalLinkText(text: string): ReactNode[] {
return Array.from(text, (character, index) => (
<React.Fragment key={`${index}:${character}`}>
{character}
<wbr />
</React.Fragment>
));
}
function plainHastText(node: unknown): string | null {
if (!node || typeof node !== "object" || !("children" in node) || !Array.isArray(node.children)) {
return null;
}
const parts = node.children.map((child) => {
if (
child &&
typeof child === "object" &&
"type" in child &&
child.type === "text" &&
"value" in child &&
typeof child.value === "string"
) {
return child.value;
}
return null;
});
return parts.every((part) => part !== null) ? parts.join("") : null;
}
const SANITIZED_FRAGMENT_PREFIX = "user-content-";
function decodeMarkdownFragmentId(href: string): string {
const encodedId = href.slice(1);
try {
return decodeURIComponent(encodedId);
} catch {
return encodedId;
}
}
function normalizeSanitizedFragmentId(id: string): string {
let normalizedId = id;
while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
}
return normalizedId;
}
function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
const decodedId = decodeMarkdownFragmentId(href);
const normalizedId = normalizeSanitizedFragmentId(decodedId);
const matchesFragment = (element: HTMLElement) =>
element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
if (markdownRoot) {
const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
const localTarget = localTargets.find(matchesFragment);
if (localTarget) return localTarget;
}
return (
document.getElementById(decodedId) ??
Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
null
);
}
function handleMarkdownFragmentClick(event: ReactMouseEvent<HTMLAnchorElement>, href: string) {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
const target = findMarkdownFragmentTarget(event.currentTarget, href);
if (!target) return;
event.preventDefault();
const nextUrl = new URL(window.location.href);
nextUrl.hash = href.slice(1);
window.history.pushState(window.history.state, "", nextUrl);
target.scrollIntoView({ block: "nearest" });
}
function MarkdownExternalLinkContent({
host,
plainText,
children,
}: {
host: string;
plainText: string | null;
children: ReactNode;
}) {
if (plainText) {
const leadingLength = leadingExternalLinkTextLength(plainText);
return (
<>
<span className="chat-markdown-link-leading">
<MarkdownLinkFavicon host={host} />
{plainText.slice(0, leadingLength)}
</span>
{breakableExternalLinkText(plainText.slice(leadingLength))}
</>
);
}
const childNodes = Children.toArray(children);
const firstChild = childNodes[0];
if (typeof firstChild === "string" && firstChild.length > 0) {
const leadingLength = leadingExternalLinkTextLength(firstChild);
return (
<>
<span className="chat-markdown-link-leading">
<MarkdownLinkFavicon host={host} />
{firstChild.slice(0, leadingLength)}
</span>
{breakableExternalLinkText(firstChild.slice(leadingLength))}
{childNodes.slice(1)}
</>
);
}
return (
<>
<span className="chat-markdown-link-leading">
<MarkdownLinkFavicon host={host} />
{firstChild}
</span>
{childNodes.slice(1)}
</>
);
}
const MarkdownFileLink = memo(function MarkdownFileLink({
href,
targetPath,
iconPath,
displayPath,
filePath,
label,
copyMarkdown,
theme,
className,
}: MarkdownFileLinkProps) {
@@ -467,7 +1037,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
render={
<a
href={href}
className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
className={cn(CHAT_FILE_TAG_CHIP_CLASS_NAME, MARKDOWN_FILE_LINK_CLASS_NAME, className)}
data-markdown-copy={copyMarkdown}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -475,13 +1046,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
}}
onContextMenu={handleContextMenu}
>
<VscodeEntryIcon
pathValue={filePath}
kind="file"
theme={theme}
className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
/>
<span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
<FileTagChipContent path={iconPath} label={label} theme={theme} selectable />
</a>
}
/>
@@ -504,9 +1069,10 @@ function areMarkdownFileLinkPropsEqual(
return (
previous.href === next.href &&
previous.targetPath === next.targetPath &&
previous.iconPath === next.iconPath &&
previous.displayPath === next.displayPath &&
previous.filePath === next.filePath &&
previous.label === next.label &&
previous.copyMarkdown === next.copyMarkdown &&
previous.theme === next.theme &&
previous.className === next.className
);
@@ -517,6 +1083,8 @@ function ChatMarkdown({
cwd,
isStreaming = false,
skills = EMPTY_MARKDOWN_SKILLS,
className,
lineBreaks = false,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
@@ -542,6 +1110,17 @@ function ChatMarkdown({
const markdownUrlTransform = useCallback((href: string) => {
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
// Re-emit highlighted content as markdown so copying out of the rendered
// view keeps links, emphasis, lists, and code fences intact.
const handleCopy = useCallback((event: ReactClipboardEvent<HTMLDivElement>) => {
const selection = window.getSelection();
if (!selection || selection.isCollapsed || !event.clipboardData) return;
const payload = chatMarkdownClipboardPayload(selection);
if (!payload) return;
event.preventDefault();
event.clipboardData.setData("text/plain", payload.text);
event.clipboardData.setData("text/html", payload.html);
}, []);
const markdownComponents = useMemo<Components>(
() => ({
p({ node: _node, children, ...props }) {
@@ -550,11 +1129,49 @@ function ChatMarkdown({
li({ node: _node, children, ...props }) {
return <li {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</li>;
},
a({ node: _node, href, ...props }) {
a({ node, href, children, ...props }) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
const faviconHost = resolveExternalLinkHost(href);
const isSameDocumentLink = href?.startsWith("#") ?? false;
const onClick = props.onClick;
const link = (
<a
{...props}
href={href}
target={isSameDocumentLink ? undefined : "_blank"}
rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
onClick={(event) => {
onClick?.(event);
if (isSameDocumentLink && href) {
handleMarkdownFragmentClick(event, href);
}
}}
>
{faviconHost ? (
<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
{children}
</MarkdownExternalLinkContent>
) : (
children
)}
</a>
);
if (!faviconHost || !href) {
return link;
}
return (
<Tooltip>
<TooltipTrigger render={link} />
<TooltipPopup
side="top"
className="max-w-[min(36rem,calc(100vw-2rem))] whitespace-normal leading-tight wrap-anywhere"
>
{href}
</TooltipPopup>
</Tooltip>
);
}
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
@@ -572,22 +1189,36 @@ function ChatMarkdown({
<MarkdownFileLink
href={fileLinkMeta.targetPath}
targetPath={fileLinkMeta.targetPath}
iconPath={fileLinkMeta.filePath}
displayPath={fileLinkMeta.displayPath}
filePath={fileLinkMeta.filePath}
label={labelParts.join(" · ")}
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
theme={resolvedTheme}
className={props.className}
/>
);
},
pre({ node: _node, children, ...props }) {
table({ node: _node, ...props }) {
return <MarkdownTable {...props} />;
},
details({ node: _node, children, open: detailsOpen }) {
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
},
pre({ node, children, ...props }) {
const codeBlock = extractCodeBlock(children);
if (!codeBlock) {
return <pre {...props}>{children}</pre>;
}
const language = extractFenceLanguage(codeBlock.className);
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
return (
<MarkdownCodeBlock code={codeBlock.code}>
<MarkdownCodeBlock
code={codeBlock.code}
language={language}
fenceTitle={fenceTitle}
theme={resolvedTheme}
>
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
<Suspense fallback={<pre {...props}>{children}</pre>}>
<SuspenseShikiCodeBlock
@@ -613,9 +1244,20 @@ function ChatMarkdown({
);
return (
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
<div
className={cn(
"chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80",
className,
)}
onCopy={handleCopy}
>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
remarkPlugins={
lineBreaks
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
: [remarkGfm, remarkPreserveCodeMeta]
}
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
+144 -13
View File
@@ -1416,13 +1416,15 @@ async function waitForButtonByText(text: string): Promise<HTMLButtonElement> {
return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`);
}
function findButtonContainingText(text: string): HTMLButtonElement | null {
return (Array.from(document.querySelectorAll("button")).find((button) =>
button.textContent?.includes(text),
) ?? null) as HTMLButtonElement | null;
function findButtonContainingText(text: string): HTMLElement | null {
return (
Array.from(document.querySelectorAll<HTMLElement>('button, [role="button"]')).find((button) =>
button.textContent?.includes(text),
) ?? null
);
}
async function waitForButtonContainingText(text: string): Promise<HTMLButtonElement> {
async function waitForButtonContainingText(text: string): Promise<HTMLElement> {
return waitForElement(
() => findButtonContainingText(text),
`Unable to find button containing "${text}".`,
@@ -2341,7 +2343,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Lint",
(button) => button.getAttribute("aria-label") === "Run Lint",
) as HTMLButtonElement | null,
"Unable to find Run Lint button.",
);
@@ -2420,7 +2422,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Test",
(button) => button.getAttribute("aria-label") === "Run Test",
) as HTMLButtonElement | null,
"Unable to find Run Test button.",
);
@@ -3160,7 +3162,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const initialModeButton = await waitForInteractionModeButton("Build");
expect(initialModeButton.title).toContain("enter plan mode");
expect(initialModeButton.getAttribute("aria-label")).toContain("enter plan mode");
expect(initialModeButton.hasAttribute("title")).toBe(false);
window.dispatchEvent(
new KeyboardEvent("keydown", {
@@ -3172,7 +3175,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
await waitForLayout();
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Build")).getAttribute("aria-label")).toContain(
"enter plan mode",
);
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
@@ -3187,7 +3192,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Plan")).title).toContain(
expect((await waitForInteractionModeButton("Plan")).getAttribute("aria-label")).toContain(
"return to normal build mode",
);
},
@@ -3205,7 +3210,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
expect(
(await waitForInteractionModeButton("Build")).getAttribute("aria-label"),
).toContain("enter plan mode");
},
{ timeout: 8_000, interval: 16 },
);
@@ -3214,6 +3221,89 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("focuses the composer and inserts printable text typed from the page background", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-target-type-to-focus" as MessageId,
targetText: "type-to-focus target",
}),
});
const backgroundTarget = document.createElement("div");
backgroundTarget.tabIndex = -1;
document.body.append(backgroundTarget);
try {
const composerEditor = await waitForComposerEditor();
backgroundTarget.focus();
expect(document.activeElement).not.toBe(composerEditor);
const event = new KeyboardEvent("keydown", {
key: "h",
bubbles: true,
cancelable: true,
});
backgroundTarget.dispatchEvent(event);
await waitForComposerText("h");
expect(event.defaultPrevented).toBe(true);
expect(document.activeElement).toBe(composerEditor);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "i",
bubbles: true,
cancelable: true,
}),
);
await waitForComposerText("hi");
} finally {
backgroundTarget.remove();
await mounted.cleanup();
}
});
it("does not steal printable keys from editable targets or shortcut modifiers", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-target-type-to-focus-guards" as MessageId,
targetText: "type-to-focus guards target",
}),
});
const input = document.createElement("input");
document.body.append(input);
try {
input.focus();
input.dispatchEvent(
new KeyboardEvent("keydown", {
key: "x",
bubbles: true,
cancelable: true,
}),
);
await waitForLayout();
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe("");
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "k",
metaKey: true,
bubbles: true,
cancelable: true,
}),
);
await waitForLayout();
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe("");
} finally {
input.remove();
await mounted.cleanup();
}
});
it("uses the active draft route session when changing the base branch", async () => {
const staleDraftId = draftIdFromPath("/draft/draft-stale-branch-session");
const activeDraftId = draftIdFromPath("/draft/draft-active-branch-session");
@@ -3587,13 +3677,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
{ timeout: 8_000, interval: 16 },
);
await waitForComposerText("hi @package.json there");
await waitForComposerText("hi [package.json](package.json) there");
await setComposerSelectionByTextOffsets({
start: "hi package.json ".length,
end: "hi package.json there".length,
});
await pressComposerKey("(");
await waitForComposerText("hi @package.json (there)");
await waitForComposerText("hi [package.json](package.json) (there)");
} finally {
await mounted.cleanup();
}
@@ -3625,6 +3715,47 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("stores selected file tags as markdown links while keeping the composer chip", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "@pack");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-file-tag-encoding" as MessageId,
targetText: "file tag encoding",
}),
resolveRpc: (body) => {
if (body._tag !== WS_METHODS.projectsSearchEntries) {
return undefined;
}
return {
entries: [
{
path: "path/to/package.json",
kind: "file",
parentPath: "path/to",
},
],
truncated: false,
};
},
});
try {
const item = await waitForComposerMenuItem("path:file:path/to/package.json");
item.click();
await waitForComposerText("[package.json](path/to/package.json) ");
const chip = await waitForElement(
() => document.querySelector<HTMLElement>('[data-composer-mention-chip="true"]'),
"Unable to find rendered composer file chip.",
);
expect(chip.textContent).toContain("package.json");
} finally {
await mounted.cleanup();
}
});
it("shows runtime mode descriptions in the desktop composer access select", async () => {
setDraftThreadWithoutWorktree();
+84 -33
View File
@@ -50,7 +50,6 @@ import {
parseStandaloneComposerSlashCommand,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -61,9 +60,7 @@ import {
findLatestProposedPlan,
deriveWorkLogEntries,
hasActionableProposedPlan,
hasToolActivityForTurn,
isLatestTurnSettled,
formatElapsed,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
import {
@@ -203,6 +200,35 @@ 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> = {};
const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [
"input",
"textarea",
"select",
'[contenteditable="true"]',
'[contenteditable="plaintext-only"]',
'[role="textbox"]',
].join(",");
const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [
"button",
"a[href]",
"summary",
'[role="button"]',
'[role="checkbox"]',
'[role="menuitem"]',
'[role="option"]',
'[role="radio"]',
'[role="switch"]',
'[role="tab"]',
].join(",");
const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [
'[data-slot="dialog"]',
'[data-slot="menu-popup"]',
'[data-slot="select-popup"]',
'[data-slot="popover-popup"]',
'[data-slot="combobox-popup"]',
'[data-slot="autocomplete-popup"]',
].join(",");
type EnvironmentUnavailableState = {
readonly environmentId: EnvironmentId;
readonly label: string;
@@ -211,6 +237,25 @@ type EnvironmentUnavailableState = {
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
function eventTargetElement(target: EventTarget | null): Element | null {
if (target instanceof Element) return target;
if (target instanceof Node) return target.parentElement;
return null;
}
function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
if (event.defaultPrevented || event.isComposing) return false;
if (event.metaKey || event.ctrlKey || event.altKey) return false;
if (event.key.length !== 1) return false;
const target = eventTargetElement(event.target);
if (target?.closest(TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;
if (target?.closest(TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
return true;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
return useStore(
useMemo(() => {
@@ -1469,14 +1514,7 @@ export default function ChatView(props: ChatViewProps) {
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
[activeLatestTurn?.turnId, threadActivities],
);
const latestTurnHasToolActivity = useMemo(
() => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId),
[activeLatestTurn?.turnId, threadActivities],
);
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -1811,25 +1849,6 @@ export default function ChatView(props: ChatViewProps) {
return byUserMessageId;
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
const completionSummary = useMemo(() => {
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!latestTurnHasToolActivity) return null;
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
return elapsed ? `Worked for ${elapsed}` : null;
}, [
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
latestTurnHasToolActivity,
latestTurnSettled,
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!latestTurnSettled) return null;
if (!completionSummary) return null;
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
@@ -1843,7 +1862,11 @@ export default function ChatView(props: ChatViewProps) {
// `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 selectedProviderInstanceId =
providerStatuses.find((status) => status.instanceId === selectedProviderByThreadId)
?.instanceId ?? null;
const activeProviderInstanceId =
selectedProviderInstanceId ??
activeThread?.session?.providerInstanceId ??
activeThread?.modelSelection.instanceId ??
activeProject?.defaultModelSelection?.instanceId ??
@@ -2698,6 +2721,18 @@ export default function ChatView(props: ChatViewProps) {
modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
};
if (
!shortcutContext.terminalFocus &&
!shortcutContext.modelPickerOpen &&
shouldTypeToFocusComposer(event)
) {
if (composerRef.current?.insertTextAtEnd(event.key)) {
event.preventDefault();
event.stopPropagation();
return;
}
}
const command = resolveShortcutCommand(event, keybindings, {
context: shortcutContext,
});
@@ -3597,6 +3632,23 @@ export default function ChatView(props: ChatViewProps) {
composerRef,
]);
const getModelDisabledReason = useCallback(
(instanceId: ProviderInstanceId, model: string): string | null => {
if (!activeThread) {
return null;
}
const reason = getStartedThreadModelChangeBlockReason({
providers: providerStatuses,
hasStartedSession: activeThread.session !== null,
currentModelSelection: activeThread.modelSelection,
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
nextModelSelection: { instanceId, model },
});
return reason ? `${reason.description} Start a new thread to use this model.` : null;
},
[activeThread, providerStatuses],
);
const onProviderModelSelect = useCallback(
(instanceId: ProviderInstanceId, model: string) => {
if (!activeThread) return;
@@ -3804,12 +3856,10 @@ export default function ChatView(props: ChatViewProps) {
key={activeThread.id}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
activeTurnId={activeLatestTurn?.turnId ?? null}
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
latestTurn={activeLatestTurn}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
activeThreadEnvironmentId={activeThread.environmentId}
routeThreadKey={routeThreadKey}
@@ -3915,6 +3965,7 @@ export default function ChatView(props: ChatViewProps) {
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
@@ -95,6 +95,7 @@ export function buildProjectActionItems(input: {
valuePrefix: string;
icon: (project: Project) => ReactNode;
runProject: (project: Project) => Promise<void>;
shortcutCommand?: KeybindingCommand;
}): CommandPaletteActionItem[] {
return input.projects.map((project) => ({
kind: "action",
@@ -103,6 +104,7 @@ export function buildProjectActionItems(input: {
title: project.name,
description: project.cwd,
icon: input.icon(project),
...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
run: async () => {
await input.runProject(project);
},
+71 -53
View File
@@ -647,6 +647,7 @@ function OpenCommandPaletteDialog() {
buildProjectActionItems({
projects,
valuePrefix: "new-thread-in",
shortcutCommand: "chat.new",
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
@@ -1570,61 +1571,78 @@ function OpenCommandPaletteDialog() {
onKeyDown={handleKeyDown}
/>
{addProjectCloneFlow?.step === "repository" ? (
<Button
variant="outline"
size="xs"
tabIndex={-1}
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
disabled={!canSubmitRemoteProjectFlow}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
void submitAddProjectCloneFlow();
}}
title={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
>
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>Enter</Kbd>
</KbdGroup>
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
disabled={!canSubmitRemoteProjectFlow}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
void submitAddProjectCloneFlow();
}}
/>
}
>
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>Enter</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{remoteProjectButtonLabel ?? "Continue"} (Enter)
</TooltipPopup>
</Tooltip>
) : isBrowsing ? (
<Button
variant="outline"
size="xs"
tabIndex={-1}
className={cn(
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
if (relativePathNeedsActiveProject) {
return;
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className={cn(
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
relativePathNeedsActiveProject ||
(isCloneDestinationStep && isRemoteProjectPending)
}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
if (relativePathNeedsActiveProject) {
return;
}
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
}}
/>
}
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
}}
title={`${submitActionLabel} (${addShortcutLabel})`}
>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
</Button>
>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{submitActionLabel} ({addShortcutLabel})
</TooltipPopup>
</Tooltip>
) : null}
</div>
<CommandPanel className="max-h-[min(28rem,70vh)]">
@@ -6,7 +6,7 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
import { type ServerProviderSkill } from "@t3tools/contracts";
import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import {
$applyNodeReplacement,
$createRangeSelection,
@@ -64,14 +64,14 @@ import {
type TerminalContextDraft,
} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
import { basenameOfPath } from "~/vscode-icons";
import {
COMPOSER_INLINE_CHIP_CLASS_NAME,
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
SKILL_CHIP_ICON_SVG,
} from "./composerInlineChip";
import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -132,19 +132,12 @@ function ComposerMentionDecorator(props: { path: string }) {
const theme = resolvedThemeFromDocument();
const chip = (
<span
className={COMPOSER_INLINE_CHIP_CLASS_NAME}
className={FILE_TAG_CHIP_CLASS_NAME}
contentEditable={false}
spellCheck={false}
data-composer-mention-chip="true"
>
<img
alt=""
aria-hidden="true"
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
loading="lazy"
src={getVscodeIconUrlForEntry(props.path, inferEntryKindFromPath(props.path), theme)}
/>
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{basenameOfPath(props.path)}</span>
<FileTagChipContent path={props.path} label={basenameOfPath(props.path)} theme={theme} />
</span>
);
@@ -175,8 +168,7 @@ class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
constructor(path: string, key?: NodeKey) {
super(key);
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
this.__path = normalizedPath;
this.__path = path;
}
override exportJSON(): SerializedComposerMentionNode {
@@ -199,7 +191,7 @@ class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
}
override getTextContent(): string {
return `@${serializeComposerMentionPath(this.__path)}`;
return serializeComposerFileLink(this.__path);
}
override isInline(): true {
@@ -918,6 +910,12 @@ function ComposerCommandKeyPlugin(props: {
if (!props.onCommandKeyDown || !event) {
return false;
}
if (key === "Enter" && (event.isComposing || event.keyCode === 229)) {
event.stopPropagation();
return true;
}
const handled = props.onCommandKeyDown(key, event);
if (handled) {
event.preventDefault();
+142 -71
View File
@@ -42,6 +42,7 @@ import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark";
@@ -52,6 +53,8 @@ const DIFF_PANEL_UNSAFE_CSS = `
[data-file],
[data-error-wrapper],
[data-virtualizer-buffer] {
--diffs-header-font-family: var(--font-sans) !important;
--diffs-font-family: var(--font-mono) !important;
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
@@ -92,6 +95,37 @@ const DIFF_PANEL_UNSAFE_CSS = `
z-index: 4;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
align-items: center !important;
font-family: var(--font-sans) !important;
font-size: 12px !important;
line-height: 1 !important;
min-height: 32px !important;
padding-block: 6px !important;
}
[data-diffs-header] [data-header-content] {
align-items: center !important;
line-height: 1 !important;
}
[data-diffs-header] [data-metadata] {
align-items: center !important;
line-height: 1 !important;
font-variant-numeric: tabular-nums;
}
[data-diffs-header] [data-additions-count],
[data-diffs-header] [data-deletions-count] {
font-family: var(--font-mono) !important;
font-size: 11px !important;
font-variant-numeric: tabular-nums;
line-height: 1 !important;
}
[data-diffs-header] [data-change-icon],
[data-diffs-header] [data-rename-icon] {
display: block;
flex-shrink: 0;
}
[data-title] {
@@ -102,6 +136,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
font-family: var(--font-sans) !important;
}
[data-title]:hover {
@@ -460,35 +495,41 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
</button>
{orderedTurnDiffSummaries.map((summary) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
<Tooltip key={summary.turnId}>
<TooltipTrigger
render={
<button
type="button"
aria-label={summary.turnId}
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
/>
}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn{" "}
{summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn{" "}
{summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70 tabular-nums">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
</div>
</div>
</div>
</button>
</TooltipTrigger>
<TooltipPopup side="top">{summary.turnId}</TooltipPopup>
</Tooltip>
))}
</div>
</div>
@@ -512,30 +553,50 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Toggle
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
>
<TextWrapIcon className="size-3" />
</Toggle>
<Toggle
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
}}
>
<PilcrowIcon className="size-3" />
</Toggle>
<Tooltip>
<TooltipTrigger
render={
<Toggle
aria-label={
diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"
}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
/>
}
>
<TextWrapIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Toggle
aria-label={
diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
}
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
}}
/>
}
>
<PilcrowIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
</TooltipPopup>
</Tooltip>
</div>
</>
);
@@ -609,26 +670,36 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<FileDiff
fileDiff={fileDiff}
renderHeaderPrefix={() => (
<button
type="button"
className={cn(
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
getDiffCollapseIconClassName(fileDiff),
)}
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
aria-expanded={!collapsed}
title={collapsed ? "Expand diff" : "Collapse diff"}
onClick={(event) => {
event.stopPropagation();
toggleDiffFileCollapsed(fileKey);
}}
>
{collapsed ? (
<ChevronRightIcon className="size-4" />
) : (
<ChevronDownIcon className="size-4" />
)}
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className={cn(
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
getDiffCollapseIconClassName(fileDiff),
)}
aria-label={
collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`
}
aria-expanded={!collapsed}
onClick={(event) => {
event.stopPropagation();
toggleDiffFileCollapsed(fileKey);
}}
/>
}
>
{collapsed ? (
<ChevronRightIcon className="size-4" />
) : (
<ChevronDownIcon className="size-4" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{collapsed ? "Expand diff" : "Collapse diff"}
</TooltipPopup>
</Tooltip>
)}
options={{
collapsed,
@@ -19,6 +19,7 @@ import {
ChevronDownIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitBranchPlusIcon,
GitCommitIcon,
InfoIcon,
LockIcon,
@@ -1611,7 +1612,10 @@ export default function GitActionsControl({
void initAction.run();
}}
>
{initAction.isPending ? "Initializing..." : "Initialize Git"}
<GitBranchPlusIcon className="size-3.5" aria-hidden />
<span className="ml-0.5">
{initAction.isPending ? "Initializing..." : "Initialize Git"}
</span>
</Button>
) : (
<Group aria-label="Git actions" className="shrink-0">
@@ -30,7 +30,7 @@ export function NoActiveThreadState() {
</header>
<Empty className="flex-1">
<div className="w-full max-w-lg rounded-3xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
<div className="w-full max-w-lg px-8 py-12">
<EmptyHeader className="max-w-none">
<EmptyTitle className="text-foreground text-xl">Pick a thread to continue</EmptyTitle>
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
+8 -7
View File
@@ -32,14 +32,14 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
function stepStatusIcon(status: string): React.ReactNode {
if (status === "completed") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-500">
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-success/10 text-success-foreground">
<CheckIcon className="size-3" />
</span>
);
}
if (status === "inProgress") {
return (
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-blue-500/15 text-blue-400">
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
<LoaderIcon className="size-3 animate-spin" />
</span>
);
@@ -139,13 +139,14 @@ const PlanSidebar = memo(function PlanSidebar({
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
<div className="flex items-center gap-2">
<Badge
variant="secondary"
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
variant="info"
size="sm"
className="rounded-md px-1.5 py-0 font-semibold tracking-wide uppercase"
>
{label}
</Badge>
{activePlan ? (
<span className="text-[11px] text-muted-foreground/60">
<span className="text-[11px] text-muted-foreground/60 tabular-nums">
{formatTimestamp(activePlan.createdAt, timestampFormat)}
</span>
) : null}
@@ -211,12 +212,12 @@ const PlanSidebar = memo(function PlanSidebar({
<div
key={`${step.status}:${step.step}`}
className={cn(
"flex items-start gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
"flex items-center gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
step.status === "inProgress" && "bg-blue-500/5",
step.status === "completed" && "bg-emerald-500/5",
)}
>
<div className="mt-0.5">{stepStatusIcon(step.status)}</div>
{stepStatusIcon(step.status)}
<p
className={cn(
"text-[13px] leading-snug",
@@ -53,6 +53,7 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Switch } from "./ui/switch";
import { Textarea } from "./ui/textarea";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
{ id: "play", label: "Play" },
@@ -219,17 +220,24 @@ export default function ProjectScriptsControl({
<>
{primaryScript ? (
<Group aria-label="Project scripts">
<Button
size="xs"
variant="outline"
onClick={() => onRunScript(primaryScript)}
title={`Run ${primaryScript.name}`}
>
<ScriptIcon icon={primaryScript.icon} />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
{primaryScript.name}
</span>
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant="outline"
aria-label={`Run ${primaryScript.name}`}
onClick={() => onRunScript(primaryScript)}
/>
}
>
<ScriptIcon icon={primaryScript.icon} />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
{primaryScript.name}
</span>
</TooltipTrigger>
<TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
</Tooltip>
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu highlightItemOnHover={false}>
<MenuTrigger
@@ -289,12 +297,19 @@ export default function ProjectScriptsControl({
</Menu>
</Group>
) : (
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
<PlusIcon className="size-3.5" />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Add action
</span>
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button size="xs" variant="outline" aria-label="Add action" onClick={openAddDialog} />
}
>
<PlusIcon className="size-3.5" />
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Add action
</span>
</TooltipTrigger>
<TooltipPopup side="top">Add action</TooltipPopup>
</Tooltip>
)}
<Dialog
+67 -44
View File
@@ -217,6 +217,8 @@ const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> =
repository_path: "Group by repository path",
separate: "Keep separate",
};
const SIDEBAR_ICON_ACTION_BUTTON_CLASS =
"inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring";
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
return Math.min(
@@ -608,14 +610,20 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
/>
}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</TooltipTrigger>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
)}
<div
className={`flex min-w-12 justify-end ${
@@ -629,7 +637,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
data-thread-selection-safe
data-testid={`thread-archive-confirm-${thread.id}`}
aria-label={`Confirm archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-md bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
onPointerDown={stopPropagationOnPointerDown}
onClick={handleConfirmArchiveClick}
>
@@ -637,13 +645,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</button>
) : !isThreadRunning ? (
appSettingsConfirmThreadArchive ? (
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
className={SIDEBAR_ICON_ACTION_BUTTON_CLASS}
onPointerDown={stopPropagationOnPointerDown}
onClick={handleStartArchiveConfirmation}
>
@@ -654,13 +662,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
<Tooltip>
<TooltipTrigger
render={
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
<button
type="button"
data-thread-selection-safe
data-testid={`thread-archive-${thread.id}`}
aria-label={`Archive ${thread.title}`}
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
className={SIDEBAR_ICON_ACTION_BUTTON_CLASS}
onPointerDown={stopPropagationOnPointerDown}
onClick={handleArchiveImmediateClick}
>
@@ -691,15 +699,22 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</Tooltip>
)}
{jumpLabel ? (
<span
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
title={jumpLabel}
>
{jumpLabel}
</span>
<Tooltip>
<TooltipTrigger
render={
<span
aria-label={jumpLabel}
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
/>
}
>
{jumpLabel}
</TooltipTrigger>
<TooltipPopup side="top">{jumpLabel}</TooltipPopup>
</Tooltip>
) : (
<span
className={`text-[10px] ${
className={`text-[10px] tabular-nums ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
@@ -1482,12 +1497,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}),
}),
label,
...(action === "delete" ? { icon: "trash" } : {}),
};
}
return {
id: `${action}:submenu`,
label,
...(action === "delete" ? { icon: "trash" } : {}),
children: project.memberProjects.map((member) =>
makeLeaf(action, member, {
...(options?.destructive ? { destructive: true } : {}),
@@ -1499,10 +1516,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const clicked = await api.contextMenu.show(
[
buildTargetedItem("rename", "Rename project"),
buildTargetedItem("grouping", "Project grouping…"),
buildTargetedItem("copy-path", "Copy Project Path"),
buildTargetedItem("delete", "Remove project", {
buildTargetedItem("rename", "Rename"),
buildTargetedItem("grouping", "Group into..."),
buildTargetedItem("copy-path", "Copy Path"),
buildTargetedItem("delete", "Remove", {
destructive: true,
}),
],
@@ -1918,7 +1935,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
],
position,
);
@@ -1994,20 +2011,26 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
onContextMenu={handleProjectButtonContextMenu}
>
{!projectExpanded && projectStatus ? (
<span
aria-hidden="true"
title={projectStatus.label}
className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}
>
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
<span
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
projectStatus.pulse ? "animate-pulse" : ""
}`}
/>
</span>
<ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
</span>
<Tooltip>
<TooltipTrigger
render={
<span
aria-label={projectStatus.label}
className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}
/>
}
>
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
<span
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
projectStatus.pulse ? "animate-pulse" : ""
}`}
/>
</span>
<ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
</TooltipTrigger>
<TooltipPopup side="top">{projectStatus.label}</TooltipPopup>
</Tooltip>
) : (
<ChevronRightIcon
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
@@ -2054,12 +2077,12 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
<Tooltip>
<TooltipTrigger
render={
<div className="pointer-events-none absolute top-1 right-1.5 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/project-header:pointer-events-auto group-hover/project-header:opacity-100 group-focus-within/project-header:pointer-events-auto group-focus-within/project-header:opacity-100">
<div className="pointer-events-none absolute top-[calc(50%+1px)] right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/project-header:pointer-events-auto group-hover/project-header:opacity-100 group-focus-within/project-header:pointer-events-auto group-focus-within/project-header:opacity-100">
<button
type="button"
aria-label={`Create new thread in ${project.displayName}`}
data-testid="new-thread-button"
className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 hover:bg-secondary hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
className={SIDEBAR_ICON_ACTION_BUTTON_CLASS}
onClick={handleCreateThreadClick}
>
<SquarePenIcon className="size-3.5" />
@@ -2297,7 +2320,7 @@ function ProjectSortMenu({
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground" />
<MenuTrigger className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground" />
}
>
<ArrowUpDownIcon className="size-3.5" />
@@ -2635,7 +2658,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
/>
}
>
<SearchIcon className="size-3.5" />
<SearchIcon className="size-3.5 text-muted-foreground/70" />
<span className="flex-1 truncate text-left text-xs">Search</span>
{commandPaletteShortcutLabel ? (
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
@@ -2692,7 +2715,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
type="button"
aria-label="Add project"
data-testid="sidebar-add-project-trigger"
className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
onClick={openAddProject}
/>
}
@@ -102,32 +102,45 @@ export function ThreadStatusLabel({
}) {
if (compact) {
return (
<span
title={status.label}
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="sr-only">{status.label}</span>
</span>
<Tooltip>
<TooltipTrigger
render={
<span
aria-label={status.label}
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
/>
}
>
<span
className={`size-[9px] rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
</TooltipTrigger>
<TooltipPopup side="top">{status.label}</TooltipPopup>
</Tooltip>
);
}
return (
<span
title={status.label}
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
</span>
<Tooltip>
<TooltipTrigger
render={
<span
aria-label={status.label}
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
/>
}
>
<span
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
status.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{status.label}</span>
</TooltipTrigger>
<TooltipPopup side="top">{status.label}</TooltipPopup>
</Tooltip>
);
}
@@ -220,14 +233,20 @@ export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSumma
return (
<span className="inline-flex shrink-0 items-center gap-1.5">
{terminalStatus ? (
<span
role="img"
aria-label={terminalStatus.label}
title={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</span>
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label={terminalStatus.label}
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
/>
}
>
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
</TooltipTrigger>
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
</Tooltip>
) : null}
{isRemoteThread ? (
<Tooltip>
@@ -329,7 +329,8 @@ export function TerminalViewport({
lineHeight: 1.2,
fontSize: 12,
scrollback: 5_000,
fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
fontFamily:
'"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace',
theme: terminalThemeFromApp(mount),
});
terminal.loadAddon(fitAddon);
@@ -1,14 +1,85 @@
import { type TurnId } from "@t3tools/contracts";
import { memo, useCallback, useMemo, useState } from "react";
import { type TurnDiffFileChange } from "../../types";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import {
buildTurnDiffTree,
summarizeTurnDiffStats,
type TurnDiffTreeNode,
} from "../../lib/turnDiffTree";
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
import { Button } from "../ui/button";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onToggleAllDirectories: () => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const {
turnId,
files,
allDirectoriesExpanded,
resolvedTheme,
onToggleAllDirectories,
onOpenTurnDiff,
} = props;
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
return (
<div className="relative mt-4 rounded-2xl bg-card/40 shadow-xs/5 not-dark:bg-clip-padding after:pointer-events-none after:absolute after:inset-0 after:z-20 after:rounded-2xl after:border after:border-input">
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 rounded-t-2xl bg-card/72 p-3 backdrop-blur-md">
<p className="flex items-center gap-1 font-medium text-foreground text-xs leading-4">
<span>{files.length} changed files</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<div className="flex items-center gap-1.5">
<Button
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={onToggleAllDirectories}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
>
View diff
</Button>
</div>
</div>
<div className="px-2 pb-2">
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
</div>
);
});
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
@@ -22,6 +93,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
() => collectDirectoryPaths(treeNodes).join("\u0000"),
[treeNodes],
);
const hasDirectoryNodes = directoryPathsKey.length > 0;
const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
const [directoryExpansionState, setDirectoryExpansionState] = useState<{
key: string;
@@ -60,7 +132,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
<button
type="button"
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path)}
>
@@ -98,11 +170,13 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
<button
key={`file:${node.path}`}
type="button"
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => onOpenTurnDiff(turnId, node.path)}
>
<span aria-hidden="true" className="size-3.5 shrink-0" />
{hasDirectoryNodes || depth > 0 ? (
<span aria-hidden="true" className="size-3.5 shrink-0" />
) : null}
<VscodeEntryIcon
pathValue={node.path}
kind="file"
+157 -81
View File
@@ -17,7 +17,7 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import {
memo,
@@ -86,6 +86,7 @@ import {
BotIcon,
CircleAlertIcon,
ListTodoIcon,
PencilRulerIcon,
type LucideIcon,
LockIcon,
LockOpenIcon,
@@ -93,7 +94,7 @@ import {
XIcon,
} from "lucide-react";
import { proposedPlanTitle } from "../../proposedPlan";
import { getProviderInteractionModeToggle } from "../../providerModels";
import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../providerModels";
import {
deriveProviderInstanceEntries,
resolveProviderDriverKindForInstanceSelection,
@@ -105,7 +106,10 @@ import type { UnifiedSettings } from "@t3tools/contracts/settings";
import type { SessionPhase, Thread } from "../../types";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingApproval, PendingUserInput } from "../../session-logic";
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
import {
deriveLatestContextWindowSnapshot,
formatProviderDisplayName,
} from "../../lib/contextWindow";
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
@@ -187,93 +191,124 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
}) {
const runtimeModeOption = runtimeModeConfig[props.runtimeMode];
const RuntimeModeIcon = runtimeModeOption.icon;
const interactionModeTooltip =
props.interactionMode === "plan"
? "Plan mode — click to return to normal build mode"
: "Default mode — click to enter plan mode";
const planSidebarTooltip = props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`;
const interactionModeToggle = props.showInteractionModeToggle ? (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
props.interactionMode === "plan"
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
size="sm"
type="button"
onClick={props.onToggleInteractionMode}
aria-label={interactionModeTooltip}
/>
}
>
{props.interactionMode === "plan" ? (
<PencilRulerIcon className="text-current opacity-100" />
) : (
<BotIcon />
)}
<span className="sr-only sm:not-sr-only">
{props.interactionMode === "plan" ? "Plan" : "Build"}
</span>
</TooltipTrigger>
<TooltipPopup side="top">{interactionModeTooltip}</TooltipPopup>
</Tooltip>
</>
) : null;
return (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
{props.showInteractionModeToggle ? (
<>
<Button
variant="ghost"
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
size="sm"
type="button"
onClick={props.onToggleInteractionMode}
title={
props.interactionMode === "plan"
? "Plan mode — click to return to normal build mode"
: "Default mode — click to enter plan mode"
<Tooltip>
<Select
value={props.runtimeMode}
onValueChange={(value) => props.onRuntimeModeChange(value!)}
>
<TooltipTrigger
render={
<SelectTrigger
variant="ghost"
size="sm"
className="font-medium"
aria-label="Runtime mode"
/>
}
>
<BotIcon />
<span className="sr-only sm:not-sr-only">
{props.interactionMode === "plan" ? "Plan" : "Build"}
</span>
</Button>
<RuntimeModeIcon className="size-4" />
<SelectValue>{runtimeModeOption.label}</SelectValue>
</TooltipTrigger>
<SelectPopup alignItemWithTrigger={false}>
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const OptionIcon = option.icon;
return (
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
<div className="grid min-w-0 gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
</span>
<span className="text-muted-foreground text-xs leading-4">
{option.description}
</span>
</div>
</SelectItem>
);
})}
</SelectPopup>
</Select>
<TooltipPopup side="top">{runtimeModeOption.description}</TooltipPopup>
</Tooltip>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
</>
) : null}
<Select
value={props.runtimeMode}
onValueChange={(value) => props.onRuntimeModeChange(value!)}
>
<SelectTrigger
variant="ghost"
size="sm"
className="font-medium"
aria-label="Runtime mode"
title={runtimeModeOption.description}
>
<RuntimeModeIcon className="size-4" />
<SelectValue>{runtimeModeOption.label}</SelectValue>
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const OptionIcon = option.icon;
return (
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
<div className="grid min-w-0 gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
</span>
<span className="text-muted-foreground text-xs leading-4">
{option.description}
</span>
</div>
</SelectItem>
);
})}
</SelectPopup>
</Select>
{interactionModeToggle}
{props.showPlanToggle ? (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
<Button
variant="ghost"
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
props.planSidebarOpen
? "text-blue-400 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
size="sm"
type="button"
onClick={props.onTogglePlanSidebar}
title={
props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`
}
>
<ListTodoIcon />
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
props.planSidebarOpen
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
size="sm"
type="button"
onClick={props.onTogglePlanSidebar}
aria-label={planSidebarTooltip}
/>
}
>
<ListTodoIcon
className={props.planSidebarOpen ? "text-current opacity-100" : undefined}
/>
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
</TooltipTrigger>
<TooltipPopup side="top">{planSidebarTooltip}</TooltipPopup>
</Tooltip>
</>
) : null}
</>
@@ -283,6 +318,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
activeThreadProviderDisplayName: string | null;
isPreparingWorktree: boolean;
pendingAction: {
questionIndex: number;
@@ -305,7 +341,12 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
}) {
return (
<>
{props.activeContextWindow ? <ContextWindowMeter usage={props.activeContextWindow} /> : null}
{props.activeContextWindow ? (
<ContextWindowMeter
usage={props.activeContextWindow}
providerDisplayName={props.activeThreadProviderDisplayName}
/>
) : null}
{props.isPreparingWorktree ? (
<span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
) : null}
@@ -336,6 +377,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
export interface ChatComposerHandle {
focusAtEnd: () => void;
focusAt: (cursor: number) => void;
insertTextAtEnd: (text: string) => boolean;
openModelPicker: () => void;
toggleModelPicker: () => void;
isModelPickerOpen: () => boolean;
@@ -470,6 +512,7 @@ export interface ChatComposerProps {
) => void;
onProviderModelSelect: (instanceId: ProviderInstanceId, model: string) => void;
getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null;
toggleInteractionMode: () => void;
handleRuntimeModeChange: (mode: RuntimeMode) => void;
handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
@@ -544,6 +587,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onPreviousActivePendingUserInputQuestion,
onChangeActivePendingUserInputCustomAnswer,
onProviderModelSelect,
getModelDisabledReason,
toggleInteractionMode,
handleRuntimeModeChange,
handleInteractionModeChange,
@@ -778,6 +822,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
[activeThreadActivities],
);
const activeThreadProviderDisplayName = useMemo(() => {
if (!activeThreadModelSelection) return null;
const entry = providerStatuses.find(
(p) => p.instanceId === activeThreadModelSelection.instanceId,
);
if (entry) {
return getProviderDisplayName(providerStatuses, entry.driver);
}
return formatProviderDisplayName(activeThreadModelSelection.instanceId);
}, [providerStatuses, activeThreadModelSelection]);
// ------------------------------------------------------------------
// Composer-local state
@@ -1472,7 +1526,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const { snapshot, trigger } = resolveActiveComposerTrigger();
if (!trigger) return;
if (item.type === "path") {
const replacement = `@${serializeComposerMentionPath(item.path)} `;
const replacement = `${serializeComposerFileLink(item.path)} `;
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
snapshot.value,
trigger.rangeEnd,
@@ -1835,6 +1889,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusAt: (cursor: number) => {
composerEditorRef.current?.focusAt(cursor);
},
insertTextAtEnd: (text: string) => {
if (
text.length === 0 ||
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
(environmentUnavailable !== null && activePendingProgress === null)
) {
return false;
}
const rangeEnd = promptRef.current.length;
return applyPromptReplacement(rangeEnd, rangeEnd, text);
},
openModelPicker: () => {
setIsComposerModelPickerOpen(true);
},
@@ -1919,6 +1986,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptRef,
composerImagesRef,
composerTerminalContextsRef,
isConnecting,
isComposerApprovalState,
pendingUserInputs.length,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
selectedModel,
@@ -2132,7 +2205,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
>
{composerMenuOpen && !isComposerApprovalState && (
<div className="absolute inset-x-0 bottom-full z-20 mb-2 px-1">
<div className="absolute inset-x-0 bottom-full z-20 mb-2">
<ComposerCommandMenu
items={composerMenuItems}
resolvedTheme={resolvedTheme}
@@ -2304,6 +2377,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
className={cn(
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-2.5 pb-2.5 sm:px-3 sm:pb-3",
pendingUserInputs.length > 0 && "pt-2",
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
showMobilePendingAnswerActions && "hidden sm:flex",
)}
@@ -2328,6 +2402,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onOpenChange={(open) => {
setIsComposerModelPickerOpen(open);
}}
getModelDisabledReason={getModelDisabledReason}
onInstanceModelChange={onProviderModelSelect}
/>
@@ -2378,6 +2453,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerFooterPrimaryActions
compact={isComposerPrimaryActionsCompact}
activeContextWindow={activeContextWindow}
activeThreadProviderDisplayName={activeThreadProviderDisplayName}
pendingAction={pendingPrimaryAction}
isRunning={phase === "running"}
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
+15 -22
View File
@@ -10,7 +10,6 @@ import { memo } from "react";
import GitActionsControl from "../GitActionsControl";
import { type DraftId } from "~/composerDraftStore";
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
import { Badge } from "../ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
import { Toggle } from "../ui/toggle";
@@ -92,25 +91,19 @@ export const ChatHeader = memo(function ChatHeader({
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<h2
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
title={activeThreadTitle}
>
{activeThreadTitle}
</h2>
{activeProjectName && (
<Badge
variant="outline"
className="min-w-0 max-w-full shrink overflow-hidden sm:max-w-56"
>
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
{activeProjectName && !isGitRepo && (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
</Badge>
)}
<Tooltip>
<TooltipTrigger
render={
<h2
aria-label={activeThreadTitle}
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
>
{activeThreadTitle}
</h2>
}
/>
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
</Tooltip>
</div>
<div className="flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3">
{activeProjectScripts && (
@@ -146,7 +139,7 @@ export const ChatHeader = memo(function ChatHeader({
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
variant="outline"
variant="ghost"
size="xs"
disabled={!terminalAvailable}
>
@@ -170,7 +163,7 @@ export const ChatHeader = memo(function ChatHeader({
pressed={diffOpen}
onPressedChange={onToggleDiff}
aria-label="Toggle diff panel"
variant="outline"
variant="ghost"
size="xs"
disabled={!isGitRepo && !diffOpen}
>
@@ -100,7 +100,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
],
["ultrathink"],
),
booleanDescriptor("fastMode", "Speed"),
booleanDescriptor("fastMode", "Fast Mode"),
],
}),
},
@@ -181,7 +181,7 @@ describe("CompactComposerControlsMenu", () => {
});
});
it("shows speed controls for Opus", async () => {
it("shows fast mode controls for Opus", async () => {
await using _ = await mountMenu({
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
@@ -193,13 +193,13 @@ describe("CompactComposerControlsMenu", () => {
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Speed");
expect(text).toContain("Normal");
expect(text).toContain("Fast");
expect(text).toContain("Fast Mode");
expect(text).toContain("On");
expect(text).toContain("Off");
});
});
it("hides speed controls for non-Opus Claude models", async () => {
it("hides fast mode controls for non-Opus Claude models", async () => {
await using _ = await mountMenu({
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
@@ -210,7 +210,7 @@ describe("CompactComposerControlsMenu", () => {
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").not.toContain("Speed");
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
});
});
@@ -141,34 +141,35 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
>
<div
ref={listRef}
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
className="relative w-full overflow-hidden rounded-[20px] border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<CommandList className="max-h-72">
{groups.map((group, groupIndex) => (
<div key={group.id}>
{groupIndex > 0 ? <CommandSeparator className="my-0.5" /> : null}
<CommandGroup>
{group.label ? (
<CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
{group.label}
</CommandGroupLabel>
) : null}
{group.items.map((item) => (
<ComposerCommandMenuItem
key={item.id}
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
</CommandGroup>
</div>
))}
</CommandList>
{props.items.length === 0 ? (
<div className="px-3 py-2">
{props.items.length > 0 ? (
<CommandList className="max-h-72">
{groups.map((group, groupIndex) => (
<div key={group.id}>
{groupIndex > 0 ? <CommandSeparator className="my-0.5" /> : null}
<CommandGroup>
{group.label ? (
<CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
{group.label}
</CommandGroupLabel>
) : null}
{group.items.map((item) => (
<ComposerCommandMenuItem
key={item.id}
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
</CommandGroup>
</div>
))}
</CommandList>
) : (
<div className="px-5 py-3.5">
{props.triggerKind === "skill" ? (
<CommandGroup>
<CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
@@ -192,7 +193,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
</p>
)}
</div>
) : null}
)}
</div>
</Command>
);
@@ -1,5 +1,5 @@
import { type ApprovalRequestId } from "@t3tools/contracts";
import { memo, useEffect, useEffectEvent, useRef } from "react";
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
import { type PendingUserInput } from "../../session-logic";
import {
derivePendingUserInputProgress,
@@ -61,11 +61,36 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
const onAdvanceRef = useRef(onAdvance);
const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
questionId: string;
optionLabel: string;
} | null>(null);
useEffect(() => {
onAdvanceRef.current = onAdvance;
}, [onAdvance]);
useEffect(() => {
if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
return;
}
if (optimisticSingleSelect.questionId !== activeQuestion.id) {
setOptimisticSingleSelect(null);
return;
}
if (
progress.customAnswer.trim().length === 0 &&
progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel)
) {
setOptimisticSingleSelect(null);
}
}, [
activeQuestion,
optimisticSingleSelect,
progress.customAnswer,
progress.selectedOptionLabels,
]);
// Clear auto-advance timer on unmount
useEffect(() => {
return () => {
@@ -76,10 +101,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
}, []);
const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
onToggleOption(questionId, optionLabel);
if (activeQuestion?.multiSelect) {
onToggleOption(questionId, optionLabel);
return;
}
setOptimisticSingleSelect({ questionId, optionLabel });
onToggleOption(questionId, optionLabel);
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
@@ -123,64 +150,77 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
return null;
}
const customAnswerActive = progress.customAnswer.trim().length > 0;
return (
<div className="px-4 py-3 sm:px-5">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
{questionIndex + 1}/{prompt.questions.length}
</span>
) : null}
<span className="text-[11px] font-semibold tracking-widest text-muted-foreground/50 uppercase">
{activeQuestion.header}
<div className="mb-2 flex items-center gap-3">
<span className="text-[11px] font-semibold tracking-widest text-muted-foreground/55 uppercase">
{activeQuestion.header}
</span>
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
{questionIndex + 1}/{prompt.questions.length}
</span>
</div>
) : null}
</div>
<p className="mt-1.5 text-sm text-foreground/90">{activeQuestion.question}</p>
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
{activeQuestion.multiSelect ? (
<p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
) : null}
<div className="mt-3 space-y-1">
<div className="mt-3 space-y-1.5">
{activeQuestion.options.map((option, index) => {
const isSelected = progress.selectedOptionLabels.includes(option.label);
const isOptimisticallySelected =
optimisticSingleSelect?.questionId === activeQuestion.id &&
optimisticSingleSelect.optionLabel === option.label;
const isSelected =
isOptimisticallySelected ||
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
const shortcutKey = index < 9 ? index + 1 : null;
return (
<button
key={`${activeQuestion.id}:${option.label}`}
type="button"
disabled={isResponding}
onClick={() => handleOptionSelection(activeQuestion.id, option.label)}
className={cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-all duration-150",
isSelected
? "border-blue-500/40 bg-blue-500/8 text-foreground"
: "border-transparent bg-muted/20 text-foreground/80 hover:bg-muted/40 hover:border-border/40",
isResponding && "opacity-50 cursor-not-allowed",
)}
>
{shortcutKey !== null ? (
const className = cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
isSelected
? "border-primary/30 bg-primary/8 text-foreground"
: "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
isResponding && "opacity-50 cursor-not-allowed",
!isResponding && "cursor-pointer",
);
const content = (
<>
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="text-xs text-muted-foreground/50">{option.description}</span>
) : null}
</div>
{isSelected ? (
<CheckIcon className="size-3.5 shrink-0 text-primary" />
) : shortcutKey !== null ? (
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded text-[11px] font-medium tabular-nums transition-colors duration-150",
isSelected
? "bg-blue-500/20 text-blue-400"
: "bg-muted/40 text-muted-foreground/50 group-hover:bg-muted/60 group-hover:text-muted-foreground/70",
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
"bg-background/35 text-muted-foreground/70 group-hover:border-border/70 group-hover:text-muted-foreground",
)}
>
{shortcutKey}
</kbd>
) : null}
<div className="min-w-0 flex-1">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="ml-2 text-xs text-muted-foreground/50">
{option.description}
</span>
) : null}
</div>
{isSelected ? <CheckIcon className="size-3.5 shrink-0 text-blue-400" /> : null}
</button>
</>
);
return (
<div
key={`${activeQuestion.id}:${option.label}`}
role="button"
tabIndex={isResponding ? -1 : 0}
aria-disabled={isResponding}
onClick={() => {
if (isResponding) return;
handleOptionSelection(activeQuestion.id, option.label);
}}
className={className}
>
{content}
</div>
);
})}
</div>
@@ -1,4 +1,5 @@
import { memo } from "react";
import { Badge } from "../ui/badge";
export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBanner({
planTitle,
@@ -8,7 +9,13 @@ export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBann
return (
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
<div className="flex flex-wrap items-center gap-2">
<span className="uppercase text-sm tracking-[0.2em]">Plan ready</span>
<Badge
variant="info"
size="sm"
className="rounded-md px-1.5 py-0 font-semibold tracking-wide uppercase"
>
Plan Ready
</Badge>
{planTitle ? (
<span className="min-w-0 flex-1 truncate text-sm font-medium">{planTitle}</span>
) : null}
@@ -3,6 +3,7 @@ import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Spinner } from "../ui/spinner";
interface PendingActionState {
questionIndex: number;
@@ -126,7 +127,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
return (
<button
type="button"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105 sm:h-8 sm:w-8"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8"
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
@@ -195,7 +196,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
return (
<button
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"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground shadow-xs enabled:shadow-primary/24 enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-primary hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8"
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
aria-label={
@@ -211,24 +212,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
}
>
{isConnecting || isSendBusy ? (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
className="animate-spin"
aria-hidden="true"
>
<circle
cx="7"
cy="7"
r="5.5"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeDasharray="20 12"
/>
</svg>
<Spinner className="size-3.5" aria-hidden="true" />
) : (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<path
@@ -12,13 +12,20 @@ function formatPercentage(value: number | null): string | null {
return `${Math.round(value)}%`;
}
export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
const { usage } = props;
export function ContextWindowMeter(props: {
usage: ContextWindowSnapshot;
providerDisplayName?: string | null;
}) {
const { usage, providerDisplayName } = props;
const usedPercentage = formatPercentage(usage.usedPercentage);
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
const radius = 9.75;
const circumference = 2 * Math.PI * radius;
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
const totalProcessedTokens = usage.totalProcessedTokens ?? null;
const showTotalProcessed = totalProcessedTokens !== null && totalProcessedTokens > 0;
const isOverloaded = normalizedPercentage > 90;
const usageColor = isOverloaded ? "var(--color-red-500)" : "var(--color-blue-500)";
return (
<Popover>
@@ -29,17 +36,21 @@ export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
render={
<button
type="button"
className="group inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-85"
className={cn(
"inline-flex size-6 cursor-pointer items-center justify-center rounded-full border border-transparent text-muted-foreground outline-none transition-colors",
"hover:bg-accent data-[pressed]:bg-accent",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
)}
aria-label={
usage.maxTokens !== null && usedPercentage
? `Context window ${usedPercentage} used`
: `Context window ${formatContextWindowTokens(usage.usedTokens)} tokens used`
}
>
<span className="relative flex h-6 w-6 items-center justify-center">
<span className="relative flex size-4 items-center justify-center">
<svg
viewBox="0 0 24 24"
className="-rotate-90 absolute inset-0 h-full w-full transform-gpu"
className="-rotate-90 absolute inset-0 size-full transform-gpu"
aria-hidden="true"
>
<circle
@@ -47,7 +58,7 @@ export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
cy="12"
r={radius}
fill="none"
stroke="color-mix(in oklab, var(--color-muted) 70%, transparent)"
stroke="color-mix(in oklab, var(--color-muted-foreground) 35%, transparent)"
strokeWidth="3"
/>
<circle
@@ -55,7 +66,7 @@ export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
cy="12"
r={radius}
fill="none"
stroke="var(--color-muted-foreground)"
stroke={usageColor}
strokeWidth="3"
strokeLinecap="round"
strokeDasharray={circumference}
@@ -63,48 +74,55 @@ export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
/>
</svg>
<span
className={cn(
"relative flex h-[15px] w-[15px] items-center justify-center rounded-full bg-background text-[8px] font-medium",
"text-muted-foreground",
)}
>
{usage.usedPercentage !== null
? Math.round(usage.usedPercentage)
: formatContextWindowTokens(usage.usedTokens)}
</span>
</span>
</button>
}
/>
<PopoverPopup tooltipStyle side="top" align="end" className="w-max max-w-none px-3 py-2">
<div className="space-y-1.5 leading-tight">
<div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
Context window
<PopoverPopup tooltipStyle side="top" align="end" className="w-64 max-w-none p-0">
<div className="flex flex-col gap-2 p-3">
<div className="flex items-center justify-between gap-3">
<div className="font-medium text-muted-foreground text-xs">Context Window</div>
{usage.maxTokens !== null && usedPercentage ? (
<div className="text-[11px] tabular-nums text-muted-foreground/70">
<span>{usedPercentage}</span>
<span className="mx-1">·</span>
<span>
{formatContextWindowTokens(usage.usedTokens)}/
{formatContextWindowTokens(usage.maxTokens ?? null)}
</span>
</div>
) : (
<div className="text-[11px] tabular-nums text-muted-foreground/70">
{formatContextWindowTokens(usage.usedTokens)}
</div>
)}
</div>
{usage.maxTokens !== null && usedPercentage ? (
<div className="whitespace-nowrap text-xs font-medium text-foreground">
<span>{usedPercentage}</span>
<span className="mx-1">⋅</span>
<span>{formatContextWindowTokens(usage.usedTokens)}</span>
<span>/</span>
<span>{formatContextWindowTokens(usage.maxTokens ?? null)} context used</span>
{usage.maxTokens !== null ? (
<div
className="h-1.5 w-full overflow-hidden rounded-full bg-muted/60"
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(normalizedPercentage)}
aria-label="Context window usage"
>
<div
className="h-full rounded-full transition-[width,background-color] duration-500 ease-out motion-reduce:transition-none"
style={{ width: `${normalizedPercentage}%`, backgroundColor: usageColor }}
/>
</div>
) : (
<div className="text-sm text-foreground">
{formatContextWindowTokens(usage.usedTokens)} tokens used so far
</div>
)}
{(usage.totalProcessedTokens ?? null) !== null &&
(usage.totalProcessedTokens ?? 0) > usage.usedTokens ? (
<div className="text-xs text-muted-foreground">
Total processed: {formatContextWindowTokens(usage.totalProcessedTokens ?? null)}{" "}
tokens
) : null}
{showTotalProcessed ? (
<div className="flex items-center justify-between gap-3 text-[11px] leading-4">
<span className="text-muted-foreground/60">Total processed</span>
<span className="font-medium tabular-nums text-muted-foreground/80">
{formatContextWindowTokens(totalProcessedTokens)}
</span>
</div>
) : null}
{usage.compactsAutomatically ? (
<div className="text-xs text-muted-foreground">
Automatically compacts its context when needed.
<div className="mt-1 text-pretty text-[11px] font-medium text-muted-foreground/70">
{providerDisplayName ?? "It"} automatically compacts its context when needed.
</div>
) : null}
</div>
+29 -4
View File
@@ -1,21 +1,46 @@
import { memo } from "react";
import { cn } from "~/lib/utils";
export function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
return stat.additions > 0 || stat.deletions > 0;
}
function formatCompactDiffCount(value: number): string {
if (value < 1000) return String(value);
if (value < 1_000_000) {
const k = value / 1000;
return `${k < 10 ? k.toFixed(1).replace(/\.0$/, "") : Math.round(k)}k`;
}
if (value < 1_000_000_000) {
const m = value / 1_000_000;
return `${m < 10 ? m.toFixed(1).replace(/\.0$/, "") : Math.round(m)}m`;
}
const b = value / 1_000_000_000;
return `${b < 10 ? b.toFixed(1).replace(/\.0$/, "") : Math.round(b)}b`;
}
export const DiffStatLabel = memo(function DiffStatLabel(props: {
additions: number;
deletions: number;
className?: string;
showParentheses?: boolean;
layout?: "aligned" | "inline";
}) {
const { additions, deletions, showParentheses = false } = props;
const { additions, deletions, className, showParentheses = false, layout = "aligned" } = props;
return (
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span className="text-success">+{additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{deletions}</span>
<span
className={cn(
layout === "inline"
? "inline-flex items-center gap-1 tabular-nums align-middle"
: "inline-grid grid-cols-[4ch_4ch] gap-2 text-right tabular-nums align-middle",
className,
)}
>
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
);
@@ -0,0 +1,39 @@
import { inferEntryKindFromPath } from "../../vscode-icons";
import {
CHAT_INLINE_CHIP_CLASS_NAME,
CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_CHIP_CLASS_NAME,
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
} from "../composerInlineChip";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
export const FILE_TAG_CHIP_CLASS_NAME = COMPOSER_INLINE_CHIP_CLASS_NAME;
export const CHAT_FILE_TAG_CHIP_CLASS_NAME = CHAT_INLINE_CHIP_CLASS_NAME;
export function FileTagChipContent(props: {
path: string;
label: string;
theme: "light" | "dark";
selectable?: boolean;
}) {
return (
<>
<VscodeEntryIcon
pathValue={props.path}
kind={inferEntryKindFromPath(props.path)}
theme={props.theme}
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
/>
<span
className={
props.selectable
? CHAT_INLINE_CHIP_LABEL_CLASS_NAME
: COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME
}
>
{props.label}
</span>
</>
);
}
@@ -68,11 +68,11 @@ export const MessageCopyButton = memo(function MessageCopyButton({
type="button"
size={size}
variant={variant}
className={cn(className)}
className={cn("text-muted-foreground hover:text-foreground", className)}
/>
}
>
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
{isCopied ? <CheckIcon className="size-3 text-primary" /> : <CopyIcon className="size-3" />}
</TooltipTrigger>
<TooltipPopup>
<p>Copy to clipboard</p>
@@ -7,6 +7,8 @@ import { page } from "vite-plus/test/browser";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
import { getVscodeIconUrlForEntry } from "../../vscode-icons";
const scrollToEndSpy = vi.fn();
const getStateSpy = vi.fn(() => ({ isAtEnd: true }));
@@ -52,11 +54,9 @@ function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
latestTurn: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: vi.fn(),
@@ -94,6 +94,21 @@ function buildUserTimelineEntry(text: string) {
};
}
function buildAssistantTimelineEntry(text: string) {
return {
id: "entry-assistant-1",
kind: "message" as const,
createdAt: MESSAGE_CREATED_AT,
message: {
id: "message-assistant-1" as never,
role: "assistant" as const,
text,
createdAt: MESSAGE_CREATED_AT,
streaming: false,
},
};
}
describe("MessagesTimeline", () => {
afterEach(() => {
scrollToEndSpy.mockReset();
@@ -114,9 +129,9 @@ describe("MessagesTimeline", () => {
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:00.000Z",
label: "thinking",
label: "read files",
detail: "Inspecting repository state",
tone: "thinking",
tone: "tool",
},
},
]}
@@ -127,7 +142,51 @@ describe("MessagesTimeline", () => {
await expect
.element(page.getByText("Send a message to start the conversation."))
.not.toBeInTheDocument();
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
} finally {
await screen.unmount();
}
});
it("uses accessible expansion instead of native titles or preview tooltips for work entry details", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
workspaceRoot="/repo"
timelineEntries={[
{
id: "work-command",
kind: "work",
createdAt: MESSAGE_CREATED_AT,
entry: {
id: "work-command",
createdAt: MESSAGE_CREATED_AT,
label: "command",
detail: "Inspecting generated output",
command: "git diff -- apps/web/src/components/ChatMarkdown.tsx",
rawCommand: "git diff -- apps/web/src/components/ChatMarkdown.tsx --stat",
changedFiles: ["/repo/apps/web/src/components/ChatMarkdown.tsx"],
tone: "tool",
},
},
]}
/>,
);
try {
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
const commandTrigger = page.getByLabelText(
"Command - git diff -- apps/web/src/components/ChatMarkdown.tsx",
);
await commandTrigger.hover();
expect(document.querySelector('[data-slot="tooltip-popup"]')).toBeNull();
await commandTrigger.click();
await expect
.element(page.getByText("git diff -- apps/web/src/components/ChatMarkdown.tsx --stat"))
.toBeVisible();
} finally {
await screen.unmount();
}
@@ -161,16 +220,16 @@ describe("MessagesTimeline", () => {
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:00.000Z",
label: "thinking",
label: "read files",
detail: "Inspecting repository state",
tone: "thinking",
tone: "tool",
},
},
]}
/>,
);
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
expect(props.onIsAtEndChange).toHaveBeenCalledWith(true);
expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false });
expect(requestAnimationFrameSpy).toHaveBeenCalled();
@@ -261,4 +320,162 @@ describe("MessagesTimeline", () => {
await screen.unmount();
}
});
it("renders user messages as markdown with chat-style line breaks", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
"## Plan\nuse **bold** and [a link](https://example.com)\nsecond line",
),
]}
/>,
);
try {
await expect.element(page.getByRole("heading", { level: 2, name: "Plan" })).toBeVisible();
await expect
.element(page.getByRole("link", { name: "a link" }))
.toHaveAttribute("href", "https://example.com");
const messageBody = document.querySelector("[data-user-message-body='true']");
expect(messageBody?.querySelector("strong")?.textContent).toBe("bold");
// remark-breaks: the single newline between the inline runs is a <br>.
expect(messageBody?.querySelectorAll("p br").length).toBe(1);
} finally {
await screen.unmount();
}
});
it("renders markdown file tags in user and assistant messages", async () => {
const fileLink = "[package.json](path/to/package.json)";
const screen = await render(
<MessagesTimeline
{...buildProps()}
markdownCwd="/repo/project"
timelineEntries={[
buildUserTimelineEntry(`Review ${fileLink}`),
buildAssistantTimelineEntry(`I reviewed ${fileLink}`),
]}
/>,
);
try {
const userFileLink = document.querySelector(
'[data-message-role="user"] .chat-markdown-file-link',
);
const assistantFileLink = document.querySelector(
'[data-message-role="assistant"] .chat-markdown-file-link',
);
expect(userFileLink?.textContent).toContain("package.json");
expect(userFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json");
expect(assistantFileLink?.textContent).toContain("package.json");
expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json");
} finally {
await screen.unmount();
}
});
it("uses the file path without line suffix for markdown file tag icons", async () => {
const fileLink = "[package.json](path/to/package.json:25)";
const screen = await render(
<MessagesTimeline
{...buildProps()}
markdownCwd="/repo/project"
timelineEntries={[buildAssistantTimelineEntry(`Updated ${fileLink}`)]}
/>,
);
try {
const assistantFileLink = document.querySelector(
'[data-message-role="assistant"] .chat-markdown-file-link',
);
const icon = assistantFileLink?.querySelector("img");
expect(assistantFileLink?.textContent).toContain("package.json");
expect(assistantFileLink?.textContent).toContain("L25");
expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json:25");
expect(icon?.getAttribute("src")).toBe(
getVscodeIconUrlForEntry("/repo/project/path/to/package.json", "file", "dark"),
);
} finally {
await screen.unmount();
}
});
it("folds settled-turn work behind a Worked-for row and expands it on click", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-commentary",
kind: "message" as const,
createdAt: "2026-04-13T12:00:00.000Z",
message: {
id: "message-commentary" as never,
role: "assistant" as const,
text: "Let me look around first.",
turnId: "turn-1" as never,
createdAt: "2026-04-13T12:00:00.000Z",
completedAt: "2026-04-13T12:00:02.000Z",
streaming: false,
},
},
{
id: "entry-work",
kind: "work" as const,
createdAt: "2026-04-13T12:00:05.000Z",
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:05.000Z",
turnId: "turn-1" as never,
label: "read files",
detail: "Inspecting repository state",
tone: "tool" as const,
},
},
{
id: "entry-final",
kind: "message" as const,
createdAt: "2026-04-13T12:00:20.000Z",
message: {
id: "message-final" as never,
role: "assistant" as const,
text: "All done.",
turnId: "turn-1" as never,
createdAt: "2026-04-13T12:00:20.000Z",
completedAt: "2026-04-13T12:00:30.000Z",
streaming: false,
},
},
]}
/>,
);
try {
const foldButton = page.getByRole("button", { name: "Worked for 30s" });
await expect.element(foldButton).toBeVisible();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
expect(document.body.textContent).toContain("All done.");
expect(document.body.textContent).not.toContain("Let me look around first.");
expect(document.body.textContent).not.toContain("Inspecting repository state");
await foldButton.click();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "true");
expect(document.body.textContent).toContain("Let me look around first.");
expect(document.body.textContent).toContain("Inspecting repository state");
await foldButton.click();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
expect(document.body.textContent).not.toContain("Inspecting repository state");
} finally {
await screen.unmount();
}
});
});
@@ -250,7 +250,7 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: "assistant-final-entry",
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -265,7 +265,6 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRows).toHaveLength(2);
expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
});
it("marks only the active assistant turn as streaming for copy controls", () => {
@@ -300,11 +299,13 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: "assistant-two-entry",
completionSummary: "done",
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:19Z",
completedAt: null,
},
isWorking: false,
activeTurnInProgress: true,
activeTurnId: "turn-2" as never,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
@@ -316,9 +317,7 @@ describe("deriveMessagesTimelineRows", () => {
);
expect(assistantRows[0]?.assistantCopyStreaming).toBe(false);
expect(assistantRows[0]?.completionSummary).toBeNull();
expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
expect(assistantRows[1]?.completionSummary).toBe("done");
});
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
@@ -360,7 +359,6 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map([
@@ -381,6 +379,441 @@ describe("deriveMessagesTimelineRows", () => {
expect(userRow?.revertTurnCount).toBe(1);
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
});
it("folds settled-turn commentary and work behind a Worked-for row", () => {
const timelineEntries = [
{
id: "user-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-1" as never,
role: "user" as const,
text: "Build it",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "assistant-thought-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:05Z",
message: {
id: "assistant-thought" as never,
role: "assistant" as const,
text: "Looking around first.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:05Z",
completedAt: "2026-01-01T00:00:06Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work" as const,
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "assistant-final-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant" as const,
text: "Done",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:22Z",
streaming: false,
},
},
];
const collapsedRows = deriveMessagesTimelineRows({
timelineEntries,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const foldRow = collapsedRows.find(
(row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
row.kind === "turn-fold",
);
expect(foldRow?.turnId).toBe("turn-1");
expect(foldRow?.expanded).toBe(false);
// User message boundary (00:00:00) → terminal message completedAt (00:00:22).
expect(foldRow?.label).toBe("Worked for 22s");
expect(collapsedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"assistant-final-entry",
]);
const expandedRows = deriveMessagesTimelineRows({
timelineEntries,
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(expandedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"assistant-thought-entry",
"work-entry-1",
"assistant-final-entry",
]);
expect(
expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
).toBeDefined();
});
it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
// A steer ends the previous turn early: its only message completes the
// instant it is created, and trailing work entries land after it. The
// fold duration must span from the user message that started the turn to
// the last entry, not message createdAt → message completedAt (~0ms).
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-1" as never,
role: "user" as const,
text: "do it once more",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "assistant-commentary-entry",
kind: "message",
createdAt: "2026-01-01T00:00:09Z",
message: {
id: "assistant-commentary" as never,
role: "assistant" as const,
text: "Kicking off call 1.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:09Z",
completedAt: "2026-01-01T00:00:09Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:12Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:12Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "steer-user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:14Z",
message: {
id: "user-2" as never,
role: "user" as const,
text: "actually do 15",
turnId: null,
createdAt: "2026-01-01T00:00:14Z",
streaming: false,
},
},
{
id: "assistant-next-turn-entry",
kind: "message",
createdAt: "2026-01-01T00:00:17Z",
message: {
id: "assistant-next" as never,
role: "assistant" as const,
text: "One down — adjusting.",
turnId: "turn-2" as never,
createdAt: "2026-01-01T00:00:17Z",
streaming: true,
},
},
],
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:14Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:14Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const foldRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> =>
row.kind === "turn-fold",
);
// User message (00:00:00) → trailing work entry (00:00:12).
expect(foldRow?.turnId).toBe("turn-1");
expect(foldRow?.label).toBe("Worked for 12s");
});
it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:05Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:05Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "interrupted",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:47Z",
},
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows).toEqual([
expect.objectContaining({
kind: "turn-fold",
turnId: "turn-1",
label: "You stopped after 47s",
expanded: false,
}),
]);
});
it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
// Right after send, isWorking is true but latestTurn still points at the
// previous, settled turn — it must stay folded through that window.
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:05Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:05Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "assistant-final-entry",
kind: "message",
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant",
text: "Done",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:22Z",
streaming: false,
},
},
{
id: "user-followup-entry",
kind: "message",
createdAt: "2026-01-01T00:01:00Z",
message: {
id: "user-followup" as never,
role: "user",
text: "yooo",
turnId: null,
createdAt: "2026-01-01T00:01:00Z",
streaming: false,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "completed",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:22Z",
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:01:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.map((row) => row.id)).toEqual([
"turn-fold:turn-1",
"assistant-final-entry",
"user-followup-entry",
"working-indicator-row",
]);
const finalRow = rows.find((row) => row.id === "assistant-final-entry");
expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true);
});
it("does not fold the active in-progress turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:05Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Working on it.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:05Z",
completedAt: "2026-01-01T00:00:06Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "running",
startedAt: "2026-01-01T00:00:00Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
expect(rows.map((row) => row.id)).toEqual([
"assistant-thought-entry",
"work-entry-1",
"working-indicator-row",
]);
});
it("only shows assistant metadata on the terminal assistant message", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:10Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Checking first.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:10Z",
completedAt: "2026-01-01T00:00:11Z",
streaming: false,
},
},
{
id: "assistant-final-entry",
kind: "message",
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant",
text: "Done.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:30Z",
streaming: false,
},
},
],
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const assistantRows = rows.filter(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "assistant",
);
expect(assistantRows.map((row) => row.showAssistantMeta)).toEqual([false, true]);
});
it("withholds assistant metadata while the active turn is still in progress", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:10Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Working on it.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:10Z",
completedAt: "2026-01-01T00:00:11Z",
streaming: false,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "running",
startedAt: "2026-01-01T00:00:00Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const assistantRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "assistant",
);
expect(assistantRow?.showAssistantMeta).toBe(false);
expect(assistantRow?.showAssistantCopyButton).toBe(false);
});
});
describe("computeStableMessagesTimelineRows", () => {
@@ -417,7 +850,6 @@ describe("computeStableMessagesTimelineRows", () => {
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -467,7 +899,6 @@ describe("computeStableMessagesTimelineRows", () => {
entry: secondWorkEntry,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -522,7 +953,6 @@ describe("computeStableMessagesTimelineRows", () => {
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -1,9 +1,26 @@
import * as Equal from "effect/Equal";
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type TurnId } from "@t3tools/contracts";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
function computeElapsedMs(startIso: string, endIso: string): number | null {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
return Math.max(0, end - start);
}
function maxIsoTimestamp(a: string | null, b: string | null): string | null {
if (a === null) return b;
if (b === null) return a;
const aMs = Date.parse(a);
const bMs = Date.parse(b);
if (!Number.isFinite(aMs)) return b;
if (!Number.isFinite(bMs)) return a;
return bMs > aMs ? b : a;
}
export interface TimelineDurationMessage {
id: string;
@@ -12,6 +29,11 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
export type TimelineLatestTurn = Pick<
OrchestrationLatestTurn,
"turnId" | "state" | "startedAt" | "completedAt"
>;
export type MessagesTimelineRow =
| {
kind: "work";
@@ -19,14 +41,21 @@ export type MessagesTimelineRow =
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "turn-fold";
id: string;
createdAt: string;
turnId: TurnId;
label: string;
expanded: boolean;
}
| {
kind: "message";
id: string;
createdAt: string;
message: ChatMessage;
durationStart: string;
showCompletionDivider: boolean;
completionSummary: string | null;
showAssistantMeta: boolean;
showAssistantCopyButton: boolean;
assistantCopyStreaming: boolean;
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
@@ -110,13 +139,161 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
return new Set(lastAssistantMessageIdByResponseKey.values());
}
interface TurnFold {
turnId: TurnId;
anchorEntryId: string;
createdAt: string;
hiddenEntryIds: ReadonlySet<string>;
label: string;
}
/**
* The latest turn counts as unsettled while it is still running (or has not
* recorded a completion). This is deliberately keyed on the turn's own
* lifecycle rather than transient working state: right after the user sends
* a message, the previous turn is still the "active" one until the server
* creates the new turn, and folding must not flicker through that window.
*/
function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null {
if (!latestTurn) {
return null;
}
const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
return isSettled ? null : latestTurn.turnId;
}
/**
* Settled turns fold their commentary and tool activity behind a
* "Worked for ..." row anchored at the turn's first foldable entry; the
* terminal assistant message stays visible below the fold.
*/
function deriveTurnFolds(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
terminalAssistantMessageIds: ReadonlySet<string>;
latestTurn: TimelineLatestTurn | null;
unsettledTurnId: TurnId | null;
}): ReadonlyMap<string, TurnFold> {
interface TurnGroup {
entries: Array<TimelineEntry>;
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
hasStreamingMessage: boolean;
/**
* The user message that kicked the turn off. Entry timestamps alone
* undercount the duration (the first entry appears only once the
* provider starts producing output), and a turn cut short by a steer may
* hold a single instantaneous commentary message.
*/
startBoundary: string | null;
}
const groupsByTurnId = new Map<TurnId, TurnGroup>();
let pendingUserBoundary: string | null = null;
for (const entry of input.timelineEntries) {
if (entry.kind === "message" && entry.message.role === "user") {
pendingUserBoundary = entry.message.createdAt;
continue;
}
const turnId =
entry.kind === "message" && entry.message.role === "assistant"
? (entry.message.turnId ?? null)
: entry.kind === "work"
? (entry.entry.turnId ?? null)
: null;
if (!turnId) {
continue;
}
let group = groupsByTurnId.get(turnId);
if (!group) {
group = {
entries: [],
terminalEntry: null,
hasStreamingMessage: false,
// Each user boundary starts at most one turn; a second turn after the
// same user message (e.g. a steer-superseded continuation) falls back
// to its own first entry.
startBoundary: pendingUserBoundary,
};
pendingUserBoundary = null;
groupsByTurnId.set(turnId, group);
}
group.entries.push(entry);
if (entry.kind === "message") {
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
group.terminalEntry = entry;
}
if (entry.message.streaming) {
group.hasStreamingMessage = true;
}
}
}
const foldsByAnchorEntryId = new Map<string, TurnFold>();
for (const [turnId, group] of groupsByTurnId) {
if (turnId === input.unsettledTurnId) {
continue;
}
if (group.hasStreamingMessage) {
continue;
}
const hiddenEntryIds = new Set<string>();
for (const entry of group.entries) {
if (entry.id !== group.terminalEntry?.id) {
hiddenEntryIds.add(entry.id);
}
}
if (hiddenEntryIds.size === 0) {
continue;
}
const firstEntry = group.entries[0];
const lastEntry = group.entries.at(-1);
if (!firstEntry || !lastEntry) {
continue;
}
const isLatestInterruptedTurn =
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
// A turn cut short by a steer leaves trailing work entries behind its
// terminal message — take whichever ended last.
const lastEntryEnd =
lastEntry.kind === "message"
? (lastEntry.message.completedAt ?? lastEntry.createdAt)
: lastEntry.createdAt;
const elapsedMs =
input.latestTurn?.turnId === turnId &&
input.latestTurn.startedAt &&
input.latestTurn.completedAt
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
: computeElapsedMs(
group.startBoundary ?? firstEntry.createdAt,
maxIsoTimestamp(group.terminalEntry?.message.completedAt ?? null, lastEntryEnd) ??
lastEntryEnd,
);
const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
const label = isLatestInterruptedTurn
? duration
? `You stopped after ${duration}`
: "You stopped this response"
: duration
? `Worked for ${duration}`
: "Worked";
foldsByAnchorEntryId.set(firstEntry.id, {
turnId,
anchorEntryId: firstEntry.id,
createdAt: firstEntry.createdAt,
hiddenEntryIds,
label,
});
}
return foldsByAnchorEntryId;
}
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
completionSummary?: string | null;
latestTurn?: TimelineLatestTurn | null;
expandedTurnIds?: ReadonlySet<TurnId>;
isWorking: boolean;
activeTurnInProgress?: boolean;
activeTurnId?: TurnId | null;
activeTurnStartedAt: string | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
@@ -126,6 +303,21 @@ export function deriveMessagesTimelineRows(input: {
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null);
const foldsByAnchorEntryId = deriveTurnFolds({
timelineEntries: input.timelineEntries,
terminalAssistantMessageIds,
latestTurn: input.latestTurn ?? null,
unsettledTurnId,
});
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorEntryId.values()) {
if (!input.expandedTurnIds?.has(fold.turnId)) {
for (const entryId of fold.hiddenEntryIds) {
collapsedEntryIds.add(entryId);
}
}
}
for (let index = 0; index < input.timelineEntries.length; index += 1) {
const timelineEntry = input.timelineEntries[index];
@@ -133,12 +325,35 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
if (turnFold) {
nextRows.push({
kind: "turn-fold",
id: `turn-fold:${turnFold.turnId}`,
createdAt: turnFold.createdAt,
turnId: turnFold.turnId,
label: turnFold.label,
expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
});
}
if (collapsedEntryIds.has(timelineEntry.id)) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < input.timelineEntries.length) {
const nextEntry = input.timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
if (
!nextEntry ||
nextEntry.kind !== "work" ||
collapsedEntryIds.has(nextEntry.id) ||
foldsByAnchorEntryId.has(nextEntry.id)
) {
break;
}
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
@@ -164,26 +379,28 @@ export function deriveMessagesTimelineRows(input: {
const assistantTurnStillInProgress =
timelineEntry.message.role === "assistant" &&
input.activeTurnInProgress === true &&
input.activeTurnId != null &&
timelineEntry.message.turnId === input.activeTurnId;
unsettledTurnId !== null &&
timelineEntry.message.turnId === unsettledTurnId;
const showCompletionDivider =
const durationStart =
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
// While the turn is still running, the latest assistant message is only
// provisionally terminal — withhold the metadata row until the turn
// settles so commentary doesn't flash timestamps mid-work.
const showAssistantMeta =
timelineEntry.message.role === "assistant" &&
input.completionDividerBeforeEntryId === timelineEntry.id;
terminalAssistantMessageIds.has(timelineEntry.message.id) &&
!assistantTurnStillInProgress;
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider,
completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null,
showAssistantCopyButton:
timelineEntry.message.role === "assistant" &&
terminalAssistantMessageIds.has(timelineEntry.message.id),
durationStart,
showAssistantMeta,
showAssistantCopyButton: showAssistantMeta,
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
assistantTurnDiffSummary:
timelineEntry.message.role === "assistant"
@@ -235,6 +452,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "working":
return a.createdAt === (b as typeof a).createdAt;
case "turn-fold": {
const bf = b as typeof a;
return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
}
case "proposed-plan":
return a.proposedPlan === (b as typeof a).proposedPlan;
@@ -246,8 +468,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
return (
a.message === bm.message &&
a.durationStart === bm.durationStart &&
a.showCompletionDivider === bm.showCompletionDivider &&
a.completionSummary === bm.completionSummary &&
a.showAssistantMeta === bm.showAssistantMeta &&
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
@@ -94,11 +94,9 @@ function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
latestTurn: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
@@ -188,7 +186,8 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("Terminal 1 lines 1-5");
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
expect(markup).toContain("yoo what&#x27;s</p>");
expect(markup).toContain('<span aria-hidden="true"> </span>');
expect(markup).toContain("Show full message");
}, 20_000);
@@ -228,7 +227,7 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
expect(markup).toContain("work log");
});
it("formats changed file paths from the workspace root", async () => {
@@ -296,4 +295,31 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("&lt;review_comment");
expect(markup).not.toContain("&lt;/review_comment&gt;");
});
it("renders a failure marker for failed tool lifecycle entries", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Glob",
tone: "tool",
toolLifecycleStatus: "failed",
detail: "No files found",
},
},
]}
/>,
);
expect(markup).toContain("lucide-x");
expect(markup).toContain('aria-label="Tool call failed"');
});
});
File diff suppressed because it is too large. Load diff
+79 -62
View File
@@ -1,6 +1,6 @@
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
import { memo } from "react";
import { StarIcon } from "lucide-react";
import { CheckIcon, StarIcon } from "lucide-react";
import {
getDisplayModelName,
getTriggerDisplayModelLabel,
@@ -27,11 +27,13 @@ export const ModelListRow = memo(function ModelListRow(props: {
providerDisplayName: string;
providerAccentColor?: string | undefined;
isFavorite: boolean;
isSelected: boolean;
showProvider: boolean;
preferShortName?: boolean;
useTriggerLabel?: boolean;
showNewBadge?: boolean;
jumpLabel?: string | null;
disabledReason?: string | null;
onToggleFavorite: () => void;
}) {
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null;
@@ -39,85 +41,100 @@ export const ModelListRow = memo(function ModelListRow(props: {
? `${props.providerDisplayName} · ${props.model.subProvider}`
: props.providerDisplayName;
return (
const row = (
<ComboboxItem
hideIndicator
index={props.index}
value={`${props.instanceId}:${props.model.slug}`}
contentClassName="flex w-full items-start gap-2"
disabled={Boolean(props.disabledReason)}
contentClassName="flex w-full items-center gap-3"
className={cn(
"w-full cursor-pointer rounded px-3 py-2 transition-colors group",
"data-highlighted:bg-muted data-selected:bg-accent data-selected:text-foreground",
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
"data-highlighted:bg-muted/56 data-selected:bg-transparent data-selected:text-foreground data-selected:ring-0",
props.disabledReason &&
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
)}
>
<Tooltip>
<TooltipTrigger
render={
<button
className="mt-0.5 shrink-0 cursor-pointer opacity-40 transition-opacity group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
props.onToggleFavorite();
}}
onKeyDown={(event) => {
event.stopPropagation();
}}
type="button"
aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"}
>
<StarIcon
className={cn("size-4", props.isFavorite && "fill-current text-yellow-500")}
/>
</button>
}
/>
<TooltipPopup side="top" align="center">
{props.isFavorite ? "Remove from favorites" : "Add to favorites"}
</TooltipPopup>
</Tooltip>
<div className="min-w-0 flex-1 text-left">
<div className="flex items-center justify-between gap-2 min-w-0">
<div className="text-xs font-medium leading-snug flex items-center gap-2 min-w-0">
<span className="truncate">
{props.useTriggerLabel
? getTriggerDisplayModelLabel(props.model)
: getDisplayModelName(
props.model,
props.preferShortName ? { preferShortName: true } : undefined,
)}
</span>
{props.showNewBadge ? (
<span
className="shrink-0 rounded border border-amber-500/35 bg-amber-500/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-amber-800 dark:border-amber-400/30 dark:bg-amber-400/12 dark:text-amber-200"
aria-label="New model"
>
New
</span>
) : null}
<div className="flex min-w-0 items-center gap-2">
<div className="min-w-0 truncate text-xs font-medium leading-snug">
{props.useTriggerLabel
? getTriggerDisplayModelLabel(props.model)
: getDisplayModelName(
props.model,
props.preferShortName ? { preferShortName: true } : undefined,
)}
</div>
{props.jumpLabel ? (
<Kbd className="h-4 min-w-0 shrink-0 rounded-sm px-1.5 text-[10px]">
{props.jumpLabel}
</Kbd>
{props.isSelected ? <CheckIcon className="size-3.5 shrink-0 text-blue-400" /> : null}
{props.showNewBadge ? (
<span
className="shrink-0 rounded border border-amber-500/35 bg-amber-500/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-amber-800 dark:border-amber-400/30 dark:bg-amber-400/12 dark:text-amber-200"
aria-label="New model"
>
New
</span>
) : null}
</div>
{props.showProvider && (
<div className="flex items-center gap-1 mt-0.5">
<div className="mt-1 flex items-center gap-1.5">
{ProviderIcon ? <ProviderIcon className="size-3 shrink-0" /> : null}
{props.providerAccentColor ? (
<span
className="size-1.5 shrink-0 rounded-full"
style={{ backgroundColor: props.providerAccentColor }}
aria-hidden
/>
) : null}
<span className="text-xs font-normal leading-snug text-muted-foreground/70 truncate">
<span className="truncate text-xs font-normal leading-snug text-muted-foreground/70">
{providerLabel}
</span>
</div>
)}
</div>
<div className="flex shrink-0 items-center gap-1.5">
{props.jumpLabel ? (
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">{props.jumpLabel}</Kbd>
) : null}
<Tooltip>
<TooltipTrigger
render={
<button
className={cn(
"relative -mr-1 flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/70 opacity-64 transition-[background-color,color,opacity] hover:bg-background/70 hover:text-foreground hover:opacity-100 group-hover:opacity-100 pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11",
props.isFavorite && "text-foreground opacity-100",
)}
onClick={(event) => {
event.stopPropagation();
props.onToggleFavorite();
}}
onKeyDown={(event) => {
event.stopPropagation();
}}
disabled={Boolean(props.disabledReason)}
type="button"
aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"}
>
<StarIcon
className={cn(
"size-3.5 sm:size-3",
props.isFavorite && "fill-current text-yellow-500",
)}
/>
</button>
}
/>
<TooltipPopup side="top" align="center">
{props.isFavorite ? "Remove from favorites" : "Add to favorites"}
</TooltipPopup>
</Tooltip>
</div>
</ComboboxItem>
);
if (!props.disabledReason) {
return row;
}
return (
<Tooltip>
<TooltipTrigger render={row} />
<TooltipPopup side="left" align="center" className="max-w-64 text-balance leading-snug">
{props.disabledReason}
</TooltipPopup>
</Tooltip>
);
});
@@ -4,14 +4,15 @@ import {
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { resolveSelectableModel } from "@t3tools/shared/model";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { SearchIcon } from "lucide-react";
import { ModelListRow } from "./ModelListRow";
import { ModelPickerSidebar } from "./ModelPickerSidebar";
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxList } from "../ui/combobox";
import { ModelEsque, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils";
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox";
import { ModelEsque } from "./providerIconUtils";
import {
modelPickerJumpCommandForIndex,
modelPickerJumpIndexFromCommand,
@@ -81,17 +82,21 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
terminalOpen: boolean;
onRequestClose?: () => void;
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
}) {
const {
keybindings: providedKeybindings,
modelOptionsByInstance,
instanceEntries,
getModelDisabledReason,
onInstanceModelChange,
} = props;
const [searchQuery, setSearchQuery] = useState("");
const [showTopScrollFade, setShowTopScrollFade] = useState(false);
const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
const listRegionRef = useRef<HTMLDivElement>(null);
const modelListRef = useRef<LegendListRef | null>(null);
const highlightedModelKeyRef = useRef<string | null>(null);
const favorites = useSettings((s) => s.favorites ?? []);
const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
@@ -213,16 +218,34 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
const isLocked = props.lockedProvider !== null;
const isSearching = searchQuery.trim().length > 0;
const lockedInstanceEntries = useMemo(
() =>
props.lockedProvider ? instanceEntries.filter((entry) => matchesLockedProvider(entry)) : [],
[instanceEntries, matchesLockedProvider, props.lockedProvider],
);
const showLockedInstanceSidebar = isLocked && lockedInstanceEntries.length > 1;
const showSidebar = !isSearching && (!isLocked || showLockedInstanceSidebar);
const sidebarInstanceEntries = showLockedInstanceSidebar
? lockedInstanceEntries
: instanceEntries;
const lockedDisabledInstanceIds = useMemo(() => {
if (!isLocked) {
return undefined;
}
const disabled = new Set<ProviderInstanceId>();
for (const entry of instanceEntries) {
if (!matchesLockedProvider(entry)) {
disabled.add(entry.instanceId);
}
}
return disabled;
}, [instanceEntries, isLocked, matchesLockedProvider]);
const sidebarInstanceEntries = useMemo(() => {
if (!isLocked) {
return instanceEntries;
}
const available: ProviderInstanceEntry[] = [];
const disabled: ProviderInstanceEntry[] = [];
for (const entry of instanceEntries) {
if (matchesLockedProvider(entry)) {
available.push(entry);
} else {
disabled.push(entry);
}
}
return [...available, ...disabled];
}, [instanceEntries, isLocked, matchesLockedProvider]);
const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
const instanceOrder = useMemo(
() => instanceEntries.map((entry) => entry.instanceId),
[instanceEntries],
@@ -308,7 +331,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
if (props.lockedProvider !== null) {
result = result.filter((m) => matchesLockedProvider(m));
if (showLockedInstanceSidebar) {
if (selectedInstanceId === "favorites") {
result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
} else {
result = result.filter((m) => m.instanceId === selectedInstanceId);
}
} else if (selectedInstanceId === "favorites") {
@@ -329,12 +354,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
matchesLockedProvider,
props.lockedProvider,
searchQuery,
showLockedInstanceSidebar,
selectedInstanceId,
]);
const handleModelSelect = useCallback(
(modelSlug: string, instanceId: ProviderInstanceId) => {
if (getModelDisabledReason?.(instanceId, modelSlug)) {
return;
}
const options = modelOptionsByInstance.get(instanceId);
if (!options) {
return;
@@ -351,7 +378,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
onInstanceModelChange(instanceId, resolvedModel);
}
},
[entryByInstanceId, modelOptionsByInstance, onInstanceModelChange],
[entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
);
const toggleFavorite = useCallback(
@@ -368,39 +395,25 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
[favorites, updateSettings],
);
const LockedProviderIcon =
isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null;
// Header label for locked mode. Use the active instance's displayName
// when the lock narrows to exactly one instance (so "Codex Personal"
// shows instead of the generic driver label); fall back to the first
// matching entry otherwise.
const lockedHeaderLabel = useMemo(() => {
if (!isLocked || !props.lockedProvider) return null;
const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry));
if (matches.length === 0) return null;
const active = matches.find((entry) => entry.instanceId === props.activeInstanceId);
return (active ?? matches[0])?.displayName ?? null;
}, [
isLocked,
matchesLockedProvider,
props.lockedProvider,
props.activeInstanceId,
instanceEntries,
]);
const modelJumpCommandByKey = useMemo(() => {
const mapping = new Map<
string,
NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
>();
for (const [visibleModelIndex, model] of filteredModels.entries()) {
const jumpCommand = modelPickerJumpCommandForIndex(visibleModelIndex);
let selectableModelIndex = 0;
for (const model of filteredModels) {
if (getModelDisabledReason?.(model.instanceId, model.slug)) {
continue;
}
const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex);
if (!jumpCommand) {
return mapping;
}
mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand);
selectableModelIndex += 1;
}
return mapping;
}, [filteredModels]);
}, [filteredModels, getModelDisabledReason]);
const modelJumpModelKeys = useMemo(
() => [...modelJumpCommandByKey.keys()],
[modelJumpCommandByKey],
@@ -418,6 +431,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)),
[filteredModels],
);
const updateModelListScrollFades = useCallback(() => {
const scrollElement = modelListRef.current?.getScrollableNode();
if (!(scrollElement instanceof HTMLElement)) {
return;
}
const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
setShowTopScrollFade(scrollElement.scrollTop > 1);
setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
}, []);
const modelJumpShortcutContext = useMemo(
() =>
({
@@ -478,72 +500,40 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
useLayoutEffect(() => {
const listRegion = listRegionRef.current;
if (!listRegion) {
return;
}
let cancelled = false;
let frame = 0;
setShowTopScrollFade(false);
setShowBottomScrollFade(filteredModelKeys.length > 5);
let nestedFrame = 0;
let timeout = 0;
const measureScrollArea = () => {
if (cancelled) {
return;
}
const viewport = listRegion.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]');
if (!viewport || viewport.scrollHeight <= viewport.clientHeight) {
return;
}
const originalScrollTop = viewport.scrollTop;
const maxScrollTop = viewport.scrollHeight - viewport.clientHeight;
if (maxScrollTop <= 0) {
return;
}
viewport.scrollTop = Math.min(originalScrollTop + 1, maxScrollTop);
viewport.scrollTop = originalScrollTop;
};
queueMicrotask(measureScrollArea);
frame = window.requestAnimationFrame(() => {
measureScrollArea();
nestedFrame = window.requestAnimationFrame(measureScrollArea);
const frame = window.requestAnimationFrame(() => {
updateModelListScrollFades();
nestedFrame = window.requestAnimationFrame(updateModelListScrollFades);
});
timeout = window.setTimeout(measureScrollArea, 0);
return () => {
cancelled = true;
window.cancelAnimationFrame(frame);
window.cancelAnimationFrame(nestedFrame);
window.clearTimeout(timeout);
};
}, [filteredModelKeys]);
}, [filteredModelKeys, updateModelListScrollFades]);
return (
<TooltipProvider delay={0}>
<div
className={cn(
"relative flex h-screen max-h-96 w-screen max-w-100 overflow-hidden rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
isLocked && !showLockedInstanceSidebar ? "flex-col" : "flex-row",
)}
className="relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]"
data-model-picker-content="true"
>
{/* Locked provider header (only shown in locked mode) */}
{isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && (
<div className="flex items-center gap-2 px-4 py-3 border-b">
<LockedProviderIcon className="size-5 shrink-0" />
<span className="font-medium text-sm">{lockedHeaderLabel}</span>
</div>
)}
{/* Sidebar (only in unlocked mode) */}
{/* Sidebar */}
{showSidebar && (
<ModelPickerSidebar
selectedInstanceId={selectedInstanceId}
onSelectInstance={handleSelectInstance}
instanceEntries={sidebarInstanceEntries}
showFavorites={!isLocked}
showComingSoon={!isLocked}
showFavorites
showComingSoon
{...(lockedDisabledInstanceIds
? {
disabledInstanceIds: lockedDisabledInstanceIds,
getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
`${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
}
: {})}
/>
)}
@@ -555,9 +545,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
filter={null}
autoHighlight
open
virtualized
value={`${props.activeInstanceId}:${props.model}`}
onItemHighlighted={(modelKey) => {
onItemHighlighted={(modelKey, eventDetails) => {
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
modelListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
}
}}
onValueChange={(modelKey) => {
if (typeof modelKey !== "string") {
@@ -569,79 +566,101 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
>
<div
className={cn(
"flex min-h-0 flex-1 flex-col overflow-hidden",
isLocked && !showLockedInstanceSidebar ? "min-w-0" : showSidebar && "border-l",
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
showSidebar && "border-l",
)}
>
{/* Search bar */}
<div className="border-b px-3 py-2">
<ComboboxInput
ref={searchInputRef}
className="[&_input]:font-sans rounded-md"
inputClassName="border-0 shadow-none ring-0 focus-visible:ring-0"
placeholder="Search models..."
showTrigger={false}
startAddon={<SearchIcon className="size-4 shrink-0 text-muted-foreground/50" />}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
props.onRequestClose?.();
return;
<div className="px-4 pt-2.5">
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
<ComboboxInput
ref={searchInputRef}
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm"
placeholder="Search models..."
showTrigger={false}
startAddon={
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
}
if (e.key === "Enter" && highlightedModelKeyRef.current) {
(
e as typeof e & { preventBaseUIHandler?: () => void }
).preventBaseUIHandler?.();
e.preventDefault();
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
props.onRequestClose?.();
return;
}
if (e.key === "Enter" && highlightedModelKeyRef.current) {
(
e as typeof e & { preventBaseUIHandler?: () => void }
).preventBaseUIHandler?.();
e.preventDefault();
e.stopPropagation();
const { instanceId, slug } = splitInstanceModelKey(
highlightedModelKeyRef.current,
);
handleModelSelect(slug, instanceId);
return;
}
e.stopPropagation();
const { instanceId, slug } = splitInstanceModelKey(
highlightedModelKeyRef.current,
);
handleModelSelect(slug, instanceId);
return;
}
e.stopPropagation();
}}
onMouseDown={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
size="sm"
/>
}}
onMouseDown={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
size="sm"
unstyled
/>
</div>
</div>
{/* Model list */}
<div
ref={listRegionRef}
className="relative min-h-0 flex-1 before:pointer-events-none before:absolute before:inset-0 before:bg-muted/40"
>
<ComboboxList className="model-picker-list size-full divide-y px-2 py-1">
{filteredModelKeys.map((modelKey, index) => {
const model = filteredModelByKey.get(modelKey);
if (!model) {
return null;
}
return (
<ModelListRow
key={modelKey}
index={index}
model={model}
instanceId={model.instanceId}
driverKind={model.driverKind}
providerDisplayName={model.instanceDisplayName}
providerAccentColor={model.instanceAccentColor}
isFavorite={favoritesSet.has(modelKey)}
showProvider={!isLocked || showLockedInstanceSidebar}
preferShortName={!isLocked}
useTriggerLabel={isLocked && !showLockedInstanceSidebar}
showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}
jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
/>
);
})}
</ComboboxList>
<div className="relative min-h-0 flex-1 overflow-hidden">
<ComboboxListVirtualized className="model-picker-list size-full min-w-0 p-0">
<LegendList<string>
ref={modelListRef}
data={filteredModelKeys}
extraData={favoritesSet}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
const model = filteredModelByKey.get(modelKey);
if (!model) {
return null;
}
const disabledReason =
getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
return (
<ModelListRow
key={modelKey}
index={index}
model={model}
instanceId={model.instanceId}
driverKind={model.driverKind}
providerDisplayName={model.instanceDisplayName}
providerAccentColor={model.instanceAccentColor}
isFavorite={favoritesSet.has(modelKey)}
isSelected={modelKey === `${props.activeInstanceId}:${props.model}`}
showProvider
preferShortName={!isLocked}
useTriggerLabel={false}
showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}
jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
disabledReason={disabledReason}
onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
/>
);
}}
estimatedItemSize={60}
drawDistance={480}
recycleItems
onLayout={updateModelListScrollFades}
onScroll={updateModelListScrollFades}
className={cn(
"scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
showTopScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]",
showBottomScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]",
)}
/>
</ComboboxListVirtualized>
</div>
<ComboboxEmpty className="not-empty:py-6 empty:h-0 text-xs font-normal leading-snug">
No models found
@@ -1,9 +1,8 @@
import { type ProviderInstanceId } from "@t3tools/contracts";
import { memo, useMemo } from "react";
import { memo, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Clock3Icon, SparklesIcon, StarIcon } from "lucide-react";
import { Gemini, GithubCopilotIcon } from "../Icons";
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { cn } from "~/lib/utils";
import type { ProviderInstanceEntry } from "../../providerInstances";
@@ -30,9 +29,8 @@ function describeUnavailableInstance(entry: ProviderInstanceEntry): string {
return msg ? `${label} — ${kind}. ${msg}` : `${label} — ${kind}.`;
}
const SELECTED_BUTTON_CLASS = "bg-background text-foreground shadow-sm";
const SELECTED_INDICATOR_CLASS =
"pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.5 -translate-y-1/2 rounded-l-full bg-primary";
"pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.75 -translate-y-1/2 rounded-l-full bg-primary";
const BADGE_BASE_CLASS =
"pointer-events-none absolute -right-0.5 top-0.5 z-10 flex size-3.5 items-center justify-center rounded-full bg-transparent shadow-sm ";
const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-amber-600 dark:text-amber-300 `;
@@ -40,6 +38,7 @@ const SOON_BADGE_CLASS = `${BADGE_BASE_CLASS} text-muted-foreground `;
/** Opens toward the rail so the list stays readable (not over the model names). */
const PICKER_TOOLTIP_SIDE = "left" as const;
const PICKER_TOOLTIP_SIDE_OFFSET = 8;
const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug";
export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
@@ -56,6 +55,9 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
showFavorites?: boolean;
/** Render non-configured coming-soon provider entries. Hidden in scoped rails. */
showComingSoon?: boolean;
/** Instance ids shown in the rail but unavailable for the current picker context. */
disabledInstanceIds?: ReadonlySet<ProviderInstanceId>;
getDisabledInstanceTooltip?: (entry: ProviderInstanceEntry) => string;
/**
* Instance id values that should render the "new" sparkle badge. Callers
* pass the subset of default built-in ids they want flagged (custom
@@ -68,6 +70,9 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
};
const showFavorites = props.showFavorites ?? true;
const showComingSoon = props.showComingSoon ?? true;
const [hoveredInstanceId, setHoveredInstanceId] = useState<ProviderInstanceId | null>(null);
const sidebarContentRef = useRef<HTMLDivElement>(null);
const [selectedIndicatorTop, setSelectedIndicatorTop] = useState<number | null>(null);
const duplicateDriverCounts = useMemo(() => {
const counts = new Map<string, number>();
for (const entry of props.instanceEntries) {
@@ -76,188 +81,248 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
return counts;
}, [props.instanceEntries]);
useLayoutEffect(() => {
const content = sidebarContentRef.current;
if (!content) {
return;
}
const selectedButton = Array.from(
content.querySelectorAll<HTMLElement>("[data-model-picker-provider]"),
).find((button) => button.dataset.modelPickerProvider === props.selectedInstanceId);
if (!selectedButton) {
setSelectedIndicatorTop(null);
return;
}
const contentRect = content.getBoundingClientRect();
const selectedButtonRect = selectedButton.getBoundingClientRect();
setSelectedIndicatorTop(
selectedButtonRect.top -
contentRect.top +
content.scrollTop +
selectedButtonRect.height / 2 -
10,
);
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
return (
<ScrollArea
hideScrollbars
scrollFade
className="w-12 shrink-0 border-r bg-muted/30"
<div
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
data-model-picker-sidebar="true"
>
<div className="flex min-h-full flex-col gap-1 p-1">
{/* Favorites section */}
{showFavorites ? (
<div className="pb-1 mb-1 border-b">
<div className="relative w-full">
{props.selectedInstanceId === "favorites" && (
<div className={SELECTED_INDICATOR_CLASS} />
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div
ref={sidebarContentRef}
className="relative flex min-h-full flex-col gap-1 px-1 pb-1 pt-0.5"
>
{selectedIndicatorTop !== null ? (
<div
data-model-picker-selected-indicator="true"
className={cn(
SELECTED_INDICATOR_CLASS,
"right-0 translate-y-0 transition-[top] duration-200 ease-out",
)}
style={{ top: selectedIndicatorTop }}
/>
) : null}
{/* Favorites section */}
{showFavorites ? (
<div className="mb-1 border-b pb-1">
<div className="relative w-full">
<Tooltip>
<TooltipTrigger
render={
<button
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
)}
onClick={() => handleSelect("favorites")}
type="button"
data-model-picker-provider="favorites"
aria-label="Favorites"
>
<StarIcon className="size-5 fill-current shrink-0" aria-hidden />
</button>
}
/>
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
sideOffset={PICKER_TOOLTIP_SIDE_OFFSET}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
Favorites
</TooltipPopup>
</Tooltip>
</div>
</div>
) : null}
{/* Instance buttons (one per configured instance — built-in + custom) */}
{props.instanceEntries.map((entry) => {
const isUnavailable = !entry.isAvailable || entry.status !== "ready";
const isContextDisabled = props.disabledInstanceIds?.has(entry.instanceId) ?? false;
const isDisabled = isUnavailable || isContextDisabled;
const isSelected = props.selectedInstanceId === entry.instanceId;
const isHovered = hoveredInstanceId === entry.instanceId;
const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false;
const showInstanceBadge =
Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1;
const tooltip = isUnavailable
? describeUnavailableInstance(entry)
: isContextDisabled
? (props.getDisabledInstanceTooltip?.(entry) ?? entry.displayName)
: showNewBadge
? `${entry.displayName} — New`
: entry.displayName;
const button = (
<button
data-model-picker-provider={entry.instanceId}
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
)}
data-provider-accent-color={entry.accentColor}
onClick={() => !isDisabled && handleSelect(entry.instanceId)}
onMouseEnter={() => setHoveredInstanceId(entry.instanceId)}
onMouseLeave={() =>
setHoveredInstanceId((current) => (current === entry.instanceId ? null : current))
}
onFocus={() => setHoveredInstanceId(entry.instanceId)}
onBlur={() =>
setHoveredInstanceId((current) => (current === entry.instanceId ? null : current))
}
disabled={isDisabled}
type="button"
aria-label={
isDisabled
? tooltip
: showNewBadge
? `${entry.displayName}, new`
: entry.displayName
}
>
<ProviderInstanceIcon
driverKind={entry.driverKind}
displayName={entry.displayName}
accentColor={entry.accentColor}
showBadge={showInstanceBadge}
className="size-6"
iconClassName="size-5"
indicatorBackground={
isHovered && !isDisabled
? "var(--muted)"
: isSelected
? "var(--background)"
: "color-mix(in oklab, var(--muted) 30%, transparent)"
}
{...(entry.accentColor
? { badgeClassName: "h-3 min-w-3 px-0.5 text-[7px]" }
: {})}
/>
{showNewBadge ? (
<span className={NEW_BADGE_CLASS} aria-hidden>
<SparklesIcon className="size-2" />
</span>
) : null}
</button>
);
const trigger = isDisabled ? (
<span className="relative block w-full">{button}</span>
) : (
button
);
return (
<div key={entry.instanceId} className="relative w-full">
<Tooltip>
<TooltipTrigger render={trigger} />
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
sideOffset={PICKER_TOOLTIP_SIDE_OFFSET}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
{tooltip}
</TooltipPopup>
</Tooltip>
</div>
);
})}
{showComingSoon ? (
<>
{/* Gemini button (coming soon) */}
<Tooltip>
<TooltipTrigger
render={
<button
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",
props.selectedInstanceId === "favorites" && SELECTED_BUTTON_CLASS,
)}
onClick={() => handleSelect("favorites")}
type="button"
data-model-picker-provider="favorites"
aria-label="Favorites"
>
<StarIcon className="size-5 fill-current shrink-0" aria-hidden />
</button>
<span className="relative block w-full">
<button
className={cn(
"relative isolate flex w-full aspect-square items-center justify-center rounded-md opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",
)}
disabled
type="button"
data-model-picker-provider="gemini-coming-soon"
aria-label="Gemini — coming soon"
>
<Gemini className="size-5 text-muted-foreground/85" aria-hidden />
<span className={SOON_BADGE_CLASS} aria-hidden>
<Clock3Icon className="size-2" />
</span>
</button>
</span>
}
/>
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
sideOffset={PICKER_TOOLTIP_SIDE_OFFSET}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
Favorites
Gemini — Coming soon
</TooltipPopup>
</Tooltip>
</div>
</div>
) : null}
{/* Instance buttons (one per configured instance — built-in + custom) */}
{props.instanceEntries.map((entry) => {
const isDisabled = !entry.isAvailable || entry.status !== "ready";
const isSelected = props.selectedInstanceId === entry.instanceId;
const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false;
const showInstanceBadge =
Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1;
const tooltip = isDisabled
? describeUnavailableInstance(entry)
: showNewBadge
? `${entry.displayName} — New`
: entry.displayName;
const button = (
<button
data-model-picker-provider={entry.instanceId}
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded transition-colors hover:bg-muted",
isSelected && SELECTED_BUTTON_CLASS,
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
)}
data-provider-accent-color={entry.accentColor}
onClick={() => !isDisabled && handleSelect(entry.instanceId)}
disabled={isDisabled}
type="button"
aria-label={
isDisabled
? tooltip
: showNewBadge
? `${entry.displayName}, new`
: entry.displayName
}
>
<ProviderInstanceIcon
driverKind={entry.driverKind}
displayName={entry.displayName}
accentColor={entry.accentColor}
showBadge={showInstanceBadge}
className="size-6"
iconClassName="size-5"
/>
{showNewBadge ? (
<span className={NEW_BADGE_CLASS} aria-hidden>
<SparklesIcon className="size-2" />
</span>
) : null}
</button>
);
const trigger = isDisabled ? (
<span className="relative block w-full">{button}</span>
) : (
button
);
return (
<div key={entry.instanceId} className="relative w-full">
{isSelected && <div className={SELECTED_INDICATOR_CLASS} />}
{/* Github Copilot button (coming soon) */}
<Tooltip>
<TooltipTrigger render={trigger} />
<TooltipTrigger
render={
<span className="relative block w-full">
<button
className={cn(
"relative isolate flex w-full aspect-square items-center justify-center rounded-md opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",
)}
disabled
type="button"
data-model-picker-provider="github-copilot-coming-soon"
aria-label="Github Copilot — coming soon"
>
<GithubCopilotIcon
className="size-5 text-muted-foreground/85"
aria-hidden
/>
<span className={SOON_BADGE_CLASS} aria-hidden>
<Clock3Icon className="size-2" />
</span>
</button>
</span>
}
/>
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
sideOffset={PICKER_TOOLTIP_SIDE_OFFSET}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
{tooltip}
Github Copilot — Coming soon
</TooltipPopup>
</Tooltip>
</div>
);
})}
{showComingSoon ? (
<>
{/* Gemini button (coming soon) */}
<Tooltip>
<TooltipTrigger
render={
<span className="relative block w-full">
<button
className={cn(
"relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",
)}
disabled
type="button"
data-model-picker-provider="gemini-coming-soon"
aria-label="Gemini — coming soon"
>
<Gemini className="size-5 text-muted-foreground/85" aria-hidden />
<span className={SOON_BADGE_CLASS} aria-hidden>
<Clock3Icon className="size-2" />
</span>
</button>
</span>
}
/>
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
Gemini — Coming soon
</TooltipPopup>
</Tooltip>
{/* Github Copilot button (coming soon) */}
<Tooltip>
<TooltipTrigger
render={
<span className="relative block w-full">
<button
className={cn(
"relative isolate flex w-full aspect-square items-center justify-center rounded opacity-50 cursor-not-allowed transition-colors hover:bg-transparent",
)}
disabled
type="button"
data-model-picker-provider="github-copilot-coming-soon"
aria-label="Github Copilot — coming soon"
>
<GithubCopilotIcon className="size-5 text-muted-foreground/85" aria-hidden />
<span className={SOON_BADGE_CLASS} aria-hidden>
<Clock3Icon className="size-2" />
</span>
</button>
</span>
}
/>
<TooltipPopup
side={PICKER_TOOLTIP_SIDE}
align="center"
className={PICKER_TOOLTIP_CLASS}
>
Github Copilot — Coming soon
</TooltipPopup>
</Tooltip>
</>
) : null}
</>
) : null}
</div>
</div>
</ScrollArea>
</div>
);
});
@@ -19,20 +19,24 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {
displayName: string;
accentColor?: string | undefined;
showBadge?: boolean;
badgeContent?: "initials" | "none";
className?: string;
iconClassName?: string;
badgeClassName?: string;
statusDotClassName?: string;
indicatorBackground?: string;
}) {
const Icon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null;
const indicatorBackground = props.indicatorBackground ?? "var(--card)";
const accentStyle = props.accentColor
? ({ "--provider-accent": props.accentColor } as CSSProperties)
: undefined;
const badgeContent = props.badgeContent ?? "initials";
return (
<span
className={cn(
"relative isolate inline-flex shrink-0 items-center justify-center",
"relative isolate inline-flex shrink-0 items-center justify-center overflow-visible",
props.className,
)}
style={accentStyle}
@@ -48,24 +52,26 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {
{props.statusDotClassName ? (
<span
className={cn(
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
"pointer-events-none absolute -left-0.5 -top-0.5 z-10 size-2 rounded-full",
props.statusDotClassName,
)}
style={{ boxShadow: `0 0 0 2px ${indicatorBackground}` }}
aria-hidden
/>
) : null}
{props.showBadge ? (
<span
className={cn(
"pointer-events-none absolute right-0 bottom-0 flex h-3.5 min-w-3.5 items-center justify-center rounded-full border border-background px-0.5 text-[8px] font-semibold leading-none shadow-sm",
"pointer-events-none absolute right-0 bottom-0 z-10 flex h-3.5 min-w-3.5 items-center justify-center rounded-full border px-0.5 text-[8px] font-semibold leading-none shadow-sm",
props.accentColor
? "bg-[var(--provider-accent)] text-white"
: "bg-muted text-muted-foreground",
props.badgeClassName,
)}
style={{ borderColor: indicatorBackground }}
aria-hidden
>
{providerInstanceInitials(props.displayName)}
{badgeContent === "initials" ? providerInstanceInitials(props.displayName) : null}
</span>
) : null}
</span>
@@ -255,6 +255,7 @@ async function mountPicker(props: {
providers?: ReadonlyArray<ServerProvider>;
settings?: UnifiedSettings;
triggerVariant?: "ghost" | "outline";
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
}) {
const host = document.createElement("div");
document.body.append(host);
@@ -277,6 +278,9 @@ async function mountPicker(props: {
instanceEntries={instanceEntries}
modelOptionsByInstance={modelOptionsByInstance}
triggerVariant={props.triggerVariant}
{...(props.getModelDisabledReason
? { getModelDisabledReason: props.getModelDisabledReason }
: {})}
onInstanceModelChange={onInstanceModelChange}
/>,
{ container: host },
@@ -461,7 +465,7 @@ describe("ProviderModelPicker", () => {
}
});
it("shows locked provider header and only its models in locked mode", async () => {
it("keeps the full provider rail in locked mode and only lists compatible models", async () => {
localStorage.setItem(
"t3code:client-settings:v1",
JSON.stringify({
@@ -484,8 +488,21 @@ describe("ProviderModelPicker", () => {
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
// Should show locked provider label
expect(text).toContain("Claude");
// Locked-compatible instances render first, then disabled ones.
expect(getSidebarProviderOrder().slice(0, 3)).toEqual([
"favorites",
"claudeAgent",
"codex",
]);
expect(
document.querySelector<HTMLButtonElement>('[data-model-picker-provider="codex"]')
?.disabled,
).toBe(true);
expect(
document.querySelector<HTMLButtonElement>('[data-model-picker-provider="claudeAgent"]')
?.disabled,
).toBe(false);
expect(getVisibleModelNames()).toEqual([
"Claude Sonnet 4.6",
"Claude Opus 4.6",
@@ -559,7 +576,21 @@ describe("ProviderModelPicker", () => {
await page.getByRole("button").click();
await vi.waitFor(() => {
expect(getSidebarProviderOrder()).toEqual(["codex", "codex_personal"]);
expect(getSidebarProviderOrder().slice(0, 5)).toEqual([
"favorites",
"codex",
"codex_personal",
"codex_isolated",
"claudeAgent",
]);
expect(
document.querySelector<HTMLButtonElement>('[data-model-picker-provider="codex_isolated"]')
?.disabled,
).toBe(true);
expect(
document.querySelector<HTMLButtonElement>('[data-model-picker-provider="claudeAgent"]')
?.disabled,
).toBe(true);
expect(getModelPickerListText()).not.toContain("Codex Isolated");
expect(
document.querySelector<HTMLElement>('[data-model-picker-provider="codex_personal"]')
@@ -625,7 +656,7 @@ describe("ProviderModelPicker", () => {
}
});
it("uses the trigger label for locked opencode rows", async () => {
it("shows the plain model name in the trigger and provider details on locked opencode rows", async () => {
const providers: ReadonlyArray<ServerProvider> = [
buildOpenCodeProvider([
{
@@ -658,14 +689,15 @@ describe("ProviderModelPicker", () => {
const trigger = document.querySelector<HTMLElement>(
'[data-chat-provider-model-picker="true"]',
);
expect(trigger?.textContent).toContain("GitHub Copilot");
expect(trigger?.textContent).toContain("Opus 4.5");
expect(trigger?.textContent).not.toContain("GitHub Copilot");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
expect(getVisibleModelNames()).toEqual(["GitHub Copilot · Opus 4.5"]);
expect(getVisibleModelNames()).toEqual(["Claude Opus 4.5"]);
expect(getModelPickerListText()).toContain("OpenCode · GitHub Copilot");
});
} finally {
await mounted.cleanup();
@@ -961,27 +993,30 @@ describe("ProviderModelPicker", () => {
expect(text).toContain("Claude Opus 4.6");
});
const getFirstStarButton = () => {
const starButton = document.querySelector<HTMLButtonElement>(
const getFavoriteButton = () => {
const modelRow = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(
(row) => row.textContent?.includes("Claude Opus 4.6"),
);
const starButton = modelRow?.querySelector<HTMLButtonElement>(
'button[aria-label*="favorites"]',
);
expect(starButton).not.toBeNull();
return starButton!;
};
const firstStar = getFirstStarButton();
const initialAriaLabel = firstStar.getAttribute("aria-label");
const favoriteButton = getFavoriteButton();
const initialAriaLabel = favoriteButton.getAttribute("aria-label");
expect(
initialAriaLabel === "Add to favorites" || initialAriaLabel === "Remove from favorites",
).toBe(true);
await page.getByRole("button", { name: initialAriaLabel! }).first().click();
await userEvent.click(favoriteButton);
const expectedAriaLabel =
initialAriaLabel === "Add to favorites" ? "Remove from favorites" : "Add to favorites";
await vi.waitFor(() => {
expect(getFirstStarButton().getAttribute("aria-label")).toBe(expectedAriaLabel);
expect(getFavoriteButton().getAttribute("aria-label")).toBe(expectedAriaLabel);
});
} finally {
await mounted.cleanup();
@@ -1050,6 +1085,38 @@ describe("ProviderModelPicker", () => {
}
});
it("filters favorites to compatible models in locked mode", async () => {
localStorage.setItem(
"t3code:client-settings:v1",
JSON.stringify({
...DEFAULT_CLIENT_SETTINGS,
favorites: [
{ provider: "codex", model: "gpt-5.3-codex" },
{ provider: "claudeAgent", model: "claude-sonnet-4-6" },
],
}),
);
const mounted = await mountPicker({
activeInstanceId: CLAUDE_INSTANCE_ID,
model: "claude-opus-4-6",
lockedProvider: ProviderDriverKind.make("claudeAgent"),
});
try {
await page.getByRole("button").click();
await page.getByRole("button", { name: "Favorites", exact: true }).click();
await vi.waitFor(() => {
expect(getVisibleModelNames()).toEqual(["Claude Sonnet 4.6"]);
expect(getModelPickerListText()).not.toContain("GPT-5.3 Codex");
});
} finally {
await mounted.cleanup();
localStorage.removeItem("t3code:client-settings:v1");
}
});
it("dispatches callback with correct provider and model when selected", async () => {
const mounted = await mountPicker({
activeInstanceId: CLAUDE_INSTANCE_ID,
@@ -1079,6 +1146,29 @@ describe("ProviderModelPicker", () => {
}
});
it("does not select models blocked by the provider", async () => {
const disabledReason =
"This provider does not allow switching models after a conversation has started. Start a new thread to use this model.";
const mounted = await mountPicker({
activeInstanceId: CLAUDE_INSTANCE_ID,
model: "claude-opus-4-6",
lockedProvider: ProviderDriverKind.make("claudeAgent"),
getModelDisabledReason: (instanceId, model) =>
instanceId === CLAUDE_INSTANCE_ID && model !== "claude-opus-4-6" ? disabledReason : null,
});
try {
await page.getByRole("button").click();
const blockedModel = page.getByText("Claude Sonnet 4.6").first();
await blockedModel.click();
expect(mounted.onProviderModelChange).not.toHaveBeenCalled();
expect(document.querySelector(".model-picker-list")).not.toBeNull();
} finally {
await mounted.cleanup();
}
});
it("only shows codex spark when the server reports it", async () => {
const providersWithoutSpark: ReadonlyArray<ServerProvider> = [
buildCodexProvider([
@@ -41,6 +41,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
onOpenChange?: (open: boolean) => void;
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
}) {
const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);
@@ -65,7 +66,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
selectedInstanceOptions.find((option) => option.slug === props.model) ??
selectedInstanceOptions[0];
const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model;
const triggerSubtitle = selectedModel?.subProvider;
const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model;
const duplicateDriverCount = props.instanceEntries.filter(
(entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind,
@@ -86,6 +86,54 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
};
}, [isMenuOpen]);
useEffect(() => {
if (!isMenuOpen) {
return;
}
const { documentElement, body } = document;
const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
const previousBodyOverflow = body.style.overflow;
const previousBodyPaddingRight = body.style.paddingRight;
const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
documentElement.style.overscrollBehavior = "contain";
body.style.overflow = "hidden";
if (scrollbarWidth > 0) {
body.style.paddingRight = `${scrollbarWidth}px`;
}
const shouldAllowOverlayScroll = (target: EventTarget | null) => {
return target instanceof Element && target.closest("[data-model-picker-content]");
};
const preventBackgroundWheel = (event: WheelEvent) => {
if (shouldAllowOverlayScroll(event.target)) {
return;
}
event.preventDefault();
};
const preventBackgroundTouchMove = (event: TouchEvent) => {
if (shouldAllowOverlayScroll(event.target)) {
return;
}
event.preventDefault();
};
document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
document.addEventListener("touchmove", preventBackgroundTouchMove, {
capture: true,
passive: false,
});
return () => {
document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
body.style.overflow = previousBodyOverflow;
body.style.paddingRight = previousBodyPaddingRight;
};
}, [isMenuOpen]);
const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {
if (props.disabled) return;
props.onInstanceModelChange(instanceId, model);
@@ -110,7 +158,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
variant={props.triggerVariant ?? "ghost"}
data-chat-provider-model-picker="true"
className={cn(
"min-w-0 justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 [&_svg]:mx-0",
"min-w-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
props.triggerClassName,
)}
@@ -118,12 +166,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
/>
}
>
<span
className={cn(
"flex min-w-0 w-full box-border items-center gap-2 overflow-hidden",
props.compact ? "max-w-36 sm:pl-1" : undefined,
)}
>
<span className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
{activeEntry ? (
<ProviderInstanceIcon
driverKind={activeEntry.driverKind}
@@ -132,42 +175,28 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
showBadge={showInstanceBadge}
className={showInstanceBadge ? "size-5" : "size-4"}
iconClassName={cn("size-4", props.activeProviderIconClassName)}
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
indicatorBackground="var(--input)"
badgeClassName={cn(
"right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3",
"px-0.5 text-[7px]",
)}
/>
) : null}
<Tooltip>
<TooltipTrigger
render={
<span
className={cn(
"min-w-0 flex-1 overflow-hidden",
triggerSubtitle
? "grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-1"
: "truncate",
)}
/>
}
>
{triggerSubtitle ? (
<>
<span className="min-w-0 truncate">{triggerSubtitle}</span>
<span aria-hidden="true" className="shrink-0 opacity-60">
·
</span>
<span className="min-w-0 truncate">{triggerTitle}</span>
</>
) : (
triggerTitle
)}
<TooltipTrigger render={<span className="min-w-0 flex-1 overflow-hidden truncate" />}>
{triggerTitle}
</TooltipTrigger>
<TooltipPopup side="top">{triggerLabel}</TooltipPopup>
</Tooltip>
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
<span aria-hidden="true" className="flex items-center">
<ChevronDownIcon aria-hidden="true" className="!ms-0 !-me-1 size-3 shrink-0 opacity-60" />
</span>
</PopoverTrigger>
<PopoverPopup
align="start"
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0] *:data-[slot=popover-viewport]:p-0"
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
viewportClassName="!overflow-hidden p-0"
>
<ModelPickerContent
activeInstanceId={activeInstanceId}
@@ -179,6 +208,9 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
modelOptionsByInstance={props.modelOptionsByInstance}
terminalOpen={props.terminalOpen ?? false}
onRequestClose={() => setIsMenuOpen(false)}
{...(props.getModelDisabledReason
? { getModelDisabledReason: props.getModelDisabledReason }
: {})}
onInstanceModelChange={handleInstanceModelChange}
/>
</PopoverPopup>
@@ -1,8 +1,9 @@
import { type ServerProvider } from "@t3tools/contracts";
import { memo } from "react";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { CircleAlertIcon } from "lucide-react";
import { InfoIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { formatProviderDriverKindLabel } from "../../providerModels";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
status,
@@ -13,22 +14,42 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
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`;
const providerName = status.displayName?.trim() || formatProviderDriverKindLabel(status.driver);
const isUnauthenticated = status.status === "error" && status.auth.status === "unauthenticated";
const title = isUnauthenticated
? `${providerName} is unauthenticated`
: `${providerName} provider status`;
const message = isUnauthenticated
? "Sign in via the CLI to authenticate again."
: (status.message ??
(status.status === "error"
? `${providerName} provider is unavailable.`
: `${providerName} provider has limited availability.`));
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 className="mx-auto w-fit max-w-[calc(100%-2rem)] pt-3">
<div
className={cn(
"inline-flex items-center gap-3 rounded-xl border px-3.5 py-3 text-card-foreground text-sm",
status.status === "warning"
? "border-warning/32 bg-warning/4 [&_svg]:text-warning"
: "border-destructive/32 bg-destructive/4 text-destructive-foreground [&_svg]:text-destructive",
)}
role="alert"
>
<InfoIcon className="size-4 shrink-0" aria-hidden />
<div className="flex min-w-0 flex-col gap-1">
<div className="font-medium">{title}</div>
<Tooltip>
<TooltipTrigger
render={<div className="line-clamp-3 text-muted-foreground">{message}</div>}
/>
<TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap">
{message}
</TooltipPopup>
</Tooltip>
</div>
</div>
</div>
);
});
@@ -1,18 +0,0 @@
import { CheckIcon } from "lucide-react";
import { Badge } from "../ui/badge";
export function SelectedModelBadge() {
return <CheckIcon className="size-3.5 shrink-0 text-blue-400" />;
}
export function DefaultBadge() {
return (
<Badge
variant="outline"
className="inline-flex h-4 w-fit min-w-0 items-center justify-center gap-0 ps-1.5 pe-1.5 py-0 text-[10px] font-semibold leading-none border-border/70 bg-muted/60 text-muted-foreground sm:h-4"
>
Default
</Badge>
);
}
@@ -3,11 +3,12 @@ import type { ServerProviderSkill } from "@t3tools/contracts";
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import {
CHAT_INLINE_CHIP_CLASS_NAME,
CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
SKILL_CHIP_ICON_SVG,
} from "../composerInlineChip";
import { cn } from "~/lib/utils";
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
@@ -70,15 +71,19 @@ export function renderSkillInlineMarkdownChildren(
function SkillChip(props: { skill: InlineSkill; rawText: string }) {
return (
<span className="inline-flex align-middle leading-none">
<span className="sr-only">{props.rawText}</span>
<span aria-hidden="true" className={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}>
<span className="inline-flex align-middle leading-none" data-markdown-copy={props.rawText}>
<span
className={cn(
CHAT_INLINE_CHIP_CLASS_NAME,
"border-fuchsia-500/25 bg-fuchsia-500/12 text-fuchsia-700 dark:text-fuchsia-300",
)}
>
<span
aria-hidden="true"
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
/>
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>
<span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>
{formatProviderSkillDisplayName(props.skill)}
</span>
</span>
@@ -1,6 +1,8 @@
import { memo } from "react";
import { Alert, AlertAction, AlertDescription } from "../ui/alert";
import { Button } from "../ui/button";
import { CircleAlertIcon, XIcon } from "lucide-react";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
error,
@@ -14,19 +16,19 @@ export const ThreadErrorBanner = memo(function ThreadErrorBanner({
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant="error">
<CircleAlertIcon />
<AlertDescription className="line-clamp-3" title={error}>
{error}
</AlertDescription>
<Tooltip>
<TooltipTrigger render={<AlertDescription className="line-clamp-3" />}>
{error}
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap">
{error}
</TooltipPopup>
</Tooltip>
{onDismiss && (
<AlertAction>
<button
type="button"
aria-label="Dismiss error"
className="inline-flex size-6 items-center justify-center rounded-md text-destructive/60 transition-colors hover:text-destructive"
onClick={onDismiss}
>
<XIcon className="size-3.5" />
</button>
<Button variant="ghost" size="icon-xs" aria-label="Dismiss error" onClick={onDismiss}>
<XIcon className="text-destructive" />
</Button>
</AlertAction>
)}
</Alert>
+102 -316
View File
@@ -14,16 +14,9 @@ import {
getProviderOptionDescriptors,
isClaudeUltrathinkPrompt,
} from "@t3tools/shared/model";
import { Fragment, memo, useCallback, useState } from "react";
import { memo, useCallback, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import {
BookOpenIcon,
BrainIcon,
ChevronDownIcon,
RabbitIcon,
TurtleIcon,
ZapIcon,
} from "lucide-react";
import { ChevronDownIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
Menu,
@@ -37,8 +30,6 @@ import {
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { cn } from "~/lib/utils";
import { Separator } from "../ui/separator";
import { DefaultBadge, SelectedModelBadge } from "./SelectedModelBadge";
type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
@@ -55,50 +46,6 @@ type TraitsPersistence =
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
function getBooleanDescriptorLabel(
descriptor: Extract<ProviderOptionDescriptor, { type: "boolean" }>,
): string {
return descriptor.id === "fastMode" ? "Speed" : descriptor.label;
}
function getBooleanDescriptorOptionLabel(
descriptor: Extract<ProviderOptionDescriptor, { type: "boolean" }>,
value: "on" | "off",
): string {
if (descriptor.id === "fastMode") {
return value === "on" ? "Fast" : "Normal";
}
return value === "on" ? "On" : "Off";
}
function getSpeedOptionDescription(input: {
provider: ProviderDriverKind;
model: string | null | undefined;
value: "on" | "off";
}): string {
if (input.value === "off") {
return "Uses standard speed and normal usage.";
}
if (input.provider === "claudeAgent") {
return "Works up to 2.5x faster, but uses 6x more usage than normal.";
}
if (input.model === "gpt-5.5") {
return "Works up to 1.5x faster, but uses 2.5x more usage than normal.";
}
return "Works up to 1.5x faster, but uses 2x more usage than normal.";
}
function BooleanDescriptorOptionIcon(props: {
descriptor: Extract<ProviderOptionDescriptor, { type: "boolean" }>;
value: "on" | "off";
}) {
if (props.descriptor.id !== "fastMode") {
return null;
}
const Icon = props.value === "on" ? RabbitIcon : TurtleIcon;
return <Icon aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />;
}
function replaceDescriptorCurrentValue(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
descriptorId: string,
@@ -244,13 +191,8 @@ export function shouldRenderTraitsControls(input: {
prompt: string;
modelOptions: ProviderOptions | null | undefined;
allowPromptInjectedEffort?: boolean;
hiddenDescriptorIds?: ReadonlyArray<string>;
}): boolean {
const visibility = getTraitsSectionVisibility(input);
if (!visibility.hasAnyControls) return false;
const hidden = new Set(input.hiddenDescriptorIds ?? []);
if (hidden.size === 0) return true;
return visibility.descriptors.some((descriptor) => !hidden.has(descriptor.id));
return getTraitsSectionVisibility(input).hasAnyControls;
}
export interface TraitsMenuContentProps {
@@ -262,11 +204,8 @@ export interface TraitsMenuContentProps {
onPromptChange: (prompt: string) => void;
modelOptions?: ProviderOptions | null | undefined;
allowPromptInjectedEffort?: boolean;
hiddenDescriptorIds?: ReadonlyArray<string>;
showTriggerSeparators?: boolean;
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
onRequestClose?: () => void;
}
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
@@ -278,8 +217,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
onPromptChange,
modelOptions,
allowPromptInjectedEffort = true,
hiddenDescriptorIds,
onRequestClose,
...persistence
}: TraitsMenuContentProps & TraitsPersistence) {
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
@@ -317,16 +254,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
modelOptions,
allowPromptInjectedEffort,
});
const hiddenDescriptorIdSet = new Set(hiddenDescriptorIds ?? []);
const visibleDescriptors = descriptors.filter(
(descriptor) => !hiddenDescriptorIdSet.has(descriptor.id),
);
const visibleSelectDescriptors = selectDescriptors.filter(
(descriptor) => !hiddenDescriptorIdSet.has(descriptor.id),
);
const visibleBooleanDescriptors = booleanDescriptors.filter(
(descriptor) => !hiddenDescriptorIdSet.has(descriptor.id),
);
const updateDescriptors = (nextDescriptors: ReadonlyArray<ProviderOptionDescriptor>) => {
updateModelOptions(buildProviderOptionSelectionsFromDescriptors(nextDescriptors));
};
@@ -350,16 +277,15 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
onPromptChange(stripped);
}
updateDescriptors(replaceDescriptorCurrentValue(descriptors, descriptor.id, value));
onRequestClose?.();
};
if (!hasAnyControls || visibleDescriptors.length === 0) {
if (!hasAnyControls) {
return null;
}
return (
<>
{visibleSelectDescriptors.map((descriptor, index) => (
{selectDescriptors.map((descriptor, index) => (
<div key={descriptor.id}>
{index > 0 ? <MenuDivider /> : null}
<MenuGroup>
@@ -372,81 +298,46 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
option.
</div>
) : null}
{(() => {
const selectedValue =
<MenuRadioGroup
value={
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "ultrathink"
: (getDescriptorStringValue(descriptor) ?? "");
return (
<MenuRadioGroup
value={selectedValue}
onValueChange={(value) => handleSelectChange(descriptor, value)}
: (getDescriptorStringValue(descriptor) ?? "")
}
onValueChange={(value) => handleSelectChange(descriptor, value)}
>
{descriptor.options.map((option) => (
<MenuRadioItem
key={option.id}
value={option.id}
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
>
{descriptor.options.map((option) => (
<MenuRadioItem
key={option.id}
value={option.id}
hideIndicator
disabled={
ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id
}
>
<span className="inline-flex items-center gap-1.5">
{option.label}
{option.isDefault ? <DefaultBadge /> : null}
{option.id === selectedValue ? <SelectedModelBadge /> : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
);
})()}
{option.label}
{option.isDefault ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</div>
))}
{visibleBooleanDescriptors.map((descriptor, index) => (
{booleanDescriptors.map((descriptor, index) => (
<div key={descriptor.id}>
{index > 0 || visibleSelectDescriptors.length > 0 ? <MenuDivider /> : null}
{index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
{getBooleanDescriptorLabel(descriptor)}
{descriptor.label}
</div>
{(() => {
const selectedValue = descriptor.currentValue === true ? "on" : "off";
return (
<MenuRadioGroup
value={selectedValue}
onValueChange={(value) => {
updateDescriptors(
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
);
onRequestClose?.();
}}
>
{(["on", "off"] as const).map((value) => (
<MenuRadioItem
key={value}
value={value}
hideIndicator
className={descriptor.id === "fastMode" ? "min-w-72 items-start py-2" : ""}
>
<span className="grid min-w-0 gap-0.5">
<span className="inline-flex items-center gap-1.5">
<BooleanDescriptorOptionIcon descriptor={descriptor} value={value} />
{getBooleanDescriptorOptionLabel(descriptor, value)}
{value === selectedValue ? <SelectedModelBadge /> : null}
</span>
{descriptor.id === "fastMode" ? (
<span className="text-muted-foreground text-xs leading-4">
{getSpeedOptionDescription({ provider, model, value })}
</span>
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
);
})()}
<MenuRadioGroup
value={descriptor.currentValue === true ? "on" : "off"}
onValueChange={(value) => {
updateDescriptors(
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
);
}}
>
<MenuRadioItem value="on">On</MenuRadioItem>
<MenuRadioItem value="off">Off</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
</div>
))}
@@ -463,12 +354,11 @@ export const TraitsPicker = memo(function TraitsPicker({
onPromptChange,
modelOptions,
allowPromptInjectedEffort = true,
hiddenDescriptorIds,
showTriggerSeparators = true,
triggerVariant,
triggerClassName,
...persistence
}: TraitsMenuContentProps & TraitsPersistence) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
getTraitsSectionVisibility({
provider,
@@ -478,33 +368,6 @@ export const TraitsPicker = memo(function TraitsPicker({
modelOptions,
allowPromptInjectedEffort,
});
const hiddenDescriptorIdSet = new Set(hiddenDescriptorIds ?? []);
const visibleDescriptors = descriptors.filter(
(descriptor) => !hiddenDescriptorIdSet.has(descriptor.id),
);
const isCodexStyle = provider === "codex";
const [openDescriptorId, setOpenDescriptorId] = useState<string | null>(null);
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
const updateModelOptions = useCallback(
(nextOptions: ProviderOptions | undefined) => {
if ("onModelOptionsChange" in persistence) {
persistence.onModelOptionsChange(nextOptions);
return;
}
const threadTarget = persistence.threadRef ?? persistence.draftId;
if (!threadTarget) {
return;
}
setProviderModelOptions(threadTarget, provider, nextOptions, {
...(instanceId ? { instanceId } : {}),
model,
persistSticky: true,
});
},
[instanceId, model, persistence, provider, setProviderModelOptions],
);
if (
!shouldRenderTraitsControls({
provider,
@@ -513,154 +376,77 @@ export const TraitsPicker = memo(function TraitsPicker({
prompt,
modelOptions,
allowPromptInjectedEffort,
}) ||
visibleDescriptors.length === 0
})
) {
return null;
}
const triggerLabels: Array<string> = [];
for (const descriptor of descriptors) {
const label =
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "Ultrathink"
: descriptor.type === "boolean"
? descriptor.id === "fastMode"
? descriptor.currentValue === true
? "Fast"
: "Normal"
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: getProviderOptionCurrentLabel(descriptor);
if (typeof label === "string" && label.length > 0) {
triggerLabels.push(label);
}
}
const triggerLabel = triggerLabels.join(" · ");
const isCodexStyle = provider === "codex";
return (
<>
{visibleDescriptors.map((descriptor, descriptorIndex) => {
const resolvedSelectLabel = getProviderOptionCurrentLabel(descriptor);
const descriptorIdLower = descriptor.id.toLowerCase();
const descriptorLabelLower = descriptor.label.toLowerCase();
const isThinkingLike =
descriptorIdLower.includes("reason") ||
descriptorLabelLower.includes("reason") ||
descriptorIdLower === "variant" ||
descriptorLabelLower === "variant" ||
descriptorIdLower.includes("thinking") ||
descriptorLabelLower.includes("thinking");
const triggerLabel =
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "Ultrathink"
: descriptor.type === "boolean"
? descriptor.id === "fastMode"
? descriptor.currentValue === true
? "Fast"
: "Normal"
: isThinkingLike
? descriptor.currentValue === true
? "On"
: "Off"
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: resolvedSelectLabel && resolvedSelectLabel.length > 0
? resolvedSelectLabel
: descriptor.label;
const isContextWindow =
descriptorIdLower === "contextwindow" ||
descriptorIdLower === "context_window" ||
descriptorIdLower.includes("contextwindow") ||
descriptorLabelLower.includes("context window");
const TriggerIcon =
descriptor.id === "fastMode"
? ZapIcon
: isThinkingLike
? BrainIcon
: isContextWindow
? BookOpenIcon
: null;
const popupHiddenDescriptorIds = [
...(hiddenDescriptorIds ?? []),
...visibleDescriptors
.filter((visibleDescriptor) => visibleDescriptor.id !== descriptor.id)
.map((visibleDescriptor) => visibleDescriptor.id),
];
const isBooleanToggle = descriptor.type === "boolean" && isThinkingLike;
const toggleOn = isBooleanToggle && descriptor.currentValue === true;
const toggleLabel = toggleOn ? "Thinking" : "Instant";
return (
<Fragment key={descriptor.id}>
{showTriggerSeparators && descriptorIndex > 0 ? (
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
) : null}
{isBooleanToggle ? (
<Button
variant="ghost"
size="sm"
type="button"
aria-pressed={toggleOn}
title={
toggleOn
? "Thinking enabled - click to switch to instant responses"
: "Instant responses - click to enable thinking"
}
onClick={() => {
updateModelOptions(
buildProviderOptionSelectionsFromDescriptors(
replaceDescriptorCurrentValue(descriptors, descriptor.id, !toggleOn),
),
);
}}
className={cn(
"shrink-0 whitespace-nowrap px-2 sm:px-3",
toggleOn
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
triggerClassName,
)}
>
<BrainIcon
aria-hidden="true"
className={cn("size-3.5", toggleOn ? "text-current opacity-100" : "opacity-70")}
/>
<span className="sr-only sm:not-sr-only">{toggleLabel}</span>
</Button>
) : (
<Menu
open={openDescriptorId === descriptor.id}
onOpenChange={(open) => setOpenDescriptorId(open ? descriptor.id : null)}
>
<MenuTrigger
render={
<Button
size="sm"
variant={triggerVariant ?? "ghost"}
className={cn(
isCodexStyle
? "min-w-0 max-w-40 shrink justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3"
: "shrink-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3",
triggerClassName,
)}
/>
}
>
<span className="flex min-w-0 flex-1 justify-center items-center gap-1.5 overflow-hidden">
{TriggerIcon ? (
<TriggerIcon aria-hidden="true" className="ps-[2px] opacity-70" />
) : null}
<span className="min-w-0 truncate">{triggerLabel}</span>
</span>
<span aria-hidden="true" className="flex items-center">
<ChevronDownIcon
aria-hidden="true"
className="!ms-0 !-me-1 size-3 shrink-0 opacity-60"
/>
</span>
</MenuTrigger>
<MenuPopup align="start">
<TraitsMenuContent
provider={provider}
{...(instanceId ? { instanceId } : {})}
models={models}
model={model}
prompt={prompt}
onPromptChange={onPromptChange}
modelOptions={modelOptions}
allowPromptInjectedEffort={allowPromptInjectedEffort}
hiddenDescriptorIds={popupHiddenDescriptorIds}
onRequestClose={() => setOpenDescriptorId(null)}
{...persistence}
/>
</MenuPopup>
</Menu>
<Menu
open={isMenuOpen}
onOpenChange={(open) => {
setIsMenuOpen(open);
}}
>
<MenuTrigger
render={
<Button
size="sm"
variant={triggerVariant ?? "ghost"}
className={cn(
isCodexStyle
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
: "shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3",
triggerClassName,
)}
</Fragment>
);
})}
</>
/>
}
>
{isCodexStyle ? (
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
{triggerLabel}
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
) : (
<>
<span>{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</>
)}
</MenuTrigger>
<MenuPopup align="start">
<TraitsMenuContent
provider={provider}
{...(instanceId ? { instanceId } : {})}
models={models}
model={model}
prompt={prompt}
onPromptChange={onPromptChange}
modelOptions={modelOptions}
allowPromptInjectedEffort={allowPromptInjectedEffort}
{...persistence}
/>
</MenuPopup>
</Menu>
);
});
@@ -56,7 +56,7 @@ function selections(
const ULTRATHINK_FRAME_CLASSES = {
composerFrameClassName: "ultrathink-frame",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.07)_inset]",
modelPickerIconClassName: "ultrathink-chroma",
} as const;
@@ -67,7 +67,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
...(ultrathinkActive
? {
composerFrameClassName: "ultrathink-frame",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.07)_inset]",
modelPickerIconClassName: "ultrathink-chroma",
}
: {}),
@@ -28,14 +28,26 @@ export type ModelEsque = {
subProvider?: string | undefined;
};
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function stripLeadingQualifier(value: string, qualifier: string | null | undefined): string {
const trimmedQualifier = qualifier?.trim();
if (!trimmedQualifier) {
return value;
}
const pattern = new RegExp(`^${escapeRegExp(trimmedQualifier)}(?:\\s*[.:/-]\\s*|\\s+)`, "iu");
return value.replace(pattern, "").trim() || value;
}
export function getDisplayModelName(
model: ModelEsque,
options?: { preferShortName?: boolean },
): string {
if (options?.preferShortName && model.shortName) {
return model.shortName;
}
return model.name;
const name = options?.preferShortName && model.shortName ? model.shortName : model.name;
return stripLeadingQualifier(name, model.subProvider);
}
export function getTriggerDisplayModelName(model: ModelEsque): string {
@@ -43,6 +55,5 @@ export function getTriggerDisplayModelName(model: ModelEsque): string {
}
export function getTriggerDisplayModelLabel(model: ModelEsque): string {
const title = getTriggerDisplayModelName(model);
return model.subProvider ? `${model.subProvider} · ${title}` : title;
return getTriggerDisplayModelName(model);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { useState } from "react";
import { cn } from "~/lib/utils";
interface ColorSelectorProps {
colors: string[];
size?: "default" | "sm" | "lg";
defaultValue: string;
name?: string;
onColorSelect?: (color: string) => void;
className?: string;
}
const colorMap = {
default: "var(--foreground)",
red: "var(--color-red-500)",
green: "var(--color-green-500)",
blue: "var(--color-blue-500)",
yellow: "var(--color-yellow-500)",
purple: "var(--color-purple-500)",
pink: "var(--color-pink-500)",
indigo: "var(--color-indigo-500)",
orange: "var(--color-orange-500)",
teal: "var(--color-teal-500)",
cyan: "var(--color-cyan-500)",
lime: "var(--color-lime-500)",
emerald: "var(--color-emerald-500)",
violet: "var(--color-violet-500)",
fuchsia: "var(--color-fuchsia-500)",
rose: "var(--color-rose-500)",
sky: "var(--color-sky-500)",
amber: "var(--color-amber-500)",
} as const;
function getSizeClass(size: "default" | "sm" | "lg") {
switch (size) {
case "sm":
return "size-4";
case "default":
return "size-5";
case "lg":
return "size-6";
default:
return "size-5";
}
}
function getColorValue(color: string): string {
return colorMap[color as keyof typeof colorMap] || color;
}
export function ColorSelector({
colors,
size = "default",
defaultValue,
name,
onColorSelect,
className,
}: ColorSelectorProps) {
const [selectedColor, setSelectedColor] = useState<string>(defaultValue);
const handleColorSelect = (color: string) => {
setSelectedColor(color);
onColorSelect?.(color);
};
const sizeClass = getSizeClass(size);
return (
<div className={cn("flex gap-2", className)}>
{name && <input type="hidden" name={name} value={selectedColor} />}
{colors.map((color) => {
const colorValue = getColorValue(color);
return (
<div
key={color}
className={`${sizeClass} cursor-pointer rounded-full transition-transform duration-200 active:scale-90`}
style={{
backgroundColor: colorValue,
...(selectedColor === color && {
boxShadow: `inset 0 0 0 2px var(--card), 0 0 0 2px ${colorValue}`,
}),
}}
onClick={() => handleColorSelect(color)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleColorSelect(color);
}
}}
tabIndex={0}
role="button"
aria-label={`Select ${color} color`}
aria-pressed={selectedColor === color}
/>
);
})}
</div>
);
}
@@ -1,9 +1,15 @@
export const COMPOSER_INLINE_CHIP_CLASS_NAME =
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
const INLINE_CHIP_CLASS_NAME =
"inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
export const CHAT_INLINE_CHIP_CLASS_NAME = INLINE_CHIP_CLASS_NAME;
export const COMPOSER_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} select-none`;
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = "truncate select-none leading-tight";
export const CHAT_INLINE_CHIP_LABEL_CLASS_NAME = "truncate leading-tight";
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = `${CHAT_INLINE_CHIP_LABEL_CLASS_NAME} select-none`;
export const COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME =
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-fuchsia-500/25 bg-fuchsia-500/12 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
@@ -274,7 +274,6 @@ function ConnectionStatusDot({
const dot = (
<button
type="button"
title={tooltipText}
aria-label={tooltipText}
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
>
@@ -881,11 +880,16 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
) : null}
</Popover>
</div>
<p className="text-xs text-muted-foreground" title={expiresAbsolute}>
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
<span aria-hidden> · </span>
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
</p>
<Tooltip>
<TooltipTrigger
render={<p aria-label={expiresAbsolute} className="text-xs text-muted-foreground" />}
>
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
<span aria-hidden> · </span>
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
</TooltipTrigger>
<TooltipPopup side="top">{expiresAbsolute}</TooltipPopup>
</Tooltip>
{shareablePairingUrl === null ? (
<p className="text-[11px] text-muted-foreground/70">
Copy the token and pair from another client using this backend&apos;s reachable host.
@@ -898,17 +902,26 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
<>
{shareablePairingUrl ? (
<Group aria-label="Copy selected endpoint">
<Button
size="xs"
variant="outline"
className="max-w-56"
title={`Copy pairing URL for: ${defaultEndpointCopyLabel}`}
onClick={handleCopyDefaultLink}
>
<span className="truncate">
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant="outline"
className="max-w-56"
aria-label={`Copy pairing URL for: ${defaultEndpointCopyLabel}`}
onClick={handleCopyDefaultLink}
/>
}
>
<span className="truncate">
Copy pairing URL for: {defaultEndpointCopyLabel}
</span>
</TooltipTrigger>
<TooltipPopup side="top">
Copy pairing URL for: {defaultEndpointCopyLabel}
</span>
</Button>
</TooltipPopup>
</Tooltip>
<GroupSeparator />
<Menu>
<MenuTrigger
@@ -1353,12 +1366,19 @@ const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({
{endpoint.label}
</h3>
{shouldShowEndpointUrl ? (
<p
className="min-w-0 truncate text-xs leading-5 text-muted-foreground"
title={endpoint.httpBaseUrl}
>
{endpoint.httpBaseUrl}
</p>
<Tooltip>
<TooltipTrigger
render={
<p
aria-label={endpoint.httpBaseUrl}
className="min-w-0 truncate text-xs leading-5 text-muted-foreground"
/>
}
>
{endpoint.httpBaseUrl}
</TooltipTrigger>
<TooltipPopup side="top">{endpoint.httpBaseUrl}</TooltipPopup>
</Tooltip>
) : null}
{!isAvailable ? (
<span className="shrink-0 rounded-md border border-border/70 px-1 py-0.5 text-[10px] text-muted-foreground">
@@ -3116,12 +3136,21 @@ export function ConnectionsSettings() {
) : null}
<div className="rounded-md border border-border/70 bg-muted/20 px-3 py-2">
<p className="text-xs font-medium text-muted-foreground">HTTPS endpoint</p>
<p
className="mt-1 truncate text-sm text-foreground"
title={pendingTailscaleServeBaseUrl ?? undefined}
>
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
</p>
<Tooltip>
<TooltipTrigger
render={
<p
aria-label={pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
className="mt-1 truncate text-sm text-foreground"
/>
}
>
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
</TooltipTrigger>
<TooltipPopup side="top">
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
</TooltipPopup>
</Tooltip>
</div>
</DialogPanel>
<DialogFooter>
@@ -805,9 +805,19 @@ function KeybindingTableRow({
<div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
<div className="min-w-0 pr-4">
<div className="flex min-w-0 items-center gap-1.5">
<div className="truncate text-[13px] font-medium text-foreground" title={row.command}>
{commandLabel(row.command)}
</div>
<Tooltip>
<TooltipTrigger
render={
<div
aria-label={row.command}
className="truncate text-[13px] font-medium text-foreground"
/>
}
>
{commandLabel(row.command)}
</TooltipTrigger>
<TooltipPopup side="top">{row.command}</TooltipPopup>
</Tooltip>
</div>
</div>
<div className="flex min-w-0 items-center gap-2 pr-4">
@@ -0,0 +1,335 @@
"use client";
import { PipetteIcon, XIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { ColorSelector } from "../color-selector";
import { Button } from "../ui/button";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { normalizeProviderAccentColor } from "../../providerInstances";
import { cn } from "../../lib/utils";
const PROVIDER_ACCENT_SWATCHES = [
"#2563eb",
"#16a34a",
"#ea580c",
"#dc2626",
"#7c3aed",
"#0891b2",
] as const;
const FALLBACK_ACCENT_COLOR = PROVIDER_ACCENT_SWATCHES[0];
function clamp(value: number, min = 0, max = 1) {
return Math.min(max, Math.max(min, value));
}
function hexToHsv(hex: string) {
const normalized = normalizeProviderAccentColor(hex) ?? FALLBACK_ACCENT_COLOR;
const numeric = Number.parseInt(normalized.slice(1), 16);
const red = ((numeric >> 16) & 255) / 255;
const green = ((numeric >> 8) & 255) / 255;
const blue = (numeric & 255) / 255;
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === red) {
hue = ((green - blue) / delta) % 6;
} else if (max === green) {
hue = (blue - red) / delta + 2;
} else {
hue = (red - green) / delta + 4;
}
hue *= 60;
if (hue < 0) hue += 360;
}
return {
h: hue,
s: max === 0 ? 0 : delta / max,
v: max,
};
}
function hsvToHex(hue: number, saturation: number, value: number) {
const chroma = value * saturation;
const x = chroma * (1 - Math.abs(((hue / 60) % 2) - 1));
const match = value - chroma;
const [red, green, blue] =
hue < 60
? [chroma, x, 0]
: hue < 120
? [x, chroma, 0]
: hue < 180
? [0, chroma, x]
: hue < 240
? [0, x, chroma]
: hue < 300
? [x, 0, chroma]
: [chroma, 0, x];
return `#${[red, green, blue]
.map((channel) =>
Math.round((channel + match) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}
function ProviderCustomColorPanel(props: {
readonly value: string;
readonly onCommit: (value: string) => void;
}) {
const { onCommit } = props;
const initialHsv = useMemo(() => hexToHsv(props.value), [props.value]);
const [hsv, setHsv] = useState(initialHsv);
const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v);
const commitHsv = useCallback(
(nextHsv: typeof hsv) => {
setHsv(nextHsv);
onCommit(hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v));
},
[onCommit],
);
const updateFromPlane = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
const saturation = clamp((event.clientX - bounds.left) / bounds.width);
const value = 1 - clamp((event.clientY - bounds.top) / bounds.height);
commitHsv({ ...hsv, s: saturation, v: value });
},
[commitHsv, hsv],
);
const updateFromHue = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
commitHsv({ ...hsv, h: clamp((event.clientX - bounds.left) / bounds.width) * 360 });
},
[commitHsv, hsv],
);
const handlePointerDown = (handler: (event: PointerEvent<HTMLDivElement>) => void) => {
return (event: PointerEvent<HTMLDivElement>) => {
event.currentTarget.setPointerCapture(event.pointerId);
handler(event);
};
};
return (
<div className="w-56 bg-popover">
<div
className="relative h-36 cursor-crosshair touch-none"
style={{
backgroundColor: `hsl(${hsv.h} 100% 50%)`,
backgroundImage:
"linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)",
}}
onPointerDown={handlePointerDown(updateFromPlane)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
updateFromPlane(event);
}
}}
>
<span
className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35)]"
style={{ left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%` }}
/>
</div>
<div className="grid gap-3 p-3">
<div
className="relative h-3 cursor-pointer touch-none rounded-full"
style={{
background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
}}
onPointerDown={handlePointerDown(updateFromHue)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
updateFromHue(event);
}
}}
>
<span
className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35)]"
style={{ left: `${(hsv.h / 360) * 100}%`, backgroundColor: currentColor }}
/>
</div>
<input
value={currentColor}
onChange={(event) => {
const nextColor = event.currentTarget.value;
if (!/^#[\da-f]{6}$/i.test(nextColor)) return;
setHsv(hexToHsv(nextColor));
props.onCommit(nextColor);
}}
className="h-8 rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground outline-none transition-colors focus:border-ring"
aria-label="Custom hex accent color"
spellCheck={false}
/>
</div>
</div>
);
}
function ProviderCustomColorPicker(props: {
readonly displayName: string;
readonly value: string | undefined;
readonly selected: boolean;
readonly onCommit: (value: string) => void;
}) {
const normalized = normalizeProviderAccentColor(props.value) ?? FALLBACK_ACCENT_COLOR;
return (
<Popover>
<PopoverTrigger
render={
<button
type="button"
className={cn(
"flex size-6 cursor-pointer items-center justify-center rounded-full text-white transition-transform duration-200 active:scale-90",
"hover:scale-105",
)}
style={{
backgroundColor: normalized,
...(props.selected
? {
boxShadow: `inset 0 0 0 2px var(--card), 0 0 0 2px ${normalized}`,
}
: {}),
}}
aria-label={`Choose custom accent color for ${props.displayName}`}
>
<PipetteIcon className="size-3 text-foreground/25" aria-hidden />
</button>
}
/>
<PopoverPopup
side="bottom"
align="start"
sideOffset={6}
className="overflow-hidden rounded-md p-0 [--viewport-inline-padding:0px] [&_[data-slot=popover-viewport]]:p-0"
>
<ProviderCustomColorPanel value={normalized} onCommit={props.onCommit} />
</PopoverPopup>
</Popover>
);
}
export function ProviderAccentColorPicker(props: {
readonly displayName: string;
readonly value: string | undefined;
readonly onCommit: (value: string) => void;
readonly description?: string;
readonly commitDelayMs?: number;
}) {
const { commitDelayMs = 0, description, displayName, onCommit, value } = props;
const [optimisticValue, setOptimisticValue] = useState(() => value ?? "");
const commitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingCommitRef = useRef<string | null>(null);
const onCommitRef = useRef(onCommit);
useEffect(() => {
onCommitRef.current = onCommit;
}, [onCommit]);
useEffect(() => {
if (pendingCommitRef.current !== null) return;
setOptimisticValue(value ?? "");
}, [value]);
useEffect(() => {
return () => {
if (commitTimeoutRef.current !== null) {
clearTimeout(commitTimeoutRef.current);
}
const pendingCommit = pendingCommitRef.current;
if (pendingCommit !== null) {
onCommitRef.current(pendingCommit);
}
};
}, []);
const commitAccentColor = useCallback(
(value: string) => {
const normalizedValue = normalizeProviderAccentColor(value) ?? "";
setOptimisticValue(normalizedValue);
if (commitDelayMs <= 0) {
pendingCommitRef.current = null;
if (commitTimeoutRef.current !== null) {
clearTimeout(commitTimeoutRef.current);
commitTimeoutRef.current = null;
}
onCommit(normalizedValue);
return;
}
pendingCommitRef.current = normalizedValue;
if (commitTimeoutRef.current !== null) {
clearTimeout(commitTimeoutRef.current);
}
commitTimeoutRef.current = setTimeout(() => {
commitTimeoutRef.current = null;
const pendingCommit = pendingCommitRef.current;
pendingCommitRef.current = null;
if (pendingCommit !== null) {
onCommitRef.current(pendingCommit);
}
}, commitDelayMs);
},
[commitDelayMs, onCommit],
);
const normalized = normalizeProviderAccentColor(optimisticValue);
const selectedValue =
normalized &&
PROVIDER_ACCENT_SWATCHES.includes(normalized as (typeof PROVIDER_ACCENT_SWATCHES)[number])
? normalized
: "";
const customSelected = Boolean(normalized && selectedValue === "");
return (
<div className="grid gap-2">
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<ProviderCustomColorPicker
displayName={displayName}
value={normalized}
selected={customSelected}
onCommit={commitAccentColor}
/>
<ColorSelector
key={selectedValue}
colors={[...PROVIDER_ACCENT_SWATCHES]}
defaultValue={selectedValue}
size="lg"
onColorSelect={commitAccentColor}
className="flex-wrap gap-1.5"
/>
<Button
type="button"
size="icon"
variant="ghost"
className={cn(
"size-7 shrink-0 text-muted-foreground transition-opacity",
normalized ? "opacity-100" : "pointer-events-none opacity-0",
)}
onClick={() => commitAccentColor("")}
aria-label={`Clear accent color for ${displayName}`}
aria-hidden={!normalized}
tabIndex={normalized ? 0 : -1}
>
<XIcon className="size-3.5" aria-hidden />
</Button>
</div>
{description ? <span className="text-xs text-muted-foreground">{description}</span> : null}
</div>
);
}
@@ -12,7 +12,7 @@ import {
} from "lucide-react";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";
import { useEffect, useState, type ReactNode } from "react";
import { useState, type ReactNode } from "react";
import {
isProviderDriverKind,
type ProviderInstanceConfig,
@@ -28,17 +28,20 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { normalizeProviderAccentColor } from "../../providerInstances";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import type { DriverOption } from "./providerDriverMeta";
import { ProviderSettingsForm } from "./ProviderSettingsForm";
import { ProviderModelsSection } from "./ProviderModelsSection";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
import { RedactedSensitiveText } from "./RedactedSensitiveText";
import {
getProviderVersionAdvisoryPresentation,
@@ -48,15 +51,6 @@ import {
type ProviderStatusKey,
} from "./providerStatus";
const PROVIDER_ACCENT_SWATCHES = [
"#2563eb",
"#16a34a",
"#ea580c",
"#dc2626",
"#7c3aed",
"#0891b2",
] as const;
const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
let environmentVariableDraftId = 0;
@@ -83,6 +77,19 @@ function makeEnvironmentDraftRow(
};
}
function getProviderEnvironmentSectionKey(
environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
): string {
return JSON.stringify(
environment.map((variable) => [
variable.name,
variable.value,
variable.sensitive,
variable.valueRedacted ?? null,
]),
);
}
/**
* Read a string[] at `key` from the opaque config blob, filtering out
* non-string entries. Used for `customModels`, which is always typed as
@@ -159,94 +166,6 @@ function ProviderAuthEmail(props: {
);
}
function ProviderAccentColorPicker(props: {
readonly displayName: string;
readonly value: string | undefined;
readonly onCommit: (value: string) => void;
}) {
const [draft, setDraft] = useState(props.value ?? "");
const [isEditing, setIsEditing] = useState(false);
const draftColor = normalizeProviderAccentColor(draft);
useEffect(() => {
if (isEditing) return;
setDraft(props.value ?? "");
}, [isEditing, props.value]);
const commitDraft = () => {
setIsEditing(false);
props.onCommit(draftColor ?? "");
};
const commitSwatch = (swatch: string) => {
setIsEditing(false);
setDraft(swatch);
props.onCommit(swatch);
};
return (
<div className="grid gap-2">
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={draftColor ?? PROVIDER_ACCENT_SWATCHES[0]}
onFocus={() => setIsEditing(true)}
onInput={(event) => {
setIsEditing(true);
setDraft(event.currentTarget.value);
}}
onChange={(event) => {
setIsEditing(true);
setDraft(event.currentTarget.value);
}}
onBlur={commitDraft}
aria-label={`Accent color for ${props.displayName}`}
className="h-8 w-10 cursor-pointer rounded border border-input bg-background p-0.5"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
const selected = draftColor?.toLowerCase() === swatch;
return (
<button
key={swatch}
type="button"
className={cn(
"size-6 cursor-pointer rounded-full border transition",
selected
? "border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
: "border-black/10 hover:scale-105 dark:border-white/20",
)}
style={{ backgroundColor: swatch }}
onClick={() => commitSwatch(swatch)}
aria-label={`Use ${swatch} accent`}
/>
);
})}
</div>
{draftColor ? (
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground"
onClick={() => {
setIsEditing(false);
setDraft("");
props.onCommit("");
}}
>
Clear
</Button>
) : null}
</div>
<span className="text-xs text-muted-foreground">
Used to distinguish this instance in picker rails and model lists.
</span>
</div>
);
}
function ProviderEnvironmentSection(props: {
readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
@@ -255,10 +174,6 @@ function ProviderEnvironmentSection(props: {
props.environment.map(makeEnvironmentDraftRow),
);
useEffect(() => {
setRows(props.environment.map(makeEnvironmentDraftRow));
}, [props.environment]);
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
const published: ProviderInstanceEnvironmentVariable[] = [];
for (const row of nextRows) {
@@ -330,59 +245,83 @@ function ProviderEnvironmentSection(props: {
Add variables to pass API keys, base URLs, or other per-instance CLI settings.
</p>
) : (
<div className="grid gap-2">
{rows.map((variable, index) => (
<div
key={variable.id}
className="grid gap-2 rounded-md border border-border/70 bg-muted/20 p-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto_auto] sm:items-center"
>
<DraftInput
value={variable.name}
onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
placeholder="VARIABLE_NAME"
spellCheck={false}
aria-label={`Environment variable name ${index + 1}`}
/>
<DraftInput
value={variable.valueRedacted ? "" : variable.value}
onCommit={(value) => updateVariable(variable.id, { value })}
type={variable.sensitive ? "password" : undefined}
autoComplete="off"
placeholder={
variable.valueRedacted ? "Stored secret - enter a new value to replace" : "Value"
}
spellCheck={false}
aria-label={`Environment variable value ${index + 1}`}
/>
<label className="inline-flex h-8 items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
className="size-3.5"
checked={variable.sensitive}
onChange={(event) => {
const sensitive = event.currentTarget.checked;
updateVariable(variable.id, {
sensitive,
...(sensitive && variable.valueRedacted === undefined
? {}
: { valueRedacted: sensitive ? variable.valueRedacted : false }),
});
}}
/>
Sensitive
</label>
<Button
type="button"
size="icon-sm"
variant="ghost"
className="size-8 justify-self-start text-muted-foreground hover:text-destructive sm:justify-self-end"
onClick={() => removeVariable(variable.id)}
aria-label={`Remove environment variable ${variable.name || index + 1}`}
>
<XIcon className="size-3.5" />
</Button>
</div>
))}
<div className="overflow-hidden rounded-md border border-border/70">
<Table>
<TableHeader className="bg-muted/25 text-[11px] text-muted-foreground">
<TableRow className="hover:bg-transparent">
<TableHead>Variable</TableHead>
<TableHead>Value</TableHead>
<TableHead className="w-20">Sensitive</TableHead>
<TableHead className="w-12 text-right">
<span className="sr-only">Options</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((variable, index) => (
<TableRow
key={variable.id}
className="border-border/60 odd:bg-muted/20 even:bg-background/20"
>
<TableCell>
<DraftInput
value={variable.name}
onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
placeholder="VARIABLE_NAME"
spellCheck={false}
aria-label={`Environment variable name ${index + 1}`}
/>
</TableCell>
<TableCell>
<DraftInput
value={variable.valueRedacted ? "" : variable.value}
onCommit={(value) => updateVariable(variable.id, { value })}
type={variable.sensitive ? "password" : undefined}
autoComplete="off"
placeholder={
variable.valueRedacted
? "Stored secret - enter a new value to replace"
: "Value"
}
spellCheck={false}
aria-label={`Environment variable value ${index + 1}`}
/>
</TableCell>
<TableCell className="w-20">
<div className="flex h-8 items-center justify-center">
<Checkbox
checked={variable.sensitive}
onCheckedChange={(checked) => {
const sensitive = Boolean(checked);
updateVariable(variable.id, {
sensitive,
...(sensitive && variable.valueRedacted === undefined
? {}
: { valueRedacted: sensitive ? variable.valueRedacted : false }),
});
}}
aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
/>
</div>
</TableCell>
<TableCell className="w-12">
<div className="flex justify-end">
<Button
type="button"
size="icon-sm"
variant="ghost"
className="size-8 text-muted-foreground hover:text-destructive"
onClick={() => removeVariable(variable.id)}
aria-label={`Remove environment variable ${variable.name || index + 1}`}
>
<XIcon className="size-3.5" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
<span className="text-xs text-muted-foreground">
@@ -518,6 +457,8 @@ export function ProviderInstanceCard({
: null;
const customModels = readConfigStringArray(instance.config, "customModels");
const environment = instance.environment ?? [];
const environmentSectionKey = getProviderEnvironmentSectionKey(environment);
// Server-returned models may lag behind settings writes. Treat probe
// models as the source for built-ins only; custom rows come directly
// from the current instance config so add/remove reflects immediately.
@@ -582,16 +523,17 @@ export function ProviderInstanceCard({
accentColor={accentColor}
showBadge={Boolean(accentColor)}
statusDotClassName={statusStyle.dot}
indicatorBackground="var(--card)"
className="size-5"
iconClassName="size-4 text-foreground/80"
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
/>
) : FallbackIconComponent ? (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
<span
className={cn(
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-card",
statusStyle.dot,
)}
aria-hidden
@@ -825,12 +767,15 @@ export function ProviderInstanceCard({
displayName={displayName}
value={accentColor}
onCommit={updateAccentColor}
commitDelayMs={120}
description="Used to distinguish this instance in picker rails and model lists."
/>
</div>
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<ProviderEnvironmentSection
environment={instance.environment ?? []}
key={environmentSectionKey}
environment={environment}
onChange={updateEnvironment}
/>
</div>
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff. Show more