Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b948600014 | ||
|
|
23175df03a | ||
|
|
5b24144370 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e |
No files matched your search
+2
-2
@@ -1,5 +1,5 @@
|
||||
# Optional: T3 Cloud source builds
|
||||
# Leave these unset to disable optional T3 Cloud features in local source builds.
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Deploy T3 Cloud relay
|
||||
name: Deploy T3 Connect relay
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -167,7 +167,7 @@ jobs:
|
||||
--github-output
|
||||
|
||||
relay_public_config:
|
||||
name: Resolve T3 Cloud public config
|
||||
name: Resolve T3 Connect public config
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.24",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -165,7 +165,7 @@ describe("DesktopWindow", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isSameOriginRendererNavigation({
|
||||
applicationUrl: "http://127.0.0.1:3773/",
|
||||
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
|
||||
navigationUrl: "http://127.0.0.1:3773/settings/connections",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
|
||||
@@ -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>
|
||||
@@ -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">
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -16,7 +16,7 @@ This app has three variants:
|
||||
|
||||
Run commands from `apps/mobile`.
|
||||
|
||||
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
|
||||
T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the
|
||||
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
|
||||
[`../../.env.example`](../../.env.example).
|
||||
|
||||
|
||||
@@ -572,7 +572,7 @@ describe("mobile cloud link environment client", () => {
|
||||
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
|
||||
return Promise.resolve(Response.json(validLinkChallengeResponse()));
|
||||
}
|
||||
if (String(url).endsWith("/api/cloud/link-proof")) {
|
||||
if (String(url).endsWith("/api/connect/link-proof")) {
|
||||
return Promise.resolve(Response.json(validLinkProof()));
|
||||
}
|
||||
return Promise.resolve(Response.json(validLinkResponse("env-other")));
|
||||
@@ -631,7 +631,7 @@ describe("mobile cloud link environment client", () => {
|
||||
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
|
||||
return Promise.resolve(Response.json(validLinkChallengeResponse()));
|
||||
}
|
||||
if (String(url).endsWith("/api/cloud/link-proof")) {
|
||||
if (String(url).endsWith("/api/connect/link-proof")) {
|
||||
return Promise.resolve(Response.json(validLinkProof()));
|
||||
}
|
||||
return Promise.resolve(
|
||||
@@ -669,7 +669,7 @@ describe("mobile cloud link environment client", () => {
|
||||
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
|
||||
return Promise.resolve(Response.json(validLinkChallengeResponse()));
|
||||
}
|
||||
if (String(url).endsWith("/api/cloud/link-proof")) {
|
||||
if (String(url).endsWith("/api/connect/link-proof")) {
|
||||
return Promise.resolve(Response.json(validLinkProof()));
|
||||
}
|
||||
return Promise.resolve(
|
||||
@@ -713,7 +713,7 @@ describe("mobile cloud link environment client", () => {
|
||||
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
|
||||
return Promise.resolve(Response.json(validLinkChallengeResponse()));
|
||||
}
|
||||
if (String(url).endsWith("/api/cloud/link-proof")) {
|
||||
if (String(url).endsWith("/api/connect/link-proof")) {
|
||||
return Promise.resolve(Response.json(validLinkProof()));
|
||||
}
|
||||
if (String(url).endsWith("/v1/client/environment-links")) {
|
||||
|
||||
@@ -301,7 +301,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
),
|
||||
);
|
||||
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
|
||||
const proof = yield* environmentClient.cloud
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers: { authorization: `Bearer ${localBearerToken}` },
|
||||
payload: {
|
||||
@@ -336,7 +336,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
link,
|
||||
});
|
||||
|
||||
yield* environmentClient.cloud
|
||||
yield* environmentClient.connect
|
||||
.relayConfig({
|
||||
headers: { authorization: `Bearer ${localBearerToken}` },
|
||||
payload: {
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { ProjectionCheckpointRepository } from "../src/persistence/Services/Proj
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
@@ -293,6 +294,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
);
|
||||
const providerRegistryLayer = makeProviderRegistryLayer();
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
@@ -375,6 +377,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.24",
|
||||
"version": "0.0.27",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -18,9 +18,15 @@ const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
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 permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
|
||||
};
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
@@ -237,6 +243,21 @@ function modeState(): AcpSchema.SessionModeState {
|
||||
};
|
||||
}
|
||||
|
||||
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
|
||||
{ modelId: "grok-build", name: "Grok Build" },
|
||||
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
|
||||
];
|
||||
|
||||
function modelState(): AcpSchema.SessionModelState {
|
||||
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
|
||||
? currentModelId
|
||||
: "grok-build";
|
||||
return {
|
||||
currentModelId: modelId,
|
||||
availableModels: grokAcpModels,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
@@ -257,6 +278,7 @@ const program = Effect.gen(function* () {
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
@@ -273,11 +295,28 @@ const program = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
`Unknown mock model id: ${request.modelId}`,
|
||||
{
|
||||
method: "session/set_model",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
currentModelId = request.modelId;
|
||||
return {};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
@@ -419,9 +458,13 @@ const program = Effect.gen(function* () {
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
|
||||
{
|
||||
optionId: permissionOptionIds.allowAlways,
|
||||
name: "Allow always",
|
||||
kind: "allow_always",
|
||||
},
|
||||
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -514,6 +557,43 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitXAiAskUserQuestion) {
|
||||
const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
|
||||
method: "x.ai/ask_user_question",
|
||||
params: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCallId: "ask-user-question-tool-call-1",
|
||||
questions: [
|
||||
{
|
||||
question: "Which scope should Grok use?",
|
||||
multiSelect: null,
|
||||
options: [
|
||||
{ label: "Workspace", description: "Use the current workspace" },
|
||||
{ label: "Session", description: "Only use this session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
mode: "default",
|
||||
},
|
||||
});
|
||||
if (typeof result !== "object" || result === null || !("outcome" in result)) {
|
||||
throw new Error("Expected _x.ai/ask_user_question response outcome.");
|
||||
}
|
||||
if (result.outcome === "cancelled") {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
if (
|
||||
result.outcome !== "accepted" ||
|
||||
!("answers" in result) ||
|
||||
typeof result.answers !== "object" ||
|
||||
result.answers === null
|
||||
) {
|
||||
throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
|
||||
}
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
|
||||
+26
-24
@@ -38,11 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
|
||||
|
||||
const cloudCli = makeCli({ cloudEnabled: true });
|
||||
const noCloudCli = makeCli({ cloudEnabled: false });
|
||||
const connectCli = makeCli({ cloudEnabled: true });
|
||||
const noConnectCli = makeCli({ cloudEnabled: false });
|
||||
const runCli = (args: ReadonlyArray<string>, command = cli) =>
|
||||
Command.runWith(command, { version: "0.0.0" })(args);
|
||||
const runCloudCli = (args: ReadonlyArray<string>) => runCli(args, cloudCli);
|
||||
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
|
||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
||||
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
|
||||
|
||||
@@ -179,9 +179,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects cloud commands when public cloud configuration is missing", () =>
|
||||
it.effect("rejects connect commands when public configuration is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip);
|
||||
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
@@ -189,20 +189,20 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "cloud"]);
|
||||
assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration");
|
||||
assert.deepEqual(error.commandPath, ["t3", "connect"]);
|
||||
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
|
||||
|
||||
const output = (yield* TestConsole.errorLines).join("\n");
|
||||
assert.include(output, "ERROR");
|
||||
assert.include(output, "missing T3 Cloud public configuration");
|
||||
assert.include(output, "missing T3 Connect public configuration");
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless cloud state without requiring local configuration", () =>
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
|
||||
const { output } = yield* captureStdout(
|
||||
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
|
||||
const status = JSON.parse(output) as {
|
||||
@@ -221,21 +221,21 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports actionable human-readable headless cloud state", () =>
|
||||
it.effect("reports actionable human-readable headless connect state", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
|
||||
const { output } = yield* captureStdout(
|
||||
runCloudCli(["cloud", "status", "--base-dir", baseDir]),
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.include(output, "T3 Cloud\n Exposure: disabled");
|
||||
assert.include(output, "T3 Connect\n Exposure: disabled");
|
||||
assert.include(output, " Authorization: missing");
|
||||
assert.include(output, " Environment link: not provisioned");
|
||||
assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure.");
|
||||
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs in to headless cloud without enabling exposure", () =>
|
||||
it.effect("logs in to headless connect without enabling access", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
|
||||
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
|
||||
@@ -250,9 +250,11 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir]));
|
||||
const login = yield* captureStdout(
|
||||
runConnectCli(["connect", "login", "--base-dir", baseDir]),
|
||||
);
|
||||
const status = yield* captureStdout(
|
||||
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
|
||||
const decoded = JSON.parse(status.output) as {
|
||||
@@ -260,24 +262,24 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
readonly authenticated: boolean;
|
||||
};
|
||||
|
||||
assert.equal(login.output, "Signed in to T3 Cloud.");
|
||||
assert.equal(login.output, "Signed in to T3 Connect.");
|
||||
assert.isFalse(decoded.desired);
|
||||
assert.isTrue(decoded.authenticated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("disables headless cloud exposure without a running server", () =>
|
||||
it.effect("disables headless connect without a running server", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
|
||||
const { output } = yield* captureStdout(
|
||||
runCloudCli(["cloud", "unlink", "--base-dir", baseDir]),
|
||||
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(output, "T3 Cloud exposure is disabled locally.");
|
||||
assert.equal(output, "T3 Connect is disabled locally.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs out of headless cloud and removes the stored CLI authorization", () =>
|
||||
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
|
||||
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
|
||||
@@ -286,10 +288,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
writeFileSync(tokenPath, "invalid persisted token");
|
||||
|
||||
const { output } = yield* captureStdout(
|
||||
runCloudCli(["cloud", "logout", "--base-dir", baseDir]),
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(output, "Signed out of T3 Cloud locally.");
|
||||
assert.equal(output, "Signed out of T3 Connect locally.");
|
||||
assert.isFalse(existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
|
||||
+10
-10
@@ -8,7 +8,7 @@ import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { cloudCommand } from "./cli/cloud.ts";
|
||||
import { connectCommand } from "./cli/connect.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
@@ -16,23 +16,23 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
const cloudPublicConfigMissingMessage =
|
||||
"T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration.";
|
||||
const connectPublicConfigMissingMessage =
|
||||
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
|
||||
|
||||
class CloudPublicConfigMissingError extends CliError.UserError {
|
||||
class ConnectPublicConfigMissingError extends CliError.UserError {
|
||||
override get message() {
|
||||
return cloudPublicConfigMissingMessage;
|
||||
return connectPublicConfigMissingMessage;
|
||||
}
|
||||
}
|
||||
|
||||
const cloudUnavailableCommand = Command.make("cloud").pipe(
|
||||
Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."),
|
||||
const connectUnavailableCommand = Command.make("connect").pipe(
|
||||
Command.withDescription("T3 Connect is unavailable in builds without public configuration."),
|
||||
Command.withHidden,
|
||||
Command.withHandler(() =>
|
||||
Effect.fail(
|
||||
new CliError.ShowHelp({
|
||||
commandPath: ["t3", "cloud"],
|
||||
errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })],
|
||||
commandPath: ["t3", "connect"],
|
||||
errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -47,7 +47,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
|
||||
serveCommand,
|
||||
authCommand,
|
||||
projectCommand,
|
||||
cloudEnabled ? cloudCommand : cloudUnavailableCommand,
|
||||
cloudEnabled ? connectCommand : connectUnavailableCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { acquireRelayClientForLink } from "./cloud.ts";
|
||||
import { acquireRelayClientForLink } from "./connect.ts";
|
||||
|
||||
const managedExecutable = {
|
||||
status: "available",
|
||||
@@ -89,15 +89,15 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
|
||||
? "pending server startup"
|
||||
: "not provisioned";
|
||||
const nextStep = !status.authenticated
|
||||
? "Run `t3 cloud link` to authorize and enable cloud exposure."
|
||||
? "Run `t3 connect link` to authorize and enable T3 Connect."
|
||||
: !status.desired
|
||||
? "Run `t3 cloud link` to enable cloud exposure."
|
||||
? "Run `t3 connect link` to enable T3 Connect."
|
||||
: !status.linked
|
||||
? "Start T3 to provision the environment link and launch its managed tunnel."
|
||||
: undefined;
|
||||
|
||||
return [
|
||||
"T3 Cloud",
|
||||
"T3 Connect",
|
||||
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
|
||||
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
|
||||
` Environment link: ${provisioned}`,
|
||||
@@ -112,7 +112,7 @@ const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
|
||||
const confirmRelayClientInstall = (version: string) =>
|
||||
Prompt.run(
|
||||
Prompt.confirm({
|
||||
message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`,
|
||||
message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
|
||||
initial: false,
|
||||
}),
|
||||
);
|
||||
@@ -169,7 +169,7 @@ const withCloudCliSessionToken = <A, E, R>(
|
||||
environmentAuth.issueSession({
|
||||
scopes: [AuthRelayWriteScope],
|
||||
subject: "cloud-cli",
|
||||
label: "t3 cloud cli",
|
||||
label: "t3 connect cli",
|
||||
}),
|
||||
(issued) => run(issued.token),
|
||||
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
|
||||
@@ -194,7 +194,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
|
||||
baseUrl: runtimeState.value.origin,
|
||||
}).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }),
|
||||
client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
|
||||
),
|
||||
Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
|
||||
),
|
||||
@@ -249,24 +249,24 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
|
||||
|
||||
if (liveResult.status === "failed") {
|
||||
yield* Console.warn(
|
||||
`T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
|
||||
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
|
||||
);
|
||||
} else {
|
||||
yield* Console.log("T3 Cloud exposure is disabled locally.");
|
||||
yield* Console.log("T3 Connect is disabled locally.");
|
||||
}
|
||||
|
||||
if (Exit.isFailure(relayResult)) {
|
||||
yield* Console.warn(
|
||||
options.clearAuthorization
|
||||
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
|
||||
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`,
|
||||
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
|
||||
);
|
||||
} else if (relayResult.value.status === "revoked") {
|
||||
yield* Console.log("Revoked the relay-side environment record.");
|
||||
}
|
||||
|
||||
if (options.clearAuthorization) {
|
||||
yield* Console.log("Signed out of T3 Cloud locally.");
|
||||
yield* Console.log("Signed out of T3 Connect locally.");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -307,26 +307,26 @@ const runCloudCommand = <A, E>(
|
||||
return yield* run.pipe(Effect.provide(runtimeLayer));
|
||||
});
|
||||
|
||||
const cloudLoginCommand = Command.make("login", {
|
||||
const connectLoginCommand = Command.make("login", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."),
|
||||
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
yield* tokens.get;
|
||||
yield* Console.log("Signed in to T3 Cloud.");
|
||||
yield* Console.log("Signed in to T3 Connect.");
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudLinkCommand = Command.make("link", {
|
||||
const connectLinkCommand = Command.make("link", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."),
|
||||
Command.withDescription("Authorize this environment for T3 Connect on next start."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
@@ -338,7 +338,7 @@ const cloudLinkCommand = Command.make("link", {
|
||||
reportRelayClientInstallProgress,
|
||||
);
|
||||
if (Option.isNone(installed)) {
|
||||
yield* Console.log("T3 Cloud link cancelled. The relay client was not installed.");
|
||||
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
@@ -349,18 +349,18 @@ const cloudLinkCommand = Command.make("link", {
|
||||
yield* tokens.get;
|
||||
yield* CliState.setCliDesiredCloudLink(true);
|
||||
yield* Console.log(
|
||||
"This T3 environment will be available over T3 Cloud the next time T3 starts.",
|
||||
"This T3 environment will be available through T3 Connect the next time T3 starts.",
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudStatusCommand = Command.make("status", {
|
||||
const connectStatusCommand = Command.make("status", {
|
||||
...projectLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Show persisted T3 Cloud and relay client state."),
|
||||
Command.withDescription("Show persisted T3 Connect and relay client state."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
@@ -395,31 +395,31 @@ const cloudStatusCommand = Command.make("status", {
|
||||
),
|
||||
);
|
||||
|
||||
const cloudUnlinkCommand = Command.make("unlink", {
|
||||
const connectUnlinkCommand = Command.make("unlink", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."),
|
||||
Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudLogoutCommand = Command.make("logout", {
|
||||
const connectLogoutCommand = Command.make("logout", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."),
|
||||
Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
|
||||
),
|
||||
);
|
||||
|
||||
export const cloudCommand = Command.make("cloud").pipe(
|
||||
Command.withDescription("Manage headless T3 Cloud exposure."),
|
||||
export const connectCommand = Command.make("connect").pipe(
|
||||
Command.withDescription("Manage headless T3 Connect access."),
|
||||
Command.withSubcommands([
|
||||
cloudLoginCommand,
|
||||
cloudLinkCommand,
|
||||
cloudStatusCommand,
|
||||
cloudUnlinkCommand,
|
||||
cloudLogoutCommand,
|
||||
connectLoginCommand,
|
||||
connectLinkCommand,
|
||||
connectStatusCommand,
|
||||
connectUnlinkCommand,
|
||||
connectLogoutCommand,
|
||||
]),
|
||||
);
|
||||
@@ -96,7 +96,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const clear = secrets
|
||||
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
|
||||
.pipe(wrapError("Could not remove the stored T3 Cloud CLI credential."));
|
||||
.pipe(wrapError("Could not remove the stored T3 Connect CLI credential."));
|
||||
|
||||
const read = Effect.fn("cloud.cli_token.read")(function* () {
|
||||
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
|
||||
@@ -146,7 +146,7 @@ const make = Effect.gen(function* () {
|
||||
const url = new URL(request.originalUrl, metadata.redirectUri);
|
||||
const code = url.searchParams.get("code");
|
||||
if (url.searchParams.get("state") !== state || !code) {
|
||||
return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", {
|
||||
return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
@@ -154,7 +154,7 @@ const make = Effect.gen(function* () {
|
||||
return yield* HttpServerResponse.html`
|
||||
<html>
|
||||
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
|
||||
<h1>T3 Cloud authorization complete</h1>
|
||||
<h1>T3 Connect authorization complete</h1>
|
||||
<p>You can close this window and return to your terminal.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -182,13 +182,13 @@ const make = Effect.gen(function* () {
|
||||
authorizationUrl.searchParams.set("state", state);
|
||||
authorizationUrl.searchParams.set("code_challenge", challenge);
|
||||
authorizationUrl.searchParams.set("code_challenge_method", "S256");
|
||||
yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`);
|
||||
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
|
||||
const code = yield* Deferred.await(callback).pipe(
|
||||
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
|
||||
Effect.catchTag("TimeoutError", () =>
|
||||
Effect.fail(
|
||||
new CloudCliTokenManagerError({
|
||||
message: "Timed out waiting for T3 Cloud authorization.",
|
||||
message: "Timed out waiting for T3 Connect authorization.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -213,12 +213,12 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const getExisting = semaphore.withPermits(1)(
|
||||
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")),
|
||||
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")),
|
||||
);
|
||||
const hasCredential = semaphore.withPermits(1)(
|
||||
read().pipe(
|
||||
Effect.map(Option.isSome),
|
||||
wrapError("Could not read the stored T3 Cloud CLI credential."),
|
||||
wrapError("Could not read the stored T3 Connect CLI credential."),
|
||||
),
|
||||
);
|
||||
const get = semaphore.withPermits(1)(
|
||||
@@ -227,7 +227,7 @@ const make = Effect.gen(function* () {
|
||||
return Option.isSome(token)
|
||||
? token.value
|
||||
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
|
||||
}).pipe(wrapError("Could not authorize the T3 Cloud CLI.")),
|
||||
}).pipe(wrapError("Could not authorize the T3 Connect CLI.")),
|
||||
);
|
||||
|
||||
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
|
||||
|
||||
@@ -76,7 +76,7 @@ describe("reconcileDesiredCloudLink", () => {
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "EnvironmentHttpUnauthorizedError",
|
||||
message: "Run `t3 cloud link` to authorize this environment.",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
|
||||
@@ -509,7 +509,7 @@ const relayClientRequest = <A>(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentHttpInternalServerError({
|
||||
message: `T3 Cloud relay request failed: ${String(cause)}`,
|
||||
message: `T3 Connect relay request failed: ${String(cause)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -535,7 +535,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentHttpUnauthorizedError({
|
||||
message: "Run `t3 cloud link` to authorize this environment.",
|
||||
message: "Run `t3 connect link` to authorize this environment.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
@@ -595,7 +595,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
|
||||
CloudCliTokenManagerError: (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error.cause),
|
||||
SecretStoreError: failEnvironmentCloudInternalError(
|
||||
"Could not persist desired T3 Cloud link state.",
|
||||
"Could not persist desired T3 Connect link state.",
|
||||
),
|
||||
}),
|
||||
);
|
||||
@@ -874,7 +874,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
scopes: AuthStandardClientScopes,
|
||||
subject: "cloud-connect",
|
||||
ttl: Duration.minutes(2),
|
||||
label: "T3 Cloud connect",
|
||||
label: "T3 Connect connect",
|
||||
proofKeyThumbprint: proof.clientProofKeyThumbprint,
|
||||
});
|
||||
const responsePayload = {
|
||||
@@ -924,9 +924,9 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
}),
|
||||
);
|
||||
|
||||
export const cloudHttpApiLayer = HttpApiBuilder.group(
|
||||
export const connectHttpApiLayer = HttpApiBuilder.group(
|
||||
EnvironmentHttpApi,
|
||||
"cloud",
|
||||
"connect",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const dependencies = yield* cloudHttpDependencies;
|
||||
return handlers
|
||||
|
||||
@@ -28,6 +28,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -142,6 +144,7 @@ describe("ProviderCommandReactor", () => {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
readonly requiresNewThreadForModelChange?: boolean;
|
||||
}) {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
@@ -280,6 +283,14 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const providerSnapshots = [
|
||||
{
|
||||
instanceId: modelSelection.instanceId,
|
||||
...(input?.requiresNewThreadForModelChange === true
|
||||
? { requiresNewThreadForModelChange: true }
|
||||
: {}),
|
||||
},
|
||||
];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
@@ -335,6 +346,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
renameBranch,
|
||||
@@ -879,6 +891,80 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"rejects changing models after start when the provider requires a new thread",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({ requiresNewThreadForModelChange: true }),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restricted-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restricted-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restricted-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restricted-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.1-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.make("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
) ?? false
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
|
||||
const readModel = yield* Effect.promise(() => harness.readModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining(
|
||||
"cannot switch models after the conversation has started",
|
||||
),
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
|
||||
|
||||
@@ -31,6 +31,7 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -180,6 +181,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -305,6 +307,38 @@ const make = Effect.gen(function* () {
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly currentModelSelection: ModelSelection;
|
||||
readonly requestedModelSelection: ModelSelection | undefined;
|
||||
}) {
|
||||
const requestedModelSelection = input.requestedModelSelection;
|
||||
if (
|
||||
requestedModelSelection === undefined ||
|
||||
(input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&
|
||||
input.currentModelSelection.model === requestedModelSelection.model)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const providers = yield* providerRegistry.getProviders;
|
||||
const requiresNewThread =
|
||||
providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)
|
||||
?.requiresNewThreadForModelChange === true ||
|
||||
providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)
|
||||
?.requiresNewThreadForModelChange === true;
|
||||
if (!requiresNewThread) {
|
||||
return;
|
||||
}
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerErrorLabelFromInstanceHint({
|
||||
instanceId: String(requestedModelSelection.instanceId),
|
||||
modelSelectionInstanceId: String(input.currentModelSelection.instanceId),
|
||||
}),
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,
|
||||
});
|
||||
});
|
||||
|
||||
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
@@ -384,6 +418,20 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderDriverKind = desiredDriverKind;
|
||||
if (thread.session !== null) {
|
||||
yield* rejectStartedThreadModelChangeIfRequired({
|
||||
threadId,
|
||||
currentModelSelection:
|
||||
activeSession?.model !== undefined
|
||||
? {
|
||||
...thread.modelSelection,
|
||||
instanceId: currentInstanceId,
|
||||
model: activeSession.model,
|
||||
}
|
||||
: thread.modelSelection,
|
||||
requestedModelSelection,
|
||||
});
|
||||
}
|
||||
if (
|
||||
thread.session !== null &&
|
||||
requestedModelSelection !== undefined &&
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
|
||||
import {
|
||||
buildInitialGrokProviderSnapshot,
|
||||
checkGrokProviderStatus,
|
||||
enrichGrokSnapshot,
|
||||
} from "../Layers/GrokProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
}),
|
||||
);
|
||||
|
||||
export type GrokDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
...snapshot,
|
||||
instanceId: input.instanceId,
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "Grok",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: GrokSettings,
|
||||
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeGrokAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
instanceId,
|
||||
});
|
||||
const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
|
||||
|
||||
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<GrokSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) =>
|
||||
buildInitialGrokProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot: currentSnapshot, publishSnapshot }) =>
|
||||
enrichGrokSnapshot({
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
publishSnapshot,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -447,6 +447,29 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("preserves xhigh effort for Claude Fable 5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
"claude-fable-5",
|
||||
[{ id: "effort", value: "xhigh" }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "xhigh");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -48,50 +48,42 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
|
||||
const CLAUDE_EFFORT_OPTIONS = {
|
||||
opus48: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
opus47: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
opus46: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
sonnet46: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
opus45: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "claude-fable-5",
|
||||
name: "Claude Fable 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
@@ -101,9 +93,21 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus48,
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
@@ -124,9 +128,20 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus47,
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
@@ -147,7 +162,13 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus46,
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
@@ -174,7 +195,12 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus45,
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
@@ -192,7 +218,13 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: CLAUDE_EFFORT_OPTIONS.sonnet46,
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
@@ -221,6 +253,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeFable5(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeOpus48(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -233,6 +269,9 @@ function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-fable-5") {
|
||||
return supportsClaudeFable5(version);
|
||||
}
|
||||
if (model.slug === "claude-opus-4-8") {
|
||||
return supportsClaudeOpus48(version);
|
||||
}
|
||||
@@ -243,6 +282,11 @@ function getBuiltInClaudeModelsForVersion(
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeFable5UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeOpus48UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;
|
||||
@@ -294,7 +338,7 @@ export function normalizeClaudeCliEffort(
|
||||
if (effort === "ultracode") {
|
||||
return "xhigh";
|
||||
}
|
||||
if (effort === "xhigh" && model !== "claude-opus-4-8") {
|
||||
if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") {
|
||||
return "max";
|
||||
}
|
||||
if (effort === "max" && model === "claude-sonnet-4-6") {
|
||||
@@ -688,11 +732,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeOpus48(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
GrokSettings,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const mockAgentCommand = process.execPath;
|
||||
|
||||
async function makeMockGrokWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "grok-acp-mock-"));
|
||||
const wrapperPath = path.join(dir, "fake-grok.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
return yield* Effect.die(new Error(`Timed out waiting for file content at ${filePath}`));
|
||||
}
|
||||
const raw = yield* Effect.tryPromise(() => readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (raw.trim().length > 0) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
return yield* readAttempt(remainingAttempts - 1);
|
||||
});
|
||||
return readAttempt(attempts);
|
||||
}
|
||||
|
||||
async function readJsonLines(filePath: string) {
|
||||
const raw = await readFile(filePath, "utf8");
|
||||
return raw
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as Record<string, unknown>);
|
||||
}
|
||||
|
||||
const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-grok-adapter-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
|
||||
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-mock-thread");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-mock-alt" },
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "grok");
|
||||
assert.equal(session.model, "grok-mock-alt");
|
||||
assert.deepStrictEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "mock-session-1",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hello grok",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
const types = runtimeEvents.map((e) => e.type);
|
||||
|
||||
assert.includeMembers(types, [
|
||||
"session.started",
|
||||
"session.state.changed",
|
||||
"thread.started",
|
||||
"turn.started",
|
||||
"item.started",
|
||||
"content.delta",
|
||||
"turn.completed",
|
||||
] as const);
|
||||
|
||||
const delta = runtimeEvents.find((e) => e.type === "content.delta");
|
||||
assert.isDefined(delta);
|
||||
if (delta?.type === "content.delta") {
|
||||
assert.equal(delta.payload.delta, "hello from mock");
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process when a session stops", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-session-close");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
mkdtemp(path.join(os.tmpdir(), "grok-adapter-exit-log-")),
|
||||
);
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
assert.include(exitLog, "SIGTERM");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects startSession when provider mismatches", () =>
|
||||
Effect.gen(function* () {
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const threadId = ThreadId.make("grok-provider-mismatch");
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterValidationError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects sendTurn with empty input and no attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-empty-turn");
|
||||
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: " ",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterValidationError");
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("responds to ACP approvals using provider-supplied option ids", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-custom-approval-option-id");
|
||||
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "grok-acp-")));
|
||||
const requestLogPath = path.join(tempDir, "requests.ndjson");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
T3_ACP_ALLOW_ONCE_OPTION_ID: "agent-defined-approval-id",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(event.requestId)),
|
||||
"accept",
|
||||
)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "approve this", attachments: [] });
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
(entry) =>
|
||||
!("method" in entry) &&
|
||||
typeof entry.result === "object" &&
|
||||
entry.result !== null &&
|
||||
"outcome" in entry.result &&
|
||||
typeof entry.result.outcome === "object" &&
|
||||
entry.result.outcome !== null &&
|
||||
"optionId" in entry.result.outcome &&
|
||||
entry.result.outcome.optionId === "agent-defined-approval-id",
|
||||
),
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles xAI ask_user_question extension requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-ask-user-question");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_ASK_USER_QUESTION: "1" }),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const requested =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.requested" }>>();
|
||||
const resolved =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.resolved" }>>();
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (event.type === "user-input.requested") {
|
||||
return Deferred.succeed(requested, event).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "user-input.resolved") {
|
||||
return Deferred.succeed(resolved, event).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "ask before continuing", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestedEvent = yield* Deferred.await(requested);
|
||||
assert.equal(requestedEvent.payload.questions.length, 1);
|
||||
assert.equal(requestedEvent.payload.questions[0]?.id, "Which scope should Grok use?");
|
||||
assert.equal(requestedEvent.payload.questions[0]?.question, "Which scope should Grok use?");
|
||||
assert.equal(requestedEvent.raw?.method, "_x.ai/ask_user_question");
|
||||
|
||||
yield* adapter.respondToUserInput(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(requestedEvent.requestId)),
|
||||
{
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
},
|
||||
);
|
||||
|
||||
const resolvedEvent = yield* Deferred.await(resolved);
|
||||
assert.deepEqual(resolvedEvent.payload.answers, {
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
});
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("continues streaming events when native notification logging fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-native-log-failure");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://grok-native-events",
|
||||
write: (record: unknown) =>
|
||||
typeof record === "object" &&
|
||||
record !== null &&
|
||||
"event" in record &&
|
||||
typeof record.event === "object" &&
|
||||
record.event !== null &&
|
||||
"kind" in record.event &&
|
||||
record.event.kind === "notification"
|
||||
? Effect.die(new Error("native log write failed"))
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "keep streaming", attachments: [] });
|
||||
yield* Deferred.await(contentDelta);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,934 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type GrokSettings,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderUserInputAnswers,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
RuntimeRequestId,
|
||||
type ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
|
||||
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "../acp/AcpCoreRuntimeEvents.ts";
|
||||
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../acp/GrokAcpSupport.ts";
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("grok");
|
||||
const GROK_RESUME_VERSION = 1 as const;
|
||||
|
||||
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
|
||||
const result = encodeUnknownJsonStringExit(input);
|
||||
return Exit.isSuccess(result) ? result.value : undefined;
|
||||
}
|
||||
|
||||
export interface GrokAdapterLiveOptions {
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly instanceId?: ProviderInstanceId;
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
|
||||
}
|
||||
|
||||
type PendingUserInputResolution =
|
||||
| { readonly _tag: "answered"; readonly answers: ProviderUserInputAnswers }
|
||||
| { readonly _tag: "cancelled" };
|
||||
|
||||
interface PendingUserInput {
|
||||
readonly resolution: Deferred.Deferred<PendingUserInputResolution>;
|
||||
}
|
||||
|
||||
interface GrokSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly acpSessionId: string;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
currentModelId: string | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function settlePendingApprovalsAsCancelled(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
Array.from(pendingApprovals.values()),
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingUserInputsAsCancelled(
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
Array.from(pendingUserInputs.values()),
|
||||
(pending) => Deferred.succeed(pending.resolution, { _tag: "cancelled" }).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
|
||||
if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
|
||||
return { sessionId: raw.sessionId.trim() };
|
||||
}
|
||||
|
||||
function selectPermissionOptionId(
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
decision: Exclude<ProviderApprovalDecision, "cancel">,
|
||||
): string | undefined {
|
||||
const kind =
|
||||
decision === "acceptForSession"
|
||||
? "allow_always"
|
||||
: decision === "accept"
|
||||
? "allow_once"
|
||||
: "reject_once";
|
||||
const option = request.options.find((entry) => entry.kind === kind);
|
||||
return option?.optionId.trim() || undefined;
|
||||
}
|
||||
|
||||
function selectAutoApprovedPermissionOption(
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
): string | undefined {
|
||||
return (
|
||||
selectPermissionOptionId(request, "acceptForSession") ??
|
||||
selectPermissionOptionId(request, "accept")
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
|
||||
|
||||
const sessions = new Map<ThreadId, GrokSessionContext>();
|
||||
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "crypto/randomUUIDv4",
|
||||
detail: "Failed to generate Grok runtime identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
|
||||
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
|
||||
const mapAcpCallbackFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
detail: "Failed to process Grok ACP callback.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
|
||||
|
||||
const getThreadSemaphore = (threadId: string) =>
|
||||
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
|
||||
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
|
||||
current.get(threadId),
|
||||
);
|
||||
return Option.match(existing, {
|
||||
onNone: () =>
|
||||
Semaphore.make(1).pipe(
|
||||
Effect.map((semaphore) => {
|
||||
const next = new Map(current);
|
||||
next.set(threadId, semaphore);
|
||||
return [semaphore, next] as const;
|
||||
}),
|
||||
),
|
||||
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
|
||||
});
|
||||
});
|
||||
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
const observedAt = yield* nowIso;
|
||||
yield* nativeEventLogger.write(
|
||||
{
|
||||
observedAt,
|
||||
event: {
|
||||
id: yield* randomUUIDv4,
|
||||
kind: "notification",
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
method,
|
||||
threadId,
|
||||
payload,
|
||||
},
|
||||
},
|
||||
threadId,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to write native Grok notification log.", {
|
||||
cause,
|
||||
threadId,
|
||||
method,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const emitPlanUpdate = (
|
||||
ctx: GrokSessionContext,
|
||||
payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
},
|
||||
rawPayload: unknown,
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
rawPayload,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const requireSession = (
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<GrokSessionContext, ProviderAdapterSessionNotFoundError> => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
};
|
||||
|
||||
const stopSessionInternal = (ctx: GrokSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
|
||||
sessions.delete(ctx.threadId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
payload: { exitKind: "graceful" },
|
||||
});
|
||||
});
|
||||
|
||||
const startSession: GrokAdapterShape["startSession"] = (input) =>
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
}
|
||||
|
||||
const cwd = path.resolve(input.cwd.trim());
|
||||
const grokModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing && !existing.stopped) {
|
||||
yield* stopSessionInternal(existing);
|
||||
}
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
|
||||
);
|
||||
|
||||
const resumeSessionId = parseGrokResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
const acp = yield* makeGrokAcpRuntime({
|
||||
grokSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
|
||||
(method) =>
|
||||
acp.handleExtRequest(method, XAiAskUserQuestionRequest, (params) =>
|
||||
mapAcpCallbackFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(input.threadId, method, params);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const resolution = yield* Deferred.make<PendingUserInputResolution>();
|
||||
pendingUserInputs.set(requestId, { resolution });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
source: "acp.grok.extension",
|
||||
method,
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
const resolved = yield* Deferred.await(resolution);
|
||||
pendingUserInputs.delete(requestId);
|
||||
const resolvedAnswers = resolved._tag === "answered" ? resolved.answers : {};
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
source: "acp.grok.extension",
|
||||
method,
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
switch (resolved._tag) {
|
||||
case "answered":
|
||||
return makeXAiAskUserQuestionResponse(params, resolved.answers);
|
||||
case "cancelled":
|
||||
return makeXAiAskUserQuestionCancelledResponse();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
mapAcpCallbackFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(input.threadId, "session/request_permission", params);
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: autoApprovedOptionId,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
const selectedOptionId =
|
||||
resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved);
|
||||
return {
|
||||
outcome: selectedOptionId
|
||||
? {
|
||||
outcome: "selected" as const,
|
||||
optionId: selectedOptionId,
|
||||
}
|
||||
: ({ outcome: "cancelled" } as const),
|
||||
};
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
const requestedStartModelId = grokModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(grokModelSelection.model)
|
||||
: undefined;
|
||||
const boundModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: acp,
|
||||
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
requestedModelId: requestedStartModelId,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: PROVIDER,
|
||||
providerInstanceId: boundInstanceId,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd,
|
||||
...(boundModelId ? { model: resolveGrokAcpBaseModelId(boundModelId) } : {}),
|
||||
threadId: input.threadId,
|
||||
resumeCursor: {
|
||||
schemaVersion: GROK_RESUME_VERSION,
|
||||
sessionId: started.sessionId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const ctx: GrokSessionContext = {
|
||||
threadId: input.threadId,
|
||||
acpSessionId: started.sessionId,
|
||||
session,
|
||||
scope: sessionScope,
|
||||
acp,
|
||||
notificationFiber: undefined,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}),
|
||||
),
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to process Grok runtime notification.", { cause }),
|
||||
),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
ctx.notificationFiber = nf;
|
||||
sessions.set(input.threadId, ctx);
|
||||
sessionScopeTransferred = true;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: "Grok ACP session ready" },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
|
||||
return session;
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
const sendTurn: GrokAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* withThreadLock(
|
||||
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),
|
||||
});
|
||||
|
||||
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({
|
||||
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;
|
||||
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* 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,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const respondToRequest: GrokAdapterShape["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
});
|
||||
|
||||
const respondToUserInput: GrokAdapterShape["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingUserInputs.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/ask_user_question",
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.resolution, { _tag: "answered", answers });
|
||||
});
|
||||
|
||||
const readThread: GrokAdapterShape["readThread"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
|
||||
const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
}
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "thread/rollback",
|
||||
detail: "Grok ACP sessions do not support provider-side rollback yet.",
|
||||
});
|
||||
});
|
||||
|
||||
const stopSession: GrokAdapterShape["stopSession"] = (threadId) =>
|
||||
withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
}),
|
||||
);
|
||||
|
||||
const listSessions: GrokAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
|
||||
|
||||
const hasSession: GrokAdapterShape["hasSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
const c = sessions.get(threadId);
|
||||
return c !== undefined && !c.stopped;
|
||||
});
|
||||
|
||||
const stopAll: GrokAdapterShape["stopAll"] = () =>
|
||||
Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true });
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.ignore(stopAll()).pipe(
|
||||
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents,
|
||||
} satisfies GrokAdapterShape;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { GrokSettings } from "@t3tools/contracts";
|
||||
|
||||
import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus } from "./GrokProvider.ts";
|
||||
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
describe("buildInitialGrokProviderSnapshot", () => {
|
||||
it.effect("returns a disabled snapshot when settings.enabled is false", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* buildInitialGrokProviderSnapshot(
|
||||
decodeGrokSettings({ enabled: false }),
|
||||
);
|
||||
expect(snapshot.enabled).toBe(false);
|
||||
expect(snapshot.status).toBe("disabled");
|
||||
expect(snapshot.installed).toBe(false);
|
||||
expect(snapshot.message).toContain("disabled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a pending snapshot by default", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({}));
|
||||
expect(snapshot.enabled).toBe(true);
|
||||
expect(snapshot.installed).toBe(true);
|
||||
expect(snapshot.status).toBe("warning");
|
||||
expect(snapshot.version).toBeNull();
|
||||
expect(snapshot.message).toContain("Checking Grok");
|
||||
expect(snapshot.requiresNewThreadForModelChange).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
|
||||
it.effect("reports the binary as missing when the binary path does not resolve", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* checkGrokProviderStatus(
|
||||
decodeGrokSettings({
|
||||
enabled: true,
|
||||
binaryPath: "/definitely/not/installed/grok-binary",
|
||||
}),
|
||||
);
|
||||
expect(snapshot.enabled).toBe(true);
|
||||
expect(snapshot.installed).toBe(false);
|
||||
expect(snapshot.status).toBe("error");
|
||||
expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
|
||||
const grokPath = path.join(dir, "grok");
|
||||
yield* fs.writeFileString(
|
||||
grokPath,
|
||||
["#!/bin/sh", 'printf "%s\\n" "broken grok install" >&2', "exit 2", ""].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(grokPath, 0o755);
|
||||
|
||||
return yield* checkGrokProviderStatus(
|
||||
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
expect(snapshot.enabled).toBe(true);
|
||||
expect(snapshot.installed).toBe(true);
|
||||
expect(snapshot.status).toBe("error");
|
||||
expect(snapshot.message).toContain("broken grok install");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports an error when ACP model discovery is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-success-" });
|
||||
const grokPath = path.join(dir, "grok");
|
||||
yield* fs.writeFileString(
|
||||
grokPath,
|
||||
["#!/bin/sh", 'printf "grok-cli 0.0.99\\n"', "exit 0", ""].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(grokPath, 0o755);
|
||||
|
||||
return yield* checkGrokProviderStatus(
|
||||
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
expect(snapshot.status).toBe("error");
|
||||
expect(snapshot.installed).toBe(true);
|
||||
expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
|
||||
expect(snapshot.message).toContain("ACP startup failed");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
import {
|
||||
type GrokSettings,
|
||||
type ModelCapabilities,
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
detailFromResult,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
spawnAndCollect,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";
|
||||
|
||||
const GROK_PRESENTATION = {
|
||||
displayName: "Grok",
|
||||
badgeLabel: "Early Access",
|
||||
showInteractionModeToggle: false,
|
||||
requiresNewThreadForModelChange: true,
|
||||
} as const;
|
||||
const PROVIDER = ProviderDriverKind.make("grok");
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [],
|
||||
});
|
||||
|
||||
const VERSION_PROBE_TIMEOUT_MS = 4_000;
|
||||
const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
|
||||
const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
{
|
||||
slug: "grok-build",
|
||||
name: "Grok Build",
|
||||
isCustom: false,
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
},
|
||||
];
|
||||
|
||||
export function buildInitialGrokProviderSnapshot(
|
||||
grokSettings: GrokSettings,
|
||||
): Effect.Effect<ServerProviderDraft> {
|
||||
return Effect.gen(function* () {
|
||||
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const models = grokModelsFromSettings(grokSettings.customModels);
|
||||
|
||||
if (!grokSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Grok is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Checking Grok CLI availability...",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function grokModelsFromSettings(
|
||||
customModels: ReadonlyArray<string> | undefined,
|
||||
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
return providerModelsFromSettings(
|
||||
builtInModels,
|
||||
PROVIDER,
|
||||
customModels ?? [],
|
||||
EMPTY_CAPABILITIES,
|
||||
);
|
||||
}
|
||||
|
||||
function buildGrokDiscoveredModelsFromSessionModelState(
|
||||
modelState: EffectAcpSchema.SessionModelState | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (!modelState || modelState.availableModels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
return modelState.availableModels
|
||||
.map((model): ServerProviderModel | undefined => {
|
||||
const slug = resolveGrokAcpBaseModelId(model.modelId);
|
||||
if (!slug || seen.has(slug)) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(slug);
|
||||
return {
|
||||
slug,
|
||||
name: model.name.trim() || slug,
|
||||
isCustom: false,
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
};
|
||||
})
|
||||
.filter((model): model is ServerProviderModel => model !== undefined);
|
||||
}
|
||||
|
||||
const discoverGrokModelsViaAcp = (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const acp = yield* makeGrokAcpRuntime({
|
||||
grokSettings,
|
||||
environment,
|
||||
childProcessSpawner,
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
|
||||
});
|
||||
const started = yield* acp.start();
|
||||
return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const runGrokVersionCommand = (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) => {
|
||||
const command = grokSettings.binaryPath || "grok";
|
||||
return spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(command, ["--version"], {
|
||||
env: environment,
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
|
||||
|
||||
if (!grokSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Grok is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(
|
||||
Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionResult)) {
|
||||
const error = versionResult.failure;
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Grok CLI (`grok`) is not installed or not on PATH."
|
||||
: `Failed to execute Grok CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isNone(versionResult.success)) {
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: "Grok CLI is installed but timed out while running `grok --version`.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionOutput = versionResult.success.value;
|
||||
const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
|
||||
if (versionOutput.code !== 0) {
|
||||
const detail = detailFromResult(versionOutput);
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Grok CLI is installed but failed to run. ${detail}`
|
||||
: "Grok CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
|
||||
Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
|
||||
Effect.exit,
|
||||
);
|
||||
if (Exit.isFailure(discoveryExit)) {
|
||||
const detail = Cause.pretty(discoveryExit.cause);
|
||||
yield* Effect.logWarning("Grok ACP model discovery failed", { cause: detail });
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: `Grok CLI is installed but ACP startup failed. ${detail}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(discoveryExit.value)) {
|
||||
yield* Effect.logWarning(
|
||||
`Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
|
||||
);
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
const discoveredModels = discoveryExit.value.value;
|
||||
const models =
|
||||
discoveredModels.length > 0
|
||||
? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
|
||||
: fallbackModels;
|
||||
|
||||
return buildServerProvider({
|
||||
presentation: GROK_PRESENTATION,
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const enrichGrokSnapshot = (input: {
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void> => {
|
||||
const { snapshot, publishSnapshot } = input;
|
||||
|
||||
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Grok version advisory enrichment failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
};
|
||||
@@ -10,7 +10,7 @@
|
||||
*
|
||||
* 2. **Many drivers, one registry** — the "all drivers slice" describe
|
||||
* block below configures one instance of every shipped driver
|
||||
* (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single
|
||||
* (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
|
||||
* `ProviderInstanceConfigMap` and asserts the registry boots them all
|
||||
* without cross-contamination. This proves the driver SPI is uniform
|
||||
* across every provider — any driver plugs into the registry through
|
||||
@@ -18,7 +18,7 @@
|
||||
*
|
||||
* Every instance in these tests is configured with `enabled: false` so the
|
||||
* provider-status checks short-circuit to pending/disabled snapshots
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `opencode`
|
||||
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
|
||||
* binaries. That keeps the assertions focused on registry routing
|
||||
* behaviour rather than the runtime details of each provider.
|
||||
*/
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type ClaudeSettings,
|
||||
type CodexSettings,
|
||||
type CursorSettings,
|
||||
type GrokSettings,
|
||||
type OpenCodeSettings,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfigMap,
|
||||
@@ -41,6 +42,7 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
@@ -79,6 +81,13 @@ const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings =>
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "grok",
|
||||
customModels: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "opencode",
|
||||
@@ -218,7 +227,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
// All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
|
||||
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
|
||||
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
|
||||
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
|
||||
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
|
||||
@@ -244,11 +253,13 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const codexId = ProviderInstanceId.make("codex_default");
|
||||
const claudeId = ProviderInstanceId.make("claude_default");
|
||||
const cursorId = ProviderInstanceId.make("cursor_default");
|
||||
const grokId = ProviderInstanceId.make("grok_default");
|
||||
const openCodeId = ProviderInstanceId.make("opencode_default");
|
||||
|
||||
const codexDriverKind = ProviderDriverKind.make("codex");
|
||||
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
|
||||
const cursorDriverKind = ProviderDriverKind.make("cursor");
|
||||
const grokDriverKind = ProviderDriverKind.make("grok");
|
||||
const openCodeDriverKind = ProviderDriverKind.make("opencode");
|
||||
|
||||
const configMap: ProviderInstanceConfigMap = {
|
||||
@@ -273,6 +284,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
enabled: false,
|
||||
config: makeCursorConfig({}),
|
||||
},
|
||||
[grokId]: {
|
||||
driver: grokDriverKind,
|
||||
displayName: "Grok",
|
||||
enabled: false,
|
||||
config: makeGrokConfig({}),
|
||||
},
|
||||
[openCodeId]: {
|
||||
driver: openCodeDriverKind,
|
||||
displayName: "OpenCode",
|
||||
@@ -282,7 +299,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
};
|
||||
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
|
||||
configMap,
|
||||
});
|
||||
|
||||
@@ -292,9 +309,9 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(unavailable).toEqual([]);
|
||||
|
||||
const instances = yield* registry.listInstances;
|
||||
expect(instances).toHaveLength(4);
|
||||
expect(instances).toHaveLength(5);
|
||||
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
|
||||
[codexId, claudeId, cursorId, openCodeId].toSorted(),
|
||||
[codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
|
||||
);
|
||||
|
||||
// Instance lookup by id resolves each instance to its own bundle —
|
||||
@@ -303,14 +320,17 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
const codex = yield* registry.getInstance(codexId);
|
||||
const claude = yield* registry.getInstance(claudeId);
|
||||
const cursor = yield* registry.getInstance(cursorId);
|
||||
const grok = yield* registry.getInstance(grokId);
|
||||
const openCode = yield* registry.getInstance(openCodeId);
|
||||
expect(codex?.driverKind).toBe(codexDriverKind);
|
||||
expect(claude?.driverKind).toBe(claudeDriverKind);
|
||||
expect(cursor?.driverKind).toBe(cursorDriverKind);
|
||||
expect(grok?.driverKind).toBe(grokDriverKind);
|
||||
expect(openCode?.driverKind).toBe(openCodeDriverKind);
|
||||
expect(codex?.displayName).toBe("Codex");
|
||||
expect(claude?.displayName).toBe("Claude");
|
||||
expect(cursor?.displayName).toBe("Cursor");
|
||||
expect(grok?.displayName).toBe("Grok");
|
||||
expect(openCode?.displayName).toBe("OpenCode");
|
||||
|
||||
// Every instance owns its own set of closures — no sharing across
|
||||
@@ -318,16 +338,29 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
// distinct references even when two instances happen to share a
|
||||
// trait (e.g. Cursor + others all use a stub-or-real
|
||||
// `textGeneration`; they must still be different object values).
|
||||
const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];
|
||||
const adapters = [
|
||||
codex!.adapter,
|
||||
claude!.adapter,
|
||||
cursor!.adapter,
|
||||
grok!.adapter,
|
||||
openCode!.adapter,
|
||||
];
|
||||
expect(new Set(adapters).size).toBe(adapters.length);
|
||||
const textGenerations = [
|
||||
codex!.textGeneration,
|
||||
claude!.textGeneration,
|
||||
cursor!.textGeneration,
|
||||
grok!.textGeneration,
|
||||
openCode!.textGeneration,
|
||||
];
|
||||
expect(new Set(textGenerations).size).toBe(textGenerations.length);
|
||||
const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];
|
||||
const snapshots = [
|
||||
codex!.snapshot,
|
||||
claude!.snapshot,
|
||||
cursor!.snapshot,
|
||||
grok!.snapshot,
|
||||
openCode!.snapshot,
|
||||
];
|
||||
expect(new Set(snapshots).size).toBe(snapshots.length);
|
||||
|
||||
// Snapshots identify themselves by `instanceId` + `driver` so
|
||||
@@ -356,6 +389,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
`${cursorDriverKind}:instance:${cursorId}`,
|
||||
);
|
||||
|
||||
const grokSnapshot = yield* grok!.snapshot.getSnapshot;
|
||||
expect(grokSnapshot.instanceId).toBe(grokId);
|
||||
expect(grokSnapshot.driver).toBe(grokDriverKind);
|
||||
expect(grokSnapshot.enabled).toBe(false);
|
||||
expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
|
||||
|
||||
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
|
||||
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
|
||||
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
|
||||
|
||||
@@ -992,6 +992,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
codex: { enabled: false },
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
// `providerInstances` keys are branded `ProviderInstanceId`;
|
||||
@@ -1086,6 +1087,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
codex: { enabled: true, binaryPath: firstMissing },
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
}),
|
||||
@@ -1186,6 +1188,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
codex: { enabled: false },
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
grok: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
},
|
||||
providerInstances: {
|
||||
@@ -1245,6 +1248,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
cursor: {
|
||||
enabled: false,
|
||||
},
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1305,6 +1311,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
"claudeAgent",
|
||||
"codex",
|
||||
"cursor",
|
||||
"grok",
|
||||
"opencode",
|
||||
]);
|
||||
assert.strictEqual(cursorProvider?.enabled, false);
|
||||
@@ -1360,6 +1367,62 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
const fable5 = status.models.find((model) => model.slug === "claude-fable-5");
|
||||
assert.strictEqual(fable5?.name, "Claude Fable 5");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.169\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides Claude Fable 5 on older Claude Code versions", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(
|
||||
defaultClaudeSettings,
|
||||
claudeCapabilities(),
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.models.some((model) => model.slug === "claude-fable-5"),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code v2.1.168 is too old for Claude Fable 5. Upgrade to v2.1.169 or newer to access it.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "2.1.168\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
|
||||
() =>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* GrokAdapter — shape type for the Grok provider adapter.
|
||||
*
|
||||
* The driver model ({@link ../Drivers/GrokDriver}) bundles one adapter per
|
||||
* instance as a captured closure, so this module only retains the shape
|
||||
* interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module GrokAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* GrokAdapterShape — per-instance Grok adapter contract.
|
||||
*/
|
||||
export interface GrokAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -105,6 +105,9 @@ export interface AcpSessionRuntimeShape {
|
||||
value: string | boolean,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
|
||||
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly setSessionModel: (
|
||||
modelId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
|
||||
readonly request: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
@@ -546,6 +549,20 @@ const makeAcpSessionRuntime = (
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
setSessionModel: (modelId) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
modelId,
|
||||
} satisfies EffectAcpSchema.SetSessionModelRequest;
|
||||
return runLoggedRequest(
|
||||
"session/set_model",
|
||||
requestPayload,
|
||||
acp.agent.setSessionModel(requestPayload),
|
||||
);
|
||||
}),
|
||||
),
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Optional integration check against a real `grok agent stdio` install.
|
||||
* Enable with: T3_GROK_ACP_PROBE=1 bun run test GrokAcpCliProbe
|
||||
*
|
||||
* The probe assumes either `XAI_API_KEY` is set in the environment or
|
||||
* the user has previously run `grok login`. Without credentials the
|
||||
* agent's `authenticate` request will fail and the test will surface
|
||||
* the error.
|
||||
*/
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { makeGrokAcpRuntime } from "./GrokAcpSupport.ts";
|
||||
|
||||
const makeProbeRuntime = Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
return yield* makeGrokAcpRuntime({
|
||||
grokSettings: { binaryPath: "grok" },
|
||||
environment: process.env,
|
||||
childProcessSpawner,
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-grok-probe", version: "0.0.0" },
|
||||
});
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real grok agent stdio", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.initializeResult).toBeDefined();
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/new advertises typed SessionModelState with at least one model", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const result = started.sessionSetupResult;
|
||||
|
||||
expect(typeof started.sessionId).toBe("string");
|
||||
|
||||
// Modern grok-shell advertises models through the typed
|
||||
// `SessionModelState` field, not via a `configOptions` entry.
|
||||
// If this assertion fails the upstream surface has regressed.
|
||||
const models = result.models;
|
||||
expect(models).toBeDefined();
|
||||
expect(typeof models?.currentModelId).toBe("string");
|
||||
expect(models?.availableModels.length ?? 0).toBeGreaterThan(0);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/set_model accepts a no-op switch to the current model", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const currentModelId = started.sessionSetupResult.models?.currentModelId?.trim();
|
||||
expect(currentModelId).toBeDefined();
|
||||
if (!currentModelId) return;
|
||||
|
||||
// No-op switch — selecting the model the session already runs on must
|
||||
// succeed against every Grok build that implements `session/set_model`.
|
||||
yield* runtime.setSessionModel(currentModelId);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
buildGrokAcpSpawnInput,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "./GrokAcpSupport.ts";
|
||||
|
||||
describe("resolveGrokAcpBaseModelId", () => {
|
||||
it("normalizes empty and custom Grok model ids", () => {
|
||||
expect(resolveGrokAcpBaseModelId(undefined)).toBe("grok-build");
|
||||
expect(resolveGrokAcpBaseModelId(" ")).toBe("grok-build");
|
||||
expect(resolveGrokAcpBaseModelId(" grok-test-custom-model ")).toBe("grok-test-custom-model");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGrokAcpSpawnInput", () => {
|
||||
it("passes the T3 Code referrer through Grok OAuth env", () => {
|
||||
const spawn = buildGrokAcpSpawnInput({ binaryPath: "/usr/local/bin/grok" }, "/tmp/project", {
|
||||
XAI_API_KEY: "secret",
|
||||
GROK_OAUTH2_REFERRER: "other-client",
|
||||
});
|
||||
|
||||
expect(spawn).toEqual({
|
||||
command: "/usr/local/bin/grok",
|
||||
args: ["agent", "stdio"],
|
||||
cwd: "/tmp/project",
|
||||
env: {
|
||||
XAI_API_KEY: "secret",
|
||||
GROK_OAUTH2_REFERRER: "t3code",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyGrokAcpModelSelection", () => {
|
||||
const makeRecordingRuntime = (failure?: EffectAcpErrors.AcpError) => {
|
||||
const modelCalls: Array<string> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
Effect.gen(function* () {
|
||||
modelCalls.push(modelId);
|
||||
if (failure) return yield* failure;
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
return { runtime, modelCalls };
|
||||
};
|
||||
|
||||
it.effect("calls session/set_model when the requested model differs from current", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-build",
|
||||
requestedModelId: "grok-mock-alt",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual(["grok-mock-alt"]);
|
||||
expect(result).toBe("grok-mock-alt");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips set_model when requested matches current", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-build",
|
||||
requestedModelId: "grok-build",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([]);
|
||||
expect(result).toBe("grok-build");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips set_model when no model is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-build",
|
||||
requestedModelId: undefined,
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([]);
|
||||
expect(result).toBe("grok-build");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates session/set_model failures via mapError", () =>
|
||||
Effect.gen(function* () {
|
||||
const failure = EffectAcpErrors.AcpRequestError.invalidParams("session id not known");
|
||||
const { runtime } = makeRecordingRuntime(failure);
|
||||
const error = yield* Effect.flip(
|
||||
applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-build",
|
||||
requestedModelId: "grok-mock-alt",
|
||||
mapError: (cause) => cause.message,
|
||||
}),
|
||||
);
|
||||
expect(error).toBe(failure.message);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
type AcpSessionRuntimeOptions,
|
||||
type AcpSessionRuntimeShape,
|
||||
type AcpSpawnInput,
|
||||
} from "./AcpSessionRuntime.ts";
|
||||
|
||||
const GROK_API_KEY_ENV = "XAI_API_KEY";
|
||||
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
|
||||
const T3_CODE_OAUTH_REFERRER = "t3code";
|
||||
const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
|
||||
const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
|
||||
type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
|
||||
|
||||
interface GrokAcpRuntimeInput extends Omit<
|
||||
AcpSessionRuntimeOptions,
|
||||
"authMethodId" | "clientCapabilities" | "spawn"
|
||||
> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export function buildGrokAcpSpawnInput(
|
||||
grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): AcpSpawnInput {
|
||||
return {
|
||||
command: grokSettings?.binaryPath || "grok",
|
||||
args: ["agent", "stdio"],
|
||||
cwd,
|
||||
env: {
|
||||
...environment,
|
||||
[GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
|
||||
return environment?.[GROK_API_KEY_ENV]?.trim()
|
||||
? GROK_AUTH_METHOD_API_KEY
|
||||
: GROK_AUTH_METHOD_CACHED_TOKEN;
|
||||
}
|
||||
|
||||
export const makeGrokAcpRuntime = (
|
||||
input: GrokAcpRuntimeInput,
|
||||
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
|
||||
authMethodId: resolveGrokAuthMethodId(input.environment),
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
|
||||
});
|
||||
|
||||
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
|
||||
const trimmed = model?.trim();
|
||||
const base = trimmed && trimmed.length > 0 ? trimmed : "grok-build";
|
||||
return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";
|
||||
}
|
||||
|
||||
export function currentGrokModelIdFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): string | undefined {
|
||||
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
|
||||
}
|
||||
|
||||
export function applyGrokAcpModelSelection<E>(input: {
|
||||
readonly runtime: Pick<AcpSessionRuntimeShape, "setSessionModel">;
|
||||
readonly currentModelId: string | undefined;
|
||||
readonly requestedModelId: string | undefined;
|
||||
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
|
||||
}): Effect.Effect<string | undefined, E> {
|
||||
const shouldSwitchModel =
|
||||
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
|
||||
if (!shouldSwitchModel) {
|
||||
return Effect.succeed(input.currentModelId);
|
||||
}
|
||||
return input.runtime
|
||||
.setSessionModel(input.requestedModelId)
|
||||
.pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
describe("XAiAcpExtension", () => {
|
||||
it("extracts questions from the real xAI ask_user_question payload shape", () => {
|
||||
const questions = extractXAiAskUserQuestions({
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
question: "Which scope should Grok use?",
|
||||
options: [
|
||||
{ label: "Workspace", description: "Use the current workspace" },
|
||||
{ label: "Session", description: "Only use this session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "scope",
|
||||
header: "Question",
|
||||
question: "Which scope should Grok use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Workspace", description: "Use the current workspace" },
|
||||
{ label: "Session", description: "Only use this session" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("extracts questions from wrapped _x.ai extension payloads", () => {
|
||||
const payload = {
|
||||
method: "_x.ai/ask_user_question",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "plan",
|
||||
questions: [
|
||||
{
|
||||
question: "Which changes should be included?",
|
||||
multiSelect: true,
|
||||
options: [{ label: "Tests" }, { label: "Docs" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const decoded = decodeXAiAskUserQuestionRequest(payload);
|
||||
const questions = extractXAiAskUserQuestions(decoded);
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "Which changes should be included?",
|
||||
header: "Question",
|
||||
question: "Which changes should be included?",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{ label: "Tests", description: "Tests" },
|
||||
{ label: "Docs", description: "Docs" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats nullable multiSelect from Grok as single-select", () => {
|
||||
const questions = extractXAiAskUserQuestions({
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
question: "Which label should Grok use?",
|
||||
multiSelect: null,
|
||||
options: [
|
||||
{ label: "Alpha", description: "Use the Alpha label" },
|
||||
{ label: "Beta", description: "Use the Beta label" },
|
||||
{ label: "Other", description: "Use the Other label" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "Which label should Grok use?",
|
||||
header: "Question",
|
||||
question: "Which label should Grok use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Alpha", description: "Use the Alpha label" },
|
||||
{ label: "Beta", description: "Use the Beta label" },
|
||||
{ label: "Other", description: "Use the Other label" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps UI question ids back to xAI question text in accepted responses", () => {
|
||||
const response = makeXAiAskUserQuestionResponse(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
question: "Which scope should Grok use?",
|
||||
options: [
|
||||
{ label: "workspace", description: "Use the current workspace" },
|
||||
{ label: "session", description: "Only use this session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ scope: "workspace" },
|
||||
);
|
||||
|
||||
expect(response).toEqual({
|
||||
outcome: "accepted",
|
||||
answers: {
|
||||
"Which scope should Grok use?": ["workspace"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("orders accepted answers by the original xAI question order", () => {
|
||||
const response = makeXAiAskUserQuestionResponse(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
id: "first",
|
||||
question: "First question?",
|
||||
options: [{ label: "A", description: "A" }],
|
||||
},
|
||||
{
|
||||
id: "second",
|
||||
question: "Second question?",
|
||||
options: [{ label: "B", description: "B" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
second: "B",
|
||||
first: "A",
|
||||
},
|
||||
);
|
||||
|
||||
expect(Object.keys(response.answers)).toEqual(["First question?", "Second question?"]);
|
||||
expect(response).toMatchObject({
|
||||
outcome: "accepted",
|
||||
answers: {
|
||||
"First question?": ["A"],
|
||||
"Second question?": ["B"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("encodes typed custom answers as xAI Other annotations", () => {
|
||||
const response = makeXAiAskUserQuestionResponse(
|
||||
{
|
||||
method: "x.ai/ask_user_question",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
question: "Which ice cream flavor?",
|
||||
options: [
|
||||
{ label: "vanilla", description: "Vanilla flavor" },
|
||||
{ label: "chocolate", description: "Chocolate flavor" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{ "Which ice cream flavor?": "pistachio" },
|
||||
);
|
||||
|
||||
expect(response).toEqual({
|
||||
outcome: "accepted",
|
||||
answers: {
|
||||
"Which ice cream flavor?": ["Other"],
|
||||
},
|
||||
annotations: {
|
||||
"Which ice cream flavor?": {
|
||||
notes: "pistachio",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("encodes interrupted dialogs as xAI cancelled responses", () => {
|
||||
expect(makeXAiAskUserQuestionCancelledResponse()).toEqual({
|
||||
outcome: "cancelled",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not echo preview annotations for multi-select answers", () => {
|
||||
const response = makeXAiAskUserQuestionResponse(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
toolCallId: "tool-call-1",
|
||||
mode: "default",
|
||||
questions: [
|
||||
{
|
||||
question: "Which files should Grok touch?",
|
||||
multiSelect: true,
|
||||
options: [
|
||||
{
|
||||
label: "Tests",
|
||||
description: "Update tests",
|
||||
preview: "test preview",
|
||||
},
|
||||
{
|
||||
label: "Docs",
|
||||
description: "Update docs",
|
||||
preview: "docs preview",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ "Which files should Grok touch?": ["Tests", "Docs"] },
|
||||
);
|
||||
|
||||
expect(response).toEqual({
|
||||
outcome: "accepted",
|
||||
answers: {
|
||||
"Which files should Grok touch?": ["Tests", "Docs"],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
description: Schema.optional(Schema.String),
|
||||
preview: Schema.optional(Schema.String),
|
||||
id: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
const XAiAskUserQuestion = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
question: Schema.String,
|
||||
options: Schema.Array(XAiAskUserQuestionOption),
|
||||
multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
});
|
||||
|
||||
const XAiAskUserQuestionParams = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
toolCallId: Schema.String,
|
||||
questions: Schema.Array(XAiAskUserQuestion),
|
||||
mode: Schema.Literals(["default", "plan"]),
|
||||
});
|
||||
|
||||
const XAiWrappedAskUserQuestionParams = Schema.Struct({
|
||||
method: Schema.Literals(["x.ai/ask_user_question", "_x.ai/ask_user_question"]),
|
||||
params: XAiAskUserQuestionParams,
|
||||
});
|
||||
|
||||
export const XAiAskUserQuestionRequest = Schema.Union([
|
||||
XAiAskUserQuestionParams,
|
||||
XAiWrappedAskUserQuestionParams,
|
||||
]);
|
||||
|
||||
type XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type;
|
||||
type XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type;
|
||||
|
||||
function trimmed(value: string | undefined): string | undefined {
|
||||
const text = value?.trim();
|
||||
return text && text.length > 0 ? text : undefined;
|
||||
}
|
||||
|
||||
function unwrapAskUserQuestionParams(
|
||||
params: XAiAskUserQuestionRequest,
|
||||
): XAiAskUserQuestionRequestParams {
|
||||
return "params" in params ? params.params : params;
|
||||
}
|
||||
|
||||
export function extractXAiAskUserQuestions(
|
||||
params: XAiAskUserQuestionRequest,
|
||||
): ReadonlyArray<UserInputQuestion> {
|
||||
return unwrapAskUserQuestionParams(params).questions.map((question) => ({
|
||||
id: question.id ?? question.question,
|
||||
header: "Question",
|
||||
question: question.question,
|
||||
multiSelect: question.multiSelect === true,
|
||||
options:
|
||||
question.options.length > 0
|
||||
? question.options.map((option) => ({
|
||||
label: option.label,
|
||||
description: option.description ?? option.label,
|
||||
}))
|
||||
: [{ label: "OK", description: "Continue" }],
|
||||
}));
|
||||
}
|
||||
|
||||
interface XAiAskUserQuestionAnnotation {
|
||||
readonly preview?: string;
|
||||
readonly notes?: string;
|
||||
}
|
||||
|
||||
interface XAiAskUserQuestionAcceptedResponse {
|
||||
readonly outcome: "accepted";
|
||||
readonly answers: Record<string, ReadonlyArray<string>>;
|
||||
readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>;
|
||||
}
|
||||
|
||||
interface XAiAskUserQuestionCancelledResponse {
|
||||
readonly outcome: "cancelled";
|
||||
}
|
||||
|
||||
export type XAiAskUserQuestionResponse =
|
||||
| XAiAskUserQuestionAcceptedResponse
|
||||
| XAiAskUserQuestionCancelledResponse;
|
||||
|
||||
interface NormalizedXAiAnswer {
|
||||
readonly questionText: string;
|
||||
readonly selectedLabels: ReadonlyArray<string>;
|
||||
readonly annotation?: XAiAskUserQuestionAnnotation;
|
||||
}
|
||||
|
||||
function answerValues(answer: unknown): ReadonlyArray<string> {
|
||||
if (Array.isArray(answer)) {
|
||||
return answer.flatMap((entry) => {
|
||||
const text = typeof entry === "string" ? trimmed(entry) : undefined;
|
||||
return text ? [text] : [];
|
||||
});
|
||||
}
|
||||
const text = typeof answer === "string" ? trimmed(answer) : undefined;
|
||||
return text ? [text] : [];
|
||||
}
|
||||
|
||||
function normalizeAnswerForXAi(
|
||||
question: XAiAskUserQuestionRequestParams["questions"][number],
|
||||
answer: unknown,
|
||||
): NormalizedXAiAnswer | undefined {
|
||||
const values = answerValues(answer);
|
||||
if (values.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
|
||||
const resolvedValues = values.map((value) => ({
|
||||
value,
|
||||
option: optionByLabel.get(value),
|
||||
}));
|
||||
const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : []));
|
||||
const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value]));
|
||||
const preview =
|
||||
question.multiSelect === true
|
||||
? undefined
|
||||
: resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value);
|
||||
|
||||
const annotation =
|
||||
preview || notes.length > 0
|
||||
? {
|
||||
...(preview ? { preview } : {}),
|
||||
...(notes.length > 0 ? { notes: notes.join("\n") } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
questionText: question.question,
|
||||
selectedLabels: selectedLabels.length > 0 ? selectedLabels : ["Other"],
|
||||
...(annotation ? { annotation } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function findQuestionAnswer(
|
||||
answers: ProviderUserInputAnswers,
|
||||
question: XAiAskUserQuestionRequestParams["questions"][number],
|
||||
): unknown {
|
||||
const key = question.id ?? question.question;
|
||||
return answers[key] ?? answers[question.question];
|
||||
}
|
||||
|
||||
export function makeXAiAskUserQuestionResponse(
|
||||
params: XAiAskUserQuestionRequest,
|
||||
answers: ProviderUserInputAnswers,
|
||||
): XAiAskUserQuestionAcceptedResponse {
|
||||
const questions = unwrapAskUserQuestionParams(params).questions;
|
||||
const normalized = questions.flatMap((question) => {
|
||||
const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question));
|
||||
return entry ? [entry] : [];
|
||||
});
|
||||
const annotations = Object.fromEntries(
|
||||
normalized.flatMap((entry) =>
|
||||
entry.annotation ? [[entry.questionText, entry.annotation] as const] : [],
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
outcome: "accepted",
|
||||
answers: Object.fromEntries(
|
||||
normalized.map((entry) => [entry.questionText, entry.selectedLabels]),
|
||||
),
|
||||
...(Object.keys(annotations).length > 0 ? { annotations } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
|
||||
return { outcome: "cancelled" };
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
|
||||
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
|
||||
@@ -35,6 +36,7 @@ export type BuiltInDriversEnv =
|
||||
| ClaudeDriverEnv
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| GrokDriverEnv
|
||||
| OpenCodeDriverEnv;
|
||||
|
||||
/**
|
||||
@@ -46,5 +48,6 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
CodexDriver,
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
GrokDriver,
|
||||
OpenCodeDriver,
|
||||
];
|
||||
@@ -45,6 +45,7 @@ export interface ServerProviderPresentation {
|
||||
readonly displayName: string;
|
||||
readonly badgeLabel?: string;
|
||||
readonly showInteractionModeToggle?: boolean;
|
||||
readonly requiresNewThreadForModelChange?: boolean;
|
||||
}
|
||||
|
||||
export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
|
||||
@@ -214,6 +215,9 @@ export function buildServerProvider(input: {
|
||||
...(typeof input.presentation.showInteractionModeToggle === "boolean"
|
||||
? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
|
||||
: {}),
|
||||
...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
|
||||
? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
|
||||
: {}),
|
||||
enabled: input.enabled,
|
||||
installed: input.probe.installed,
|
||||
version: input.probe.version,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export const makeProviderRegistryMock = (
|
||||
providers: ReadonlyArray<ServerProvider> = [],
|
||||
): ProviderRegistryShape => ({
|
||||
getProviders: Effect.succeed(providers),
|
||||
refresh: () => Effect.succeed(providers),
|
||||
refreshInstance: () => Effect.succeed(providers),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null })),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed(providers),
|
||||
streamChanges: Stream.empty,
|
||||
});
|
||||
|
||||
export const makeProviderRegistryLayer = (providers: ReadonlyArray<ServerProvider> = []) =>
|
||||
Layer.succeed(ProviderRegistry, makeProviderRegistryMock(providers));
|
||||
@@ -303,7 +303,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!relayConfig) {
|
||||
yield* Effect.logDebug("agent activity publish skipped; T3 Cloud config missing", {
|
||||
yield* Effect.logDebug("agent activity publish skipped; T3 Connect config missing", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
@@ -421,7 +421,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!relayConfig) {
|
||||
yield* Effect.logDebug("agent activity snapshot skipped; T3 Cloud config missing");
|
||||
yield* Effect.logDebug("agent activity snapshot skipped; T3 Connect config missing");
|
||||
return false;
|
||||
}
|
||||
const environmentId = yield* serverEnvironment.getEnvironmentId;
|
||||
@@ -459,7 +459,7 @@ const make = Effect.gen(function* () {
|
||||
function* () {
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!relayConfig) {
|
||||
yield* Effect.logInfo("agent activity publishing standby; T3 Cloud config missing");
|
||||
yield* Effect.logInfo("agent activity publishing standby; T3 Connect config missing");
|
||||
} else {
|
||||
yield* Effect.logInfo("agent activity publishing enabled", {
|
||||
relayUrl: relayConfig.url,
|
||||
|
||||
@@ -782,7 +782,7 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({
|
||||
get: Effect.die(new Error("Unexpected T3 Cloud CLI authorization request.")),
|
||||
get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")),
|
||||
getExisting: Effect.succeed(Option.none()),
|
||||
hasCredential: Effect.succeed(false),
|
||||
clear: Effect.void,
|
||||
@@ -1713,7 +1713,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -1750,7 +1750,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const serverPort = Number(new URL(linkProofUrl).port);
|
||||
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
|
||||
method: "POST",
|
||||
@@ -1762,10 +1762,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
challenge: "relay-link-challenge",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
endpoint: {
|
||||
httpBaseUrl: linkProofUrl.replace("/api/cloud/link-proof", ""),
|
||||
httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""),
|
||||
wsBaseUrl: linkProofUrl
|
||||
.replace("http://", "ws://")
|
||||
.replace("/api/cloud/link-proof", "/ws"),
|
||||
.replace("/api/connect/link-proof", "/ws"),
|
||||
providerKind: "manual",
|
||||
},
|
||||
origin: {
|
||||
@@ -1789,9 +1789,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const serverPort = Number(new URL(linkProofUrl).port);
|
||||
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
|
||||
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
|
||||
headers: {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
@@ -1833,9 +1833,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const serverPort = Number(new URL(linkProofUrl).port);
|
||||
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
|
||||
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
|
||||
headers: {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
@@ -1875,9 +1875,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const serverPort = Number(new URL(linkProofUrl).port);
|
||||
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
|
||||
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
|
||||
headers: {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
@@ -1918,7 +1918,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const serverPort = Number(new URL(linkProofUrl).port);
|
||||
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
|
||||
method: "POST",
|
||||
@@ -1962,7 +1962,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
const credential = (yield* credentialResponse.json) as { readonly credential: string };
|
||||
const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential);
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
|
||||
const response = yield* fetchEffect(linkStateUrl, {
|
||||
headers: { cookie: pairedCookie },
|
||||
});
|
||||
@@ -2028,7 +2028,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const preferencesUrl = yield* getHttpServerUrl("/api/cloud/preferences");
|
||||
const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences");
|
||||
const ownerResponse = yield* fetchEffect(preferencesUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2072,7 +2072,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2107,7 +2107,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const postRelayConfig = (body: {
|
||||
readonly relayUrl: string;
|
||||
readonly relayIssuer?: string;
|
||||
@@ -2184,7 +2184,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const postRelayConfig = (cloudUserId: string, environmentCredential: string) =>
|
||||
fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
@@ -2227,8 +2227,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
|
||||
const initialResponse = yield* fetchEffect(linkStateUrl, {
|
||||
headers: {
|
||||
@@ -2284,7 +2284,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const reconcileUrl = yield* getHttpServerUrl("/api/cloud/reconcile");
|
||||
const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile");
|
||||
const response = yield* fetchEffect(reconcileUrl, {
|
||||
method: "POST",
|
||||
});
|
||||
@@ -2321,9 +2321,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const unlinkUrl = yield* getHttpServerUrl("/api/cloud/unlink");
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink");
|
||||
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
|
||||
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
@@ -2398,7 +2398,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2424,7 +2424,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
issuedAt: DateTime.formatIso(now),
|
||||
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
|
||||
});
|
||||
const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");
|
||||
const postMint = () =>
|
||||
fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
@@ -2448,7 +2448,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("serves the documented T3 Cloud mint credential endpoint", () =>
|
||||
it.effect("serves the documented T3 Connect mint credential endpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
@@ -2457,7 +2457,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2484,7 +2484,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
issuedAt: DateTime.formatIso(now),
|
||||
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
|
||||
});
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
|
||||
const response = yield* fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2507,7 +2507,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("serves signed T3 Cloud environment health checks", () =>
|
||||
it.effect("serves signed T3 Connect environment health checks", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
@@ -2516,7 +2516,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2542,7 +2542,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
issuedAt: DateTime.formatIso(now),
|
||||
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
|
||||
});
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const response = yield* fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2576,7 +2576,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2602,7 +2602,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
issuedAt: DateTime.formatIso(now),
|
||||
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
|
||||
});
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const postHealth = () =>
|
||||
fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
@@ -2637,7 +2637,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2656,7 +2656,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
|
||||
const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>
|
||||
fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
@@ -2717,7 +2717,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2756,7 +2756,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
issuedAt: DateTime.formatIso(now),
|
||||
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
|
||||
});
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const healthResponse = yield* fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2786,7 +2786,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2804,7 +2804,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");
|
||||
const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>
|
||||
fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
@@ -2853,7 +2853,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2871,7 +2871,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
|
||||
const response = yield* fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2904,7 +2904,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2922,7 +2922,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
|
||||
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
|
||||
const response = yield* fetchEffect(mintUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2955,7 +2955,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -2973,7 +2973,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const postHealth = (request: ReturnType<typeof makeCloudEnvironmentHealthRequest>) =>
|
||||
fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
@@ -3020,7 +3020,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -3038,7 +3038,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const response = yield* fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -3070,7 +3070,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
|
||||
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
|
||||
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -3088,7 +3088,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(relayConfigResponse.status, 200);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
|
||||
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
|
||||
const response = yield* fetchEffect(healthUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -3280,7 +3280,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
config: { devUrl: new URL(crossOriginClientOrigin) },
|
||||
});
|
||||
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
|
||||
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
|
||||
const response = yield* fetchEffect(linkProofUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
|
||||
@@ -69,7 +69,7 @@ import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts
|
||||
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { cloudHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
|
||||
import { connectHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
|
||||
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
|
||||
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
|
||||
import * as CloudCliState from "./cloud/CliState.ts";
|
||||
@@ -321,7 +321,7 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
|
||||
export const makeRoutesLayer = Layer.mergeAll(
|
||||
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
|
||||
Layer.provide(authHttpApiLayer),
|
||||
Layer.provide(cloudHttpApiLayer),
|
||||
Layer.provide(connectHttpApiLayer),
|
||||
Layer.provide(orchestrationHttpApiLayer),
|
||||
Layer.provide(serverEnvironmentHttpApiLayer),
|
||||
Layer.provide(environmentAuthenticatedAuthLayer),
|
||||
@@ -429,9 +429,9 @@ export const makeServerLayer = Layer.unwrap(
|
||||
Effect.sleep("250 millis").pipe(
|
||||
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
|
||||
Effect.retry({ times: 4 }),
|
||||
Effect.tap(() => Effect.logInfo("T3 Cloud desired link reconciled on startup")),
|
||||
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to reconcile T3 Cloud desired link on startup", {
|
||||
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
isProviderDriverKind,
|
||||
type ModelSelection,
|
||||
@@ -207,6 +208,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
instanceId: ProviderInstanceId.make(fallback),
|
||||
model:
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
} satisfies ModelSelection,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vite-plus/test";
|
||||
import { GrokSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { makeGrokTextGeneration } from "./GrokTextGeneration.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
const GrokTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-grok-text-generation-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
function makeAcpGrokWrapper(dir: string, env: Record<string, string>): string {
|
||||
const binDir = path.join(dir, "bin");
|
||||
const grokPath = path.join(binDir, "grok");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
writeFileSync(
|
||||
grokPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||
'if [ "$1" != "agent" ] || [ "$2" != "stdio" ]; then',
|
||||
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||
" exit 11",
|
||||
"fi",
|
||||
`exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
chmodSync(grokPath, 0o755);
|
||||
return grokPath;
|
||||
}
|
||||
|
||||
function withFakeAcpGrok<A, E, R>(
|
||||
env: Record<string, string>,
|
||||
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-grok-text-acp-"));
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
const binaryPath = makeAcpGrokWrapper(tempDir, env);
|
||||
const config = decodeGrokSettings({ binaryPath });
|
||||
const textGeneration = yield* makeGrokTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
|
||||
function readJsonRpcRequests(
|
||||
filePath: string,
|
||||
): ReadonlyArray<{ readonly method?: string; readonly params?: Record<string, unknown> }> {
|
||||
return readFileSync(filePath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
|
||||
}
|
||||
|
||||
it.layer(GrokTextGenerationTestLayer)("GrokTextGeneration", (it) => {
|
||||
it.effect("uses ACP with disabled tool capabilities and forwards the requested model id", () => {
|
||||
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-grok-text-log-"));
|
||||
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
|
||||
|
||||
return withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Add Grok provider",
|
||||
body: "Wire up the ACP runtime and headless text generation path.",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/grok",
|
||||
stagedSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
|
||||
stagedPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add Grok provider");
|
||||
expect(generated.body).toBe("Wire up the ACP runtime and headless text generation path.");
|
||||
|
||||
const requests = readJsonRpcRequests(requestLogPath);
|
||||
expect(
|
||||
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||
).toMatchObject({
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_model" &&
|
||||
request.params?.modelId === "grok-mock-alt",
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("extracts the JSON object when Grok wraps it in conversational text", () =>
|
||||
withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||
"Sure! Here's a thread title:\n\n" +
|
||||
JSON.stringify({ title: "Investigate failing CI" }) +
|
||||
"\n\nLet me know if you need anything else.",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "the lint job is red",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
|
||||
});
|
||||
expect(generated.title).toBe("Investigate failing CI");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("surfaces ACP request failures as text generation errors", () =>
|
||||
withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "unreachable" }),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "wire up grok",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("grok"),
|
||||
"missing-grok-model",
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("TextGenerationError");
|
||||
expect(error.detail).toContain("Grok ACP base model");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails with TextGenerationError when output is empty", () =>
|
||||
withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: " \n ",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "anything",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("TextGenerationError");
|
||||
expect(error.detail).toMatch(/empty/i);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("decodes a structured PR title + body", () =>
|
||||
withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
title: "feat(grok): wire up session/set_model",
|
||||
body: "## Summary\n- Replace `-m` spawn flag with the typed ACP `session/set_model`.\n- Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT` into a validation error.",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feat/grok-provider",
|
||||
commitSummary: "feat: add grok provider",
|
||||
diffSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
|
||||
diffPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("feat(grok): wire up session/set_model");
|
||||
expect(generated.body).toContain("Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT`");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails with TextGenerationError when output is unparseable JSON", () =>
|
||||
withFakeAcpGrok(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "anything",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("TextGenerationError");
|
||||
expect(error.detail).toMatch(/invalid structured output/i);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { type GrokSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { extractJsonObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../provider/acp/GrokAcpSupport.ts";
|
||||
|
||||
const GROK_TIMEOUT_MS = 180_000;
|
||||
|
||||
function mapGrokAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): TextGenerationError {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isTextGenerationError(error: unknown): error is TextGenerationError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "TextGenerationError"
|
||||
);
|
||||
}
|
||||
|
||||
export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const runGrokJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const resolvedModel = resolveGrokAcpBaseModelId(modelSelection.model);
|
||||
const outputRef = yield* Ref.make("");
|
||||
const runtime = yield* makeGrokAcpRuntime({
|
||||
grokSettings,
|
||||
environment,
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
});
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "agent_message_chunk") {
|
||||
return Effect.void;
|
||||
}
|
||||
const content = update.content;
|
||||
if (content.type !== "text") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.update(outputRef, (current) => current + content.text);
|
||||
});
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
const started = yield* runtime.start();
|
||||
yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
requestedModelId: resolvedModel,
|
||||
mapError: (cause) =>
|
||||
mapGrokAcpError(
|
||||
operation,
|
||||
"Failed to set Grok ACP base model for text generation.",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: prompt }],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeoutOption(GROK_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Grok ACP request timed out." }),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapGrokAcpError(operation, "Grok ACP request failed.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const trimmed = (yield* Ref.get(outputRef)).trim();
|
||||
if (!trimmed) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
promptResult.stopReason === "cancelled"
|
||||
? "Grok ACP request was cancelled."
|
||||
: "Grok Agent returned empty output.",
|
||||
});
|
||||
}
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Grok Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapGrokAcpError(operation, "Grok ACP text generation failed.", cause),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"GrokTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"GrokTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"GrokTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"GrokTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
|
||||
@@ -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
@@ -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>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.24",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -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"
|
||||
|
||||
@@ -184,7 +184,7 @@ export function writeBrowserSavedEnvironmentSecret(
|
||||
return record;
|
||||
}
|
||||
found = true;
|
||||
const nextRecord = {
|
||||
const nextRecord: BrowserSavedEnvironmentRecord = {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
|
||||
@@ -514,7 +514,7 @@ describe("web cloud link environment client", () => {
|
||||
expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include");
|
||||
|
||||
expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
|
||||
"http://127.0.0.1:3000/api/cloud/link-proof",
|
||||
"http://127.0.0.1:3000/api/connect/link-proof",
|
||||
);
|
||||
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
|
||||
method: "POST",
|
||||
@@ -553,7 +553,7 @@ describe("web cloud link environment client", () => {
|
||||
});
|
||||
|
||||
expect(String(fetchMock.mock.calls[3]?.[0])).toBe(
|
||||
"http://127.0.0.1:3000/api/cloud/relay-config",
|
||||
"http://127.0.0.1:3000/api/connect/relay-config",
|
||||
);
|
||||
expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({
|
||||
method: "POST",
|
||||
@@ -615,7 +615,7 @@ describe("web cloud link environment client", () => {
|
||||
publishAgentActivity: false,
|
||||
});
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
|
||||
"http://127.0.0.1:3000/api/cloud/link-state",
|
||||
"http://127.0.0.1:3000/api/connect/link-state",
|
||||
);
|
||||
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
|
||||
method: "GET",
|
||||
@@ -654,7 +654,7 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
|
||||
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
@@ -698,7 +698,7 @@ describe("web cloud link environment client", () => {
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
|
||||
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
|
||||
@@ -451,7 +451,7 @@ export function readPrimaryCloudLinkState(): Effect.Effect<
|
||||
return null;
|
||||
}
|
||||
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
|
||||
return yield* client.cloud
|
||||
return yield* client.connect
|
||||
.linkState({ headers: {} })
|
||||
.pipe(
|
||||
withPrimaryEnvironmentRequestInit,
|
||||
@@ -465,7 +465,7 @@ export function updatePrimaryCloudPreferences(input: {
|
||||
}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
|
||||
return Effect.gen(function* () {
|
||||
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
|
||||
return yield* client.cloud
|
||||
return yield* client.connect
|
||||
.preferences({
|
||||
headers: {},
|
||||
payload: input,
|
||||
@@ -488,7 +488,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
|
||||
});
|
||||
}
|
||||
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
|
||||
yield* client.cloud
|
||||
yield* client.connect
|
||||
.unlink({ headers: {} })
|
||||
.pipe(
|
||||
withPrimaryEnvironmentRequestInit,
|
||||
@@ -568,7 +568,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
),
|
||||
),
|
||||
);
|
||||
const proof = yield* environmentClient.cloud
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers,
|
||||
payload: {
|
||||
@@ -604,7 +604,7 @@ export function linkEnvironmentToCloud(input: {
|
||||
link,
|
||||
});
|
||||
|
||||
yield* environmentClient.cloud
|
||||
yield* environmentClient.connect
|
||||
.relayConfig({
|
||||
headers,
|
||||
payload: {
|
||||
@@ -656,7 +656,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
),
|
||||
),
|
||||
);
|
||||
const proof = yield* environmentClient.cloud
|
||||
const proof = yield* environmentClient.connect
|
||||
.linkProof({
|
||||
headers: {},
|
||||
payload: {
|
||||
@@ -695,7 +695,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
|
||||
link,
|
||||
});
|
||||
|
||||
yield* environmentClient.cloud
|
||||
yield* environmentClient.connect
|
||||
.relayConfig({
|
||||
headers: {},
|
||||
payload: {
|
||||
|
||||
@@ -55,7 +55,7 @@ export function usePrimaryCloudLinkState() {
|
||||
let error: string | null = null;
|
||||
if (result._tag === "Failure") {
|
||||
const cause = Cause.squash(result.cause);
|
||||
error = cause instanceof Error ? cause.message : "Could not read T3 Cloud link state.";
|
||||
error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -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 "{trimmedBranchQuery}"</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();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
@@ -280,17 +666,15 @@ interface MarkdownFileLinkProps {
|
||||
href: string;
|
||||
targetPath: 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 +751,196 @@ 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,
|
||||
displayPath,
|
||||
filePath,
|
||||
label,
|
||||
copyMarkdown,
|
||||
theme,
|
||||
className,
|
||||
}: MarkdownFileLinkProps) {
|
||||
@@ -467,7 +1035,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 +1044,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={targetPath} label={label} theme={theme} selectable />
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
@@ -505,8 +1068,8 @@ function areMarkdownFileLinkPropsEqual(
|
||||
previous.href === next.href &&
|
||||
previous.targetPath === next.targetPath &&
|
||||
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 +1080,8 @@ function ChatMarkdown({
|
||||
cwd,
|
||||
isStreaming = false,
|
||||
skills = EMPTY_MARKDOWN_SKILLS,
|
||||
className,
|
||||
lineBreaks = false,
|
||||
}: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
@@ -542,6 +1107,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 +1126,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);
|
||||
@@ -573,21 +1187,34 @@ function ChatMarkdown({
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
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 +1240,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}
|
||||
>
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveSendEnvMode,
|
||||
@@ -90,6 +91,73 @@ describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStartedThreadModelChangeBlockReason", () => {
|
||||
const providers = [
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
},
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
requiresNewThreadForModelChange: true,
|
||||
},
|
||||
];
|
||||
|
||||
it("allows model changes before a provider session has started", () => {
|
||||
expect(
|
||||
getStartedThreadModelChangeBlockReason({
|
||||
providers,
|
||||
hasStartedSession: false,
|
||||
currentModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-build",
|
||||
},
|
||||
nextModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-other",
|
||||
},
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("allows unchanged model selections for restricted providers", () => {
|
||||
expect(
|
||||
getStartedThreadModelChangeBlockReason({
|
||||
providers,
|
||||
hasStartedSession: true,
|
||||
currentModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-build",
|
||||
},
|
||||
nextModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-build",
|
||||
},
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("blocks started-session model changes when either provider requires a new thread", () => {
|
||||
expect(
|
||||
getStartedThreadModelChangeBlockReason({
|
||||
providers,
|
||||
hasStartedSession: true,
|
||||
currentModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
nextModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-build",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Start a new chat to change models",
|
||||
description:
|
||||
"This provider does not allow switching models after a conversation has started.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSendEnvMode", () => {
|
||||
it("keeps worktree mode for git repositories", () => {
|
||||
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ProjectId,
|
||||
type ModelSelection,
|
||||
type ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
@@ -262,6 +263,44 @@ export function deriveLockedProvider(input: {
|
||||
return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
|
||||
}
|
||||
|
||||
export function getStartedThreadModelChangeBlockReason(input: {
|
||||
providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
|
||||
hasStartedSession: boolean;
|
||||
currentModelSelection: ModelSelection;
|
||||
currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
|
||||
nextModelSelection: ModelSelection;
|
||||
}): { title: string; description: string } | null {
|
||||
if (!input.hasStartedSession) {
|
||||
return null;
|
||||
}
|
||||
const currentModelSelection = {
|
||||
...input.currentModelSelection,
|
||||
instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
|
||||
};
|
||||
if (
|
||||
currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
|
||||
currentModelSelection.model === input.nextModelSelection.model
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const currentProvider = input.providers.find(
|
||||
(snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
|
||||
);
|
||||
const nextProvider = input.providers.find(
|
||||
(snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
|
||||
);
|
||||
if (
|
||||
currentProvider?.requiresNewThreadForModelChange !== true &&
|
||||
nextProvider?.requiresNewThreadForModelChange !== true
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
title: "Start a new chat to change models",
|
||||
description: "This provider does not allow switching models after a conversation has started.",
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForStartedServerThread(
|
||||
threadRef: ScopedThreadRef,
|
||||
timeoutMs = 1_000,
|
||||
|
||||
@@ -163,6 +163,7 @@ import {
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
type LocalDispatchSnapshot,
|
||||
@@ -202,6 +203,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;
|
||||
@@ -209,131 +239,137 @@ type EnvironmentUnavailableState = {
|
||||
};
|
||||
|
||||
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
|
||||
type ThreadPlanCatalogStoreState = ReturnType<typeof useStore.getState>;
|
||||
|
||||
interface ThreadPlanCatalogCacheEntry {
|
||||
shell: object | null;
|
||||
proposedPlanIds: readonly string[] | undefined;
|
||||
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
|
||||
entry: ThreadPlanCatalogEntry;
|
||||
function eventTargetElement(target: EventTarget | null): Element | null {
|
||||
if (target instanceof Element) return target;
|
||||
if (target instanceof Node) return target.parentElement;
|
||||
return null;
|
||||
}
|
||||
|
||||
function createThreadPlanCatalogSelector(threadIds: readonly ThreadId[]) {
|
||||
let previousThreadIds: readonly ThreadId[] = [];
|
||||
let previousResult: ThreadPlanCatalogEntry[] = [];
|
||||
let previousEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
|
||||
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;
|
||||
|
||||
return (state: ThreadPlanCatalogStoreState): ThreadPlanCatalogEntry[] => {
|
||||
const sameThreadIds =
|
||||
previousThreadIds.length === threadIds.length &&
|
||||
previousThreadIds.every((id, index) => id === threadIds[index]);
|
||||
const nextEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
|
||||
const nextResult: ThreadPlanCatalogEntry[] = [];
|
||||
let changed = !sameThreadIds;
|
||||
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;
|
||||
|
||||
for (const threadId of threadIds) {
|
||||
let shell: object | undefined;
|
||||
let proposedPlanIds: readonly string[] | undefined;
|
||||
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
|
||||
|
||||
for (const environmentState of Object.values(state.environmentStateById)) {
|
||||
const matchedShell = environmentState.threadShellById[threadId];
|
||||
if (!matchedShell) {
|
||||
continue;
|
||||
}
|
||||
shell = matchedShell;
|
||||
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
|
||||
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
|
||||
| Record<string, Thread["proposedPlans"][number]>
|
||||
| undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!shell) {
|
||||
const previous = previousEntries.get(threadId);
|
||||
if (
|
||||
previous &&
|
||||
previous.shell === null &&
|
||||
previous.proposedPlanIds === undefined &&
|
||||
previous.proposedPlansById === undefined
|
||||
) {
|
||||
nextEntries.set(threadId, previous);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
nextEntries.set(threadId, {
|
||||
shell: null,
|
||||
proposedPlanIds: undefined,
|
||||
proposedPlansById: undefined,
|
||||
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = previousEntries.get(threadId);
|
||||
if (
|
||||
previous &&
|
||||
previous.shell === shell &&
|
||||
previous.proposedPlanIds === proposedPlanIds &&
|
||||
previous.proposedPlansById === proposedPlansById
|
||||
) {
|
||||
nextEntries.set(threadId, previous);
|
||||
nextResult.push(previous.entry);
|
||||
continue;
|
||||
}
|
||||
|
||||
changed = true;
|
||||
const proposedPlans =
|
||||
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
|
||||
? proposedPlanIds.flatMap((planId) => {
|
||||
const proposedPlan = proposedPlansById?.[planId];
|
||||
return proposedPlan ? [proposedPlan] : [];
|
||||
})
|
||||
: EMPTY_PROPOSED_PLANS;
|
||||
const entry = { id: threadId, proposedPlans };
|
||||
nextEntries.set(threadId, {
|
||||
shell,
|
||||
proposedPlanIds,
|
||||
proposedPlansById,
|
||||
entry,
|
||||
});
|
||||
nextResult.push(entry);
|
||||
}
|
||||
|
||||
if (!changed && previousResult.length === nextResult.length) {
|
||||
return previousResult;
|
||||
}
|
||||
|
||||
previousThreadIds = threadIds;
|
||||
previousEntries = nextEntries;
|
||||
previousResult = nextResult;
|
||||
return nextResult;
|
||||
};
|
||||
}
|
||||
|
||||
function deriveThreadPlanCatalogThreadIds(input: {
|
||||
activeThreadId: ThreadId | null;
|
||||
sourceProposedPlanThreadId: ThreadId | null;
|
||||
}): readonly ThreadId[] {
|
||||
const threadIds: ThreadId[] = [];
|
||||
if (input.activeThreadId) {
|
||||
threadIds.push(input.activeThreadId);
|
||||
}
|
||||
if (
|
||||
input.sourceProposedPlanThreadId &&
|
||||
input.sourceProposedPlanThreadId !== input.activeThreadId
|
||||
) {
|
||||
threadIds.push(input.sourceProposedPlanThreadId);
|
||||
}
|
||||
return threadIds;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
|
||||
const selectThreadPlanCatalog = useMemo(
|
||||
() => createThreadPlanCatalogSelector(threadIds),
|
||||
[threadIds],
|
||||
return useStore(
|
||||
useMemo(() => {
|
||||
let previousThreadIds: readonly ThreadId[] = [];
|
||||
let previousResult: ThreadPlanCatalogEntry[] = [];
|
||||
let previousEntries = new Map<
|
||||
ThreadId,
|
||||
{
|
||||
shell: object | null;
|
||||
proposedPlanIds: readonly string[] | undefined;
|
||||
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
|
||||
entry: ThreadPlanCatalogEntry;
|
||||
}
|
||||
>();
|
||||
|
||||
return (state) => {
|
||||
const sameThreadIds =
|
||||
previousThreadIds.length === threadIds.length &&
|
||||
previousThreadIds.every((id, index) => id === threadIds[index]);
|
||||
const nextEntries = new Map<
|
||||
ThreadId,
|
||||
{
|
||||
shell: object | null;
|
||||
proposedPlanIds: readonly string[] | undefined;
|
||||
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
|
||||
entry: ThreadPlanCatalogEntry;
|
||||
}
|
||||
>();
|
||||
const nextResult: ThreadPlanCatalogEntry[] = [];
|
||||
let changed = !sameThreadIds;
|
||||
|
||||
for (const threadId of threadIds) {
|
||||
let shell: object | undefined;
|
||||
let proposedPlanIds: readonly string[] | undefined;
|
||||
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
|
||||
|
||||
for (const environmentState of Object.values(state.environmentStateById)) {
|
||||
const matchedShell = environmentState.threadShellById[threadId];
|
||||
if (!matchedShell) {
|
||||
continue;
|
||||
}
|
||||
shell = matchedShell;
|
||||
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
|
||||
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
|
||||
| Record<string, Thread["proposedPlans"][number]>
|
||||
| undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!shell) {
|
||||
const previous = previousEntries.get(threadId);
|
||||
if (
|
||||
previous &&
|
||||
previous.shell === null &&
|
||||
previous.proposedPlanIds === undefined &&
|
||||
previous.proposedPlansById === undefined
|
||||
) {
|
||||
nextEntries.set(threadId, previous);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
nextEntries.set(threadId, {
|
||||
shell: null,
|
||||
proposedPlanIds: undefined,
|
||||
proposedPlansById: undefined,
|
||||
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = previousEntries.get(threadId);
|
||||
if (
|
||||
previous &&
|
||||
previous.shell === shell &&
|
||||
previous.proposedPlanIds === proposedPlanIds &&
|
||||
previous.proposedPlansById === proposedPlansById
|
||||
) {
|
||||
nextEntries.set(threadId, previous);
|
||||
nextResult.push(previous.entry);
|
||||
continue;
|
||||
}
|
||||
|
||||
changed = true;
|
||||
const proposedPlans =
|
||||
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
|
||||
? proposedPlanIds.flatMap((planId) => {
|
||||
const proposedPlan = proposedPlansById?.[planId];
|
||||
return proposedPlan ? [proposedPlan] : [];
|
||||
})
|
||||
: EMPTY_PROPOSED_PLANS;
|
||||
const entry = { id: threadId, proposedPlans };
|
||||
nextEntries.set(threadId, {
|
||||
shell,
|
||||
proposedPlanIds,
|
||||
proposedPlansById,
|
||||
entry,
|
||||
});
|
||||
nextResult.push(entry);
|
||||
}
|
||||
|
||||
if (!changed && previousResult.length === nextResult.length) {
|
||||
return previousResult;
|
||||
}
|
||||
|
||||
previousThreadIds = threadIds;
|
||||
previousEntries = nextEntries;
|
||||
previousResult = nextResult;
|
||||
return nextResult;
|
||||
};
|
||||
}, [threadIds]),
|
||||
);
|
||||
return useStore(selectThreadPlanCatalog);
|
||||
}
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
@@ -1041,16 +1077,19 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
|
||||
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const sourceProposedPlanThreadId = activeLatestTurn?.sourceProposedPlan?.threadId ?? null;
|
||||
const threadPlanCatalogThreadIds = useMemo(
|
||||
() =>
|
||||
deriveThreadPlanCatalogThreadIds({
|
||||
activeThreadId,
|
||||
sourceProposedPlanThreadId,
|
||||
}),
|
||||
[activeThreadId, sourceProposedPlanThreadId],
|
||||
const threadPlanCatalog = useThreadPlanCatalog(
|
||||
useMemo(() => {
|
||||
const threadIds: ThreadId[] = [];
|
||||
if (activeThread?.id) {
|
||||
threadIds.push(activeThread.id);
|
||||
}
|
||||
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
|
||||
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
|
||||
threadIds.push(sourceThreadId);
|
||||
}
|
||||
return threadIds;
|
||||
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
|
||||
);
|
||||
const threadPlanCatalog = useThreadPlanCatalog(threadPlanCatalogThreadIds);
|
||||
useEffect(() => {
|
||||
setMountedTerminalThreadKeys((currentThreadIds) => {
|
||||
const nextThreadIds = reconcileMountedTerminalThreadIds({
|
||||
@@ -1852,7 +1891,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 ??
|
||||
@@ -1994,15 +2037,18 @@ export default function ChatView(props: ChatViewProps) {
|
||||
|
||||
const focusComposer = useCallback(() => {
|
||||
composerRef.current?.focusAtEnd();
|
||||
}, []);
|
||||
}, [composerRef]);
|
||||
const scheduleComposerFocus = useCallback(() => {
|
||||
window.requestAnimationFrame(() => {
|
||||
focusComposer();
|
||||
});
|
||||
}, [focusComposer]);
|
||||
const addTerminalContextToDraft = useCallback((selection: TerminalContextSelection) => {
|
||||
composerRef.current?.addTerminalContext(selection);
|
||||
}, []);
|
||||
const addTerminalContextToDraft = useCallback(
|
||||
(selection: TerminalContextSelection) => {
|
||||
composerRef.current?.addTerminalContext(selection);
|
||||
},
|
||||
[composerRef],
|
||||
);
|
||||
const setTerminalOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (!activeThreadRef) return;
|
||||
@@ -2704,6 +2750,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,
|
||||
});
|
||||
@@ -2781,6 +2839,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
keybindings,
|
||||
onToggleDiff,
|
||||
toggleTerminalVisibility,
|
||||
composerRef,
|
||||
]);
|
||||
|
||||
const onRevertToTurnCount = useCallback(
|
||||
@@ -3255,7 +3314,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
promptRef.current = "";
|
||||
composerRef.current?.resetCursorState({ cursor: 0 });
|
||||
},
|
||||
[activePendingProgress?.activeQuestion, activePendingUserInput],
|
||||
[activePendingProgress?.activeQuestion, activePendingUserInput, composerRef],
|
||||
);
|
||||
|
||||
const onChangeActivePendingUserInputCustomAnswer = useCallback(
|
||||
@@ -3289,7 +3348,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
composerRef.current?.focusAt(nextCursor);
|
||||
}
|
||||
},
|
||||
[activePendingUserInput],
|
||||
[activePendingUserInput, composerRef],
|
||||
);
|
||||
|
||||
const onAdvanceActivePendingUserInput = useCallback(() => {
|
||||
@@ -3461,6 +3520,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
setThreadError,
|
||||
autoOpenPlanSidebar,
|
||||
environmentId,
|
||||
composerRef,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3598,8 +3658,26 @@ export default function ChatView(props: ChatViewProps) {
|
||||
runtimeMode,
|
||||
autoOpenPlanSidebar,
|
||||
environmentId,
|
||||
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;
|
||||
@@ -3643,6 +3721,22 @@ export default function ChatView(props: ChatViewProps) {
|
||||
instanceId,
|
||||
model: resolvedModel,
|
||||
};
|
||||
const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({
|
||||
providers: providerStatuses,
|
||||
hasStartedSession: activeThread.session !== null,
|
||||
currentModelSelection: activeThread.modelSelection,
|
||||
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
|
||||
nextModelSelection,
|
||||
});
|
||||
if (modelChangeBlockReason) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: modelChangeBlockReason.title,
|
||||
description: modelChangeBlockReason.description,
|
||||
});
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
setComposerDraftModelSelection(
|
||||
scopeThreadRef(activeThread.environmentId, activeThread.id),
|
||||
nextModelSelection,
|
||||
@@ -3902,6 +3996,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);
|
||||
},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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";
|
||||
@@ -460,35 +461,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">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{summary.turnId}</TooltipPopup>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -512,30 +519,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 +636,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,
|
||||
|
||||
@@ -199,6 +199,18 @@ export const CursorIcon: Icon = ({ className, ...props }) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const GrokIcon: Icon = ({ className, ...props }) => (
|
||||
<svg
|
||||
{...props}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
className={cn("fill-[#0F0F0F] dark:fill-[#F5F5F5]", className)}
|
||||
>
|
||||
<path d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
|
||||
<path d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const TraeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
|
||||
|
||||
@@ -158,6 +158,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
launchArgs: "",
|
||||
},
|
||||
cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },
|
||||
grok: { enabled: true, binaryPath: "", customModels: [] },
|
||||
opencode: {
|
||||
enabled: true,
|
||||
binaryPath: "",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -92,12 +92,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>
|
||||
<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>
|
||||
{activeProjectName && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
@@ -128,6 +143,59 @@ describe("MessagesTimeline", () => {
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.not.toBeInTheDocument();
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses accessible tooltips instead of native titles 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();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain(
|
||||
"git diff -- apps/web/src/components/ChatMarkdown.tsx --stat",
|
||||
);
|
||||
});
|
||||
|
||||
const fileTrigger = page.getByLabelText("repo/apps/web/src/components/ChatMarkdown.tsx", {
|
||||
exact: true,
|
||||
});
|
||||
await fileTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("apps/web/src/components/ChatMarkdown.tsx");
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
@@ -261,4 +329,61 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -188,7 +188,8 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
expect(markup).toContain("yoo what's</p>");
|
||||
expect(markup).toContain('<span aria-hidden="true"> </span>');
|
||||
expect(markup).toContain("Show full message");
|
||||
}, 20_000);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
Fragment,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@@ -19,7 +20,6 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import {
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
@@ -43,8 +43,7 @@ import {
|
||||
import { Button } from "../ui/button";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { ChangedFilesCard } from "./ChangedFilesTree";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
@@ -380,6 +379,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
skills={ctx.skills}
|
||||
markdownCwd={ctx.markdownCwd}
|
||||
footer={
|
||||
<>
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
@@ -404,16 +404,23 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
title="Revert to this message"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
aria-label="Revert to this message"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Revert to this message</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -699,50 +706,18 @@ function AssistantChangedFilesSectionInner({
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const changedFileCountLabel = String(checkpointFiles.length);
|
||||
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="sticky top-2 z-10 mb-1.5 flex items-center justify-between gap-2 bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:absolute before:inset-x-0 before:-top-2 before:h-2 before:bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:content-['']">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
<ChangedFilesCard
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onToggleAllDirectories={() =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
|
||||
}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -781,6 +756,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
markdownCwd: string | undefined;
|
||||
footer?: ReactNode;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
@@ -810,6 +786,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
|
||||
text={props.text}
|
||||
terminalContexts={props.terminalContexts}
|
||||
skills={props.skills}
|
||||
markdownCwd={props.markdownCwd}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -847,7 +824,34 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
markdownCwd: string | undefined;
|
||||
}) {
|
||||
const renderInlineMarkdownSegment = (text: string, key: string) => {
|
||||
const leadingWhitespace = /^\s+/.exec(text)?.[0] ?? "";
|
||||
const textWithoutLeadingWhitespace = text.slice(leadingWhitespace.length);
|
||||
const trailingWhitespace = /\s+$/.exec(textWithoutLeadingWhitespace)?.[0] ?? "";
|
||||
const content = textWithoutLeadingWhitespace.slice(
|
||||
0,
|
||||
textWithoutLeadingWhitespace.length - trailingWhitespace.length,
|
||||
);
|
||||
|
||||
return (
|
||||
<Fragment key={key}>
|
||||
{leadingWhitespace ? <span aria-hidden="true">{leadingWhitespace}</span> : null}
|
||||
{content ? (
|
||||
<ChatMarkdown
|
||||
text={content}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
) : null}
|
||||
{trailingWhitespace ? <span aria-hidden="true">{trailingWhitespace}</span> : null}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
|
||||
if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) {
|
||||
return (
|
||||
@@ -855,8 +859,14 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
{reviewCommentSegments.map((segment) =>
|
||||
segment.kind === "text" ? (
|
||||
segment.text.trim().length > 0 ? (
|
||||
<div key={segment.id} className="whitespace-pre-wrap wrap-break-word">
|
||||
<SkillInlineText text={segment.text.trim()} skills={props.skills} />
|
||||
<div key={segment.id} className="wrap-break-word">
|
||||
<ChatMarkdown
|
||||
text={segment.text.trim()}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
</div>
|
||||
) : null
|
||||
) : (
|
||||
@@ -887,9 +897,10 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
}
|
||||
if (matchIndex > cursor) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
|
||||
<SkillInlineText text={props.text.slice(cursor, matchIndex)} skills={props.skills} />
|
||||
</span>,
|
||||
renderInlineMarkdownSegment(
|
||||
props.text.slice(cursor, matchIndex),
|
||||
`user-terminal-context-inline-before:${context.header}:${cursor}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
inlineNodes.push(
|
||||
@@ -904,9 +915,10 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
if (inlineNodes.length > 0) {
|
||||
if (cursor < props.text.length) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-message-terminal-context-inline-rest:${cursor}`}>
|
||||
<SkillInlineText text={props.text.slice(cursor)} skills={props.skills} />
|
||||
</span>,
|
||||
renderInlineMarkdownSegment(
|
||||
props.text.slice(cursor),
|
||||
`user-message-terminal-context-inline-rest:${cursor}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -934,9 +946,14 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
|
||||
if (props.text.length > 0) {
|
||||
inlineNodes.push(
|
||||
<span key="user-message-terminal-context-inline-text">
|
||||
<SkillInlineText text={props.text} skills={props.skills} />
|
||||
</span>,
|
||||
<ChatMarkdown
|
||||
key="user-message-terminal-context-inline-text"
|
||||
text={props.text}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>,
|
||||
);
|
||||
} else if (inlinePrefix.length === 0) {
|
||||
return null;
|
||||
@@ -954,9 +971,13 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
|
||||
<SkillInlineText text={props.text} skills={props.skills} />
|
||||
</div>
|
||||
<ChatMarkdown
|
||||
text={props.text}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1203,49 +1224,40 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
{rawCommand ? (
|
||||
<div className="max-w-full">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-xs leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
title={displayText}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
closeDelay={0}
|
||||
delay={75}
|
||||
render={
|
||||
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
|
||||
{" "}
|
||||
- {preview}
|
||||
</span>
|
||||
}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
closeDelay={0}
|
||||
delay={75}
|
||||
render={
|
||||
<p
|
||||
className={cn(
|
||||
"truncate rounded-sm text-xs leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
aria-label={displayText}
|
||||
/>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</p>
|
||||
}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
className="block min-w-0 w-full text-left"
|
||||
title={displayText}
|
||||
aria-label={displayText}
|
||||
>
|
||||
<TooltipTrigger className="block min-w-0 w-full text-left" aria-label={displayText}>
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-[11px] leading-5",
|
||||
@@ -1273,13 +1285,21 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
{workEntry.changedFiles?.slice(0, 4).map((filePath) => {
|
||||
const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
|
||||
return (
|
||||
<span
|
||||
key={`${workEntry.id}:${filePath}`}
|
||||
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
|
||||
title={displayPath}
|
||||
>
|
||||
{displayPath}
|
||||
</span>
|
||||
<Tooltip key={`${workEntry.id}:${filePath}`}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
|
||||
aria-label={displayPath}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{displayPath}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="max-w-[min(40rem,calc(100vw-2rem))]">
|
||||
<span className="font-mono text-[11px] whitespace-nowrap">{displayPath}</span>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
{(workEntry.changedFiles?.length ?? 0) > 4 && (
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { ClaudeAI, CursorIcon, GrokIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { PROVIDER_OPTIONS } from "../../session-logic";
|
||||
|
||||
export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {
|
||||
@@ -7,6 +7,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
|
||||
[ProviderDriverKind.make("claudeAgent")]: ClaudeAI,
|
||||
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
|
||||
[ProviderDriverKind.make("cursor")]: CursorIcon,
|
||||
[ProviderDriverKind.make("grok")]: GrokIcon,
|
||||
};
|
||||
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
@@ -27,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 {
|
||||
@@ -42,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);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { UserButton, useAuth } from "@clerk/react";
|
||||
import { LogInIcon } from "lucide-react";
|
||||
|
||||
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
|
||||
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
|
||||
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
|
||||
|
||||
export function T3ConnectSidebarSignIn() {
|
||||
if (!hasCloudPublicConfig()) return null;
|
||||
|
||||
return <ConfiguredT3ConnectSidebarSignIn />;
|
||||
}
|
||||
|
||||
export function T3ConnectSidebarAvatar() {
|
||||
if (!hasCloudPublicConfig()) return null;
|
||||
|
||||
return <ConfiguredT3ConnectSidebarAvatar />;
|
||||
}
|
||||
|
||||
function ConfiguredT3ConnectSidebarAvatar() {
|
||||
const { isLoaded, isSignedIn } = useAuth();
|
||||
|
||||
if (!isLoaded || !isSignedIn) return null;
|
||||
|
||||
return (
|
||||
<UserButton
|
||||
appearance={{
|
||||
elements: {
|
||||
avatarBox: "size-7",
|
||||
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-accent",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredT3ConnectSidebarSignIn() {
|
||||
const { isLoaded, isSignedIn } = useAuth();
|
||||
const { authPrompt, openAuthPrompt } = useT3ConnectAuthPrompt();
|
||||
|
||||
if (!isLoaded || isSignedIn) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
onClick={openAuthPrompt}
|
||||
>
|
||||
<LogInIcon className="size-4" />
|
||||
<span>Sign in to T3 Connect</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
{authPrompt}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user