Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f65e38f3d1 | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e | ||
|
|
0e4a43519f |
No files matched your search
+7
-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.
|
||||
|
||||
@@ -10,3 +10,8 @@
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
@@ -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",
|
||||
|
||||
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed<string | null>(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -44,6 +44,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
continue;
|
||||
}
|
||||
|
||||
// Header items are decorative section labels for the web fallback only —
|
||||
// Electron's native menu has no equivalent affordance, so we skip them.
|
||||
if (sourceItem.header === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedItem: ContextMenuItem = {
|
||||
id: sourceItem.id,
|
||||
label: sourceItem.label,
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -161,6 +161,11 @@ const config: ExpoConfig = {
|
||||
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
|
||||
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
|
||||
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
|
||||
},
|
||||
eas: {
|
||||
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useAuth, useUser, useUserProfileModal } from "@clerk/expo";
|
||||
import { useAuth, useUser } from "@clerk/expo";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { Link, Stack, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
@@ -68,7 +68,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const { push } = useRouter();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
|
||||
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
|
||||
@@ -266,15 +265,11 @@ function ConfiguredSettingsRouteScreen() {
|
||||
push("/settings/waitlist");
|
||||
return;
|
||||
}
|
||||
if (isUserProfileModalAvailable) {
|
||||
void presentUserProfile();
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"T3 Cloud unavailable",
|
||||
"Native T3 Cloud account management is not available in this build.",
|
||||
);
|
||||
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]);
|
||||
}, [isLoaded, isSignedIn, push]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
|
||||
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
|
||||
}
|
||||
|
||||
function readRelayConfig(): { readonly url: string } | null {
|
||||
const relayUrl = resolveCloudPublicConfig().relayUrl;
|
||||
const relayUrl = resolveCloudPublicConfig().relay.url;
|
||||
if (!relayUrl) {
|
||||
logRegistrationDebug("relay registration skipped; relay config missing");
|
||||
return null;
|
||||
|
||||
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
|
||||
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
|
||||
const config = resolveCloudPublicConfig();
|
||||
const publishableKey = config.clerk.publishableKey;
|
||||
const relayUrl = config.relay.url;
|
||||
|
||||
useEffect(() => {
|
||||
if (!publishableKey || !relayUrl) {
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
|
||||
}
|
||||
|
||||
function readRelayUrl(): string | null {
|
||||
return resolveCloudPublicConfig().relayUrl;
|
||||
return resolveCloudPublicConfig().relay.url;
|
||||
}
|
||||
|
||||
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
|
||||
@@ -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: {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
createManagedRelayQueryManager,
|
||||
ManagedRelayClient,
|
||||
managedRelaySessionAtom,
|
||||
readManagedRelaySnapshotState,
|
||||
} from "@t3tools/client-runtime";
|
||||
@@ -9,23 +8,13 @@ import type {
|
||||
RelayClientEnvironmentRecord,
|
||||
RelayEnvironmentStatusResponse,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { mobileRuntime } from "../../lib/runtime";
|
||||
import { mobileRuntimeContextLayer } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
|
||||
const managedRelayAtomRuntime = Atom.runtime(
|
||||
Layer.effect(
|
||||
ManagedRelayClient,
|
||||
mobileRuntime.contextEffect.pipe(
|
||||
Effect.map((context) => Context.get(context, ManagedRelayClient)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
|
||||
|
||||
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveCloudPublicConfig } from "./publicConfig";
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
|
||||
describe("resolveCloudPublicConfig", () => {
|
||||
it("returns no cloud configuration for an unconfigured build", () => {
|
||||
expect(resolveCloudPublicConfig({})).toEqual({
|
||||
clerkPublishableKey: null,
|
||||
clerkJwtTemplate: null,
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: null,
|
||||
jwtTemplate: null,
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,11 +33,25 @@ describe("resolveCloudPublicConfig", () => {
|
||||
resolveCloudPublicConfig({
|
||||
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
|
||||
relay: { url: " https://relay.example.test/// " },
|
||||
observability: {
|
||||
tracesUrl: " https://api.axiom.co/v1/traces ",
|
||||
tracesDataset: " mobile-traces ",
|
||||
tracesToken: " public-ingest-token ",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: "https://relay.example.test",
|
||||
clerk: {
|
||||
publishableKey: "pk_test_example",
|
||||
jwtTemplate: "t3-relay",
|
||||
},
|
||||
relay: {
|
||||
url: "https://relay.example.test",
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
|
||||
relay: { url: "http://relay.example.test" },
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: null,
|
||||
clerk: {
|
||||
publishableKey: "pk_test_example",
|
||||
jwtTemplate: "t3-relay",
|
||||
},
|
||||
relay: {
|
||||
url: null,
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: null,
|
||||
tracesDataset: null,
|
||||
tracesToken: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an insecure traces URL", () => {
|
||||
expect(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "http://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
}).observability,
|
||||
).toEqual({
|
||||
tracesUrl: null,
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps tracing disabled unless every public tracing value is configured", () => {
|
||||
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
|
||||
expect(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
hasMobileTracingPublicConfig(
|
||||
resolveCloudPublicConfig({
|
||||
observability: {
|
||||
tracesUrl: "https://api.axiom.co/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -2,40 +2,92 @@ import Constants from "expo-constants";
|
||||
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
|
||||
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
|
||||
|
||||
export interface CloudPublicConfig {
|
||||
readonly clerkPublishableKey: string | null;
|
||||
readonly clerkJwtTemplate: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
readonly clerk: {
|
||||
readonly publishableKey: string | null;
|
||||
readonly jwtTemplate: string | null;
|
||||
};
|
||||
readonly relay: {
|
||||
readonly url: string | null;
|
||||
};
|
||||
readonly observability: {
|
||||
readonly tracesUrl: string | null;
|
||||
readonly tracesDataset: string | null;
|
||||
readonly tracesToken: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
type UntrustedSection<T> = {
|
||||
readonly [Key in keyof T]?: unknown;
|
||||
};
|
||||
|
||||
type ExpoExtra =
|
||||
| {
|
||||
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
function trimNonEmpty(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
|
||||
const clerk = extra?.clerk as
|
||||
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
|
||||
| undefined;
|
||||
const relay = extra?.relay as { readonly url?: unknown } | undefined;
|
||||
function normalizeSecureUrl(value: unknown): string | null {
|
||||
const raw = trimNonEmpty(value);
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return url.protocol === "https:" ? url.toString() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
|
||||
return {
|
||||
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
|
||||
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
|
||||
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
|
||||
clerk: {
|
||||
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
|
||||
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
|
||||
},
|
||||
relay: {
|
||||
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
|
||||
},
|
||||
observability: {
|
||||
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
|
||||
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
|
||||
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
|
||||
},
|
||||
} satisfies CloudPublicConfig;
|
||||
}
|
||||
|
||||
export function hasCloudPublicConfig(): boolean {
|
||||
const config = resolveCloudPublicConfig();
|
||||
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
|
||||
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
|
||||
}
|
||||
|
||||
type Configured<T> = {
|
||||
readonly [Key in keyof T]: NonNullable<T[Key]>;
|
||||
};
|
||||
|
||||
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
|
||||
readonly observability: Configured<CloudPublicConfig["observability"]>;
|
||||
};
|
||||
|
||||
export function hasMobileTracingPublicConfig(
|
||||
config: CloudPublicConfig = resolveCloudPublicConfig(),
|
||||
): config is MobileTracingPublicConfig {
|
||||
return Boolean(
|
||||
config.observability.tracesUrl &&
|
||||
config.observability.tracesDataset &&
|
||||
config.observability.tracesToken,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveRelayClerkTokenOptions() {
|
||||
const { clerkJwtTemplate } = resolveCloudPublicConfig();
|
||||
if (!clerkJwtTemplate) {
|
||||
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
|
||||
if (!jwtTemplate) {
|
||||
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
|
||||
}
|
||||
return relayClerkTokenOptions(clerkJwtTemplate);
|
||||
return relayClerkTokenOptions(jwtTemplate);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
|
||||
import { makeMobileTracingLayer } from "./mobileTracing";
|
||||
|
||||
vi.mock("expo-constants", () => ({
|
||||
default: {
|
||||
expoConfig: {
|
||||
extra: {},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
it.effect("exports spans through the scoped mobile OTLP layer", () => {
|
||||
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
|
||||
const tracingLayer = makeMobileTracingLayer(
|
||||
{
|
||||
tracesUrl: "https://api.axiom.test/v1/traces",
|
||||
tracesDataset: "mobile-traces",
|
||||
tracesToken: "public-ingest-token",
|
||||
},
|
||||
{
|
||||
appVariant: "test",
|
||||
serviceVersion: "1.2.3",
|
||||
},
|
||||
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
|
||||
const tracedApplication = Layer.effectDiscard(
|
||||
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
|
||||
).pipe(Layer.provide(tracingLayer));
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* Layer.build(tracedApplication);
|
||||
|
||||
expect(fetchFn).not.toHaveBeenCalled();
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
expect(fetchFn).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchFn.mock.calls[0]!;
|
||||
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
|
||||
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
|
||||
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
|
||||
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import Constants from "expo-constants";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type { HttpClient } from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
|
||||
|
||||
export interface MobileTracingConfig {
|
||||
readonly tracesUrl: string;
|
||||
readonly tracesDataset: string;
|
||||
readonly tracesToken: string;
|
||||
}
|
||||
|
||||
export interface MobileTracingResource {
|
||||
readonly serviceVersion?: string;
|
||||
readonly appVariant: string;
|
||||
}
|
||||
|
||||
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
|
||||
const config = resolveCloudPublicConfig();
|
||||
if (!hasMobileTracingPublicConfig(config)) {
|
||||
return null;
|
||||
}
|
||||
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
|
||||
return { tracesUrl, tracesDataset, tracesToken };
|
||||
}
|
||||
|
||||
export function makeMobileTracingLayer(
|
||||
config: MobileTracingConfig | null,
|
||||
resource: MobileTracingResource,
|
||||
): Layer.Layer<never, never, HttpClient.HttpClient> {
|
||||
if (config === null) {
|
||||
return Layer.empty;
|
||||
}
|
||||
|
||||
return OtlpTracer.layer({
|
||||
url: config.tracesUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.tracesToken}`,
|
||||
"X-Axiom-Dataset": config.tracesDataset,
|
||||
},
|
||||
resource: {
|
||||
serviceName: "t3-mobile",
|
||||
serviceVersion: resource.serviceVersion,
|
||||
attributes: {
|
||||
"service.runtime": "react-native",
|
||||
"service.component": "mobile",
|
||||
"deployment.environment.name": resource.appVariant,
|
||||
},
|
||||
},
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
}
|
||||
|
||||
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
|
||||
serviceVersion: Constants.expoConfig?.version,
|
||||
appVariant:
|
||||
typeof Constants.expoConfig?.extra?.appVariant === "string"
|
||||
? Constants.expoConfig.extra.appVariant
|
||||
: "unknown",
|
||||
});
|
||||
@@ -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") {
|
||||
|
||||
@@ -6,19 +6,20 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
|
||||
import { mobileCryptoLayer } from "../features/cloud/dpop";
|
||||
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
|
||||
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
|
||||
import { mobileTracingLayer } from "../features/observability/mobileTracing";
|
||||
|
||||
function configuredRelayUrl(): string {
|
||||
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
|
||||
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
|
||||
}
|
||||
|
||||
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
|
||||
|
||||
export const mobileRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
mobileHttpClientLayer,
|
||||
mobileCryptoLayer,
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
|
||||
),
|
||||
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
|
||||
Layer.provideMerge(mobileCryptoLayer),
|
||||
Layer.provideMerge(mobileHttpClientLayer),
|
||||
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
|
||||
@@ -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",
|
||||
@@ -22,7 +22,7 @@
|
||||
"test": "vp test run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
|
||||
@@ -18,9 +18,16 @@ 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 promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
|
||||
const permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
|
||||
};
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
@@ -237,6 +244,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 +279,7 @@ const program = Effect.gen(function* () {
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
@@ -273,11 +296,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) {
|
||||
@@ -325,6 +365,10 @@ const program = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -419,9 +463,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 +562,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
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
|
||||
|
||||
it("returns the selected Codex service tier id", () => {
|
||||
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
|
||||
{ id: "serviceTier", value: "flex" },
|
||||
]);
|
||||
|
||||
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
|
||||
});
|
||||
|
||||
it("keeps legacy persisted fast mode selections working", () => {
|
||||
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
||||
{ id: "fastMode", value: true },
|
||||
]);
|
||||
|
||||
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ModelSelection } from "@t3tools/contracts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
export function getCodexServiceTierOptionValue(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): string | undefined {
|
||||
return (
|
||||
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
|
||||
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
|
||||
);
|
||||
}
|
||||
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
);
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetails(cwd)
|
||||
.statusDetailsRemote(cwd)
|
||||
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
|
||||
if (details === null || !details.isRepo) {
|
||||
return null;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
|
||||
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -18,6 +19,7 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
|
||||
httpHeaderRedactionLayer,
|
||||
);
|
||||
|
||||
const tracerLayer = Layer.unwrap(
|
||||
|
||||
@@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-turn-lifecycle");
|
||||
const turnId = TurnId.make("turn-lifecycle-1");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-tl1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-tl1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-turn-lifecycle"),
|
||||
title: "Turn lifecycle",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claude"),
|
||||
model: "claude-opus",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-tl2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:00:01.000Z",
|
||||
commandId: CommandId.make("cmd-tl2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Interim assistant message completes mid-turn (commentary between
|
||||
// tool calls) — the turn must stay running and unsettled.
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-tl3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:00:05.000Z",
|
||||
commandId: CommandId.make("cmd-tl3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-tl-interim"),
|
||||
role: "assistant",
|
||||
text: "interim commentary",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:05.000Z",
|
||||
updatedAt: "2026-01-01T00:00:05.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const runningRows = yield* sql<{
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
|
||||
`;
|
||||
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
|
||||
|
||||
// The session leaving "running" is the turn-end signal.
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-tl4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:01:00.000Z",
|
||||
commandId: CommandId.make("cmd-tl4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:01:00.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const settledRows = yield* sql<{
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
|
||||
`;
|
||||
assert.deepEqual(settledRows, [
|
||||
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a superseded running turn when a new turn becomes active", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-turn-supersede");
|
||||
const oldTurnId = TurnId.make("turn-superseded");
|
||||
const newTurnId = TurnId.make("turn-steer");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-ts1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-ts1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-ts1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-turn-supersede"),
|
||||
title: "Turn supersede",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "big-pickle",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
|
||||
eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make(eventId),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: updatedAt,
|
||||
commandId: CommandId.make(`cmd-${eventId}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-${eventId}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "opencode",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
|
||||
// A steer: a new turn becomes active without the provider ever
|
||||
// completing the previous one.
|
||||
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY requested_at
|
||||
`;
|
||||
assert.deepEqual(rows, [
|
||||
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
|
||||
{ turnId: newTurnId, state: "running", completedAt: null },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
@@ -1656,6 +1877,142 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears stale pending user input from projected shell summaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-stale-user-input-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:00.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-stale-user-input"),
|
||||
title: "Project Stale User Input",
|
||||
workspaceRoot: "/tmp/project-stale-user-input",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:35:00.000Z",
|
||||
updatedAt: "2026-02-26T12:35:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-stale-user-input-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:01.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
projectId: ProjectId.make("project-stale-user-input"),
|
||||
title: "Thread Stale User Input",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:35:01.000Z",
|
||||
updatedAt: "2026-02-26T12:35:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-user-input-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:02.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-user-input-requested"),
|
||||
tone: "info",
|
||||
kind: "user-input.requested",
|
||||
summary: "User input requested",
|
||||
payload: {
|
||||
requestId: "user-input-request-stale-1",
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow workspace writes only",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:35:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-user-input-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:03.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-user-input-failed"),
|
||||
tone: "error",
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
payload: {
|
||||
requestId: "user-input-request-stale-1",
|
||||
detail:
|
||||
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:35:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingUserInputCount: number;
|
||||
}>`
|
||||
SELECT pending_user_input_count AS "pendingUserInputCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-stale-user-input'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
type ProjectorName =
|
||||
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
|
||||
|
||||
/**
|
||||
* Turn state to settle still-running turns with when their session leaves the
|
||||
* "running" status, or null while the session is (re)starting or running and
|
||||
* turns must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSessionStatus,
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ProjectorDefinition {
|
||||
readonly name: ProjectorName;
|
||||
readonly apply: (
|
||||
@@ -141,7 +165,9 @@ function derivePendingUserInputCountFromActivities(
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
@@ -999,9 +1025,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
case "thread.session-set": {
|
||||
const turnId = event.payload.session.activeTurnId;
|
||||
if (turnId === null || event.payload.session.status !== "running") {
|
||||
// Leaving the "running" session status is the turn-end signal:
|
||||
// settle still-running turns so their duration reflects the whole
|
||||
// turn rather than the last assistant message.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
|
||||
if (settledTurnState === null) {
|
||||
return;
|
||||
}
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
|
||||
(turn) =>
|
||||
turn.turnId === null
|
||||
? Effect.void
|
||||
: projectionTurnRepository.upsertByTurnId({
|
||||
...turn,
|
||||
turnId: turn.turnId,
|
||||
state: settledTurnState,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// A new active turn supersedes any still-running turn on the same
|
||||
// thread — steering can open a new turn without the provider ever
|
||||
// completing the previous one.
|
||||
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
otherRunningTurns.filter(
|
||||
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
|
||||
),
|
||||
(turn) =>
|
||||
turn.turnId === null
|
||||
? Effect.void
|
||||
: projectionTurnRepository.upsertByTurnId({
|
||||
...turn,
|
||||
turnId: turn.turnId,
|
||||
state: "completed",
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId,
|
||||
@@ -1080,6 +1154,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (event.payload.turnId === null || event.payload.role !== "assistant") {
|
||||
return;
|
||||
}
|
||||
// A completed assistant message only settles the turn once the
|
||||
// session is no longer running it — providers may emit several
|
||||
// assistant messages per turn (commentary between tool calls), and
|
||||
// the turn must stay unsettled until the provider reports turn end
|
||||
// (projected as thread.session-set leaving the "running" status).
|
||||
const session = yield* projectionThreadSessionRepository.getByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const turnStillRunning =
|
||||
Option.isSome(session) &&
|
||||
session.value.status === "running" &&
|
||||
session.value.activeTurnId === event.payload.turnId;
|
||||
const settlesTurn = !event.payload.streaming && !turnStillRunning;
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
@@ -1088,16 +1175,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming
|
||||
? existingTurn.value.state
|
||||
: existingTurn.value.state === "interrupted"
|
||||
state: settlesTurn
|
||||
? existingTurn.value.state === "interrupted"
|
||||
? "interrupted"
|
||||
: existingTurn.value.state === "error"
|
||||
? "error"
|
||||
: "completed",
|
||||
completedAt: event.payload.streaming
|
||||
? existingTurn.value.completedAt
|
||||
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
|
||||
: "completed"
|
||||
: existingTurn.value.state,
|
||||
completedAt: settlesTurn
|
||||
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
|
||||
: existingTurn.value.completedAt,
|
||||
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
|
||||
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
|
||||
});
|
||||
@@ -1110,10 +1197,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming ? "running" : "completed",
|
||||
state: settlesTurn ? "completed" : "running",
|
||||
requestedAt: event.payload.createdAt,
|
||||
startedAt: event.payload.createdAt,
|
||||
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
|
||||
completedAt: settlesTurn ? event.payload.updatedAt : null,
|
||||
checkpointTurnCount: null,
|
||||
checkpointRef: null,
|
||||
checkpointStatus: null,
|
||||
@@ -1160,6 +1247,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
|
||||
case "thread.turn-diff-completed": {
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// checkpoint, but don't settle a turn its session is still running.
|
||||
const session = yield* projectionThreadSessionRepository.getByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const turnStillRunning =
|
||||
Option.isSome(session) &&
|
||||
session.value.status === "running" &&
|
||||
session.value.activeTurnId === event.payload.turnId;
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
@@ -1175,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
state: turnStillRunning ? existingTurn.value.state : nextState,
|
||||
checkpointTurnCount: event.payload.checkpointTurnCount,
|
||||
checkpointRef: event.payload.checkpointRef,
|
||||
checkpointStatus: event.payload.status,
|
||||
@@ -1193,7 +1289,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
state: turnStillRunning ? "running" : nextState,
|
||||
requestedAt: event.payload.completedAt,
|
||||
startedAt: event.payload.completedAt,
|
||||
completedAt: event.payload.completedAt,
|
||||
|
||||
@@ -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" },
|
||||
@@ -1857,7 +1943,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(resolvedActivity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
|
||||
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
harness.respondToUserInput.mockImplementation(() =>
|
||||
@@ -1865,7 +1951,7 @@ describe("ProviderCommandReactor", () => {
|
||||
new ProviderAdapterRequestError({
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
method: "item/tool/respondToUserInput",
|
||||
detail: "Unknown pending user-input request: user-input-request-1",
|
||||
detail: "Unknown pending Codex user input request: user-input-request-1",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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 {
|
||||
@@ -140,9 +141,19 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
const message = Cause.pretty(cause).toLowerCase();
|
||||
return (
|
||||
message.includes("unknown pending user-input request") ||
|
||||
message.includes("unknown pending user input request") ||
|
||||
message.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
|
||||
function stalePendingRequestDetail(
|
||||
@@ -180,6 +191,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 +317,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 +428,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 &&
|
||||
|
||||
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
Effect.andThen(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
|
||||
});
|
||||
|
||||
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
|
||||
// Steering a running turn: the server requests a new turn while the old
|
||||
// one is still active, and providers like opencode open the new turn
|
||||
// without ever completing the superseded one. The new turn.started must
|
||||
// replace the active turn instead of being rejected as stale.
|
||||
const harness = await createHarness();
|
||||
const threadId = asThreadId("thread-1");
|
||||
const oldTurnId = asTurnId("turn-steered-over");
|
||||
const newTurnId = asTurnId("turn-from-steer");
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: oldTurnId,
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-steered-over"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt,
|
||||
threadId,
|
||||
turnId: oldTurnId,
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
|
||||
2_000,
|
||||
threadId,
|
||||
);
|
||||
|
||||
// The steer: a user-requested turn start while the old turn still runs.
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-steer"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-steer"),
|
||||
role: "user",
|
||||
text: "actually, do 15 instead",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
// The provider session tracks the new turn before emitting turn.started
|
||||
// (sendTurn updates the session first).
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: newTurnId,
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-from-steer"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt,
|
||||
threadId,
|
||||
turnId: newTurnId,
|
||||
});
|
||||
|
||||
const threadAfterSteer = await waitForThread(
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
|
||||
2_000,
|
||||
threadId,
|
||||
);
|
||||
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
|
||||
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
|
||||
expect(threadAfterSteer.latestTurn?.state).toBe("running");
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
|
||||
@@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () {
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
||||
|
||||
// A turn.started that conflicts with the active turn is legitimate when
|
||||
// the server itself has a turn start pending for this thread AND the
|
||||
// provider session already tracks the event's turn as its active turn:
|
||||
// steering a running turn makes some providers (e.g. opencode) open a
|
||||
// new turn without ever completing the superseded one. A stale
|
||||
// turn.started for some other turn id still gets rejected.
|
||||
const conflictingTurnStartIsPendingTurnStart =
|
||||
event.type === "turn.started" && conflictsWithActiveTurn
|
||||
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
|
||||
Option.isSome(
|
||||
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
}),
|
||||
)
|
||||
: false;
|
||||
|
||||
const shouldApplyThreadLifecycle = (() => {
|
||||
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
|
||||
return true;
|
||||
@@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () {
|
||||
case "thread.started":
|
||||
return true;
|
||||
case "turn.started":
|
||||
return !conflictsWithActiveTurn;
|
||||
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
|
||||
case "turn.completed":
|
||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||
return false;
|
||||
|
||||
@@ -267,37 +267,76 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const afterRunning = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: startedAt,
|
||||
commandId: "cmd-running",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
const settledAt = "2026-02-23T08:01:00.000Z";
|
||||
const [afterRunning, afterReady] = await Effect.runPromise(
|
||||
Effect.flatMap(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: startedAt,
|
||||
commandId: "cmd-running",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(running) =>
|
||||
Effect.map(
|
||||
projectEvent(
|
||||
running,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: settledAt,
|
||||
commandId: "cmd-ready",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(ready) => [running, ready] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const thread = afterRunning.threads[0];
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
|
||||
// Leaving the "running" session status settles the running turn with the
|
||||
// session timestamp as the turn end.
|
||||
const settledThread = afterReady.threads[0];
|
||||
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(settledThread?.latestTurn?.state).toBe("completed");
|
||||
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
|
||||
});
|
||||
|
||||
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
|
||||
|
||||
@@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
|
||||
return "completed" as const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn state to settle a still-running latest turn with when its session
|
||||
* leaves the "running" status, or null while the session is (re)starting or
|
||||
* running and the turn must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSession["status"],
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
threads: ReadonlyArray<OrchestrationThread>,
|
||||
threadId: ThreadId,
|
||||
@@ -438,6 +461,9 @@ export function projectEvent(
|
||||
"session",
|
||||
);
|
||||
|
||||
// Leaving the "running" session status is the turn-end signal: settle
|
||||
// a still-running latest turn so its duration reflects the whole turn.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(session.status);
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
@@ -461,7 +487,18 @@ export function projectEvent(
|
||||
? thread.latestTurn.assistantMessageId
|
||||
: null,
|
||||
}
|
||||
: thread.latestTurn,
|
||||
: thread.latestTurn !== null &&
|
||||
thread.latestTurn.state === "running" &&
|
||||
settledTurnState !== null
|
||||
? {
|
||||
...thread.latestTurn,
|
||||
state: settledTurnState,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: session.updatedAt,
|
||||
}
|
||||
: thread.latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
@@ -544,24 +581,31 @@ export function projectEvent(
|
||||
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
|
||||
.slice(-MAX_THREAD_CHECKPOINTS);
|
||||
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// checkpoint, but don't settle a turn its session is still running.
|
||||
const turnStillRunning =
|
||||
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
checkpoints,
|
||||
latestTurn: {
|
||||
turnId: payload.turnId,
|
||||
state: checkpointStatusToLatestTurnState(payload.status),
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: payload.completedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||
: payload.completedAt,
|
||||
completedAt: payload.completedAt,
|
||||
assistantMessageId: payload.assistantMessageId,
|
||||
},
|
||||
latestTurn: turnStillRunning
|
||||
? thread.latestTurn
|
||||
: {
|
||||
turnId: payload.turnId,
|
||||
state: checkpointStatusToLatestTurnState(payload.status),
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: payload.completedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||
: payload.completedAt,
|
||||
completedAt: payload.completedAt,
|
||||
assistantMessageId: payload.assistantMessageId,
|
||||
},
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -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* () {
|
||||
@@ -867,6 +890,73 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.takeUntil(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.completed",
|
||||
).pipe(Stream.runCollect, Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "run 5 commands",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
// Steer: a second sendTurn while the turn is still running continues
|
||||
// the same turn — the message is queued into the live agent loop.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "actually run 15",
|
||||
attachments: [],
|
||||
});
|
||||
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-steer",
|
||||
uuid: "assistant-steer-1",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-steer-1",
|
||||
content: [{ type: "text", text: "Adjusting to 15." }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-steer",
|
||||
uuid: "result-steer-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
|
||||
|
||||
// One turn boundary for the whole run: the steer produced no
|
||||
// turn.completed/turn.started pair.
|
||||
assert.equal(turnStartedEvents.length, 1);
|
||||
assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompletedEvents.length, 1);
|
||||
assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId));
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type PermissionResult,
|
||||
type PermissionUpdate,
|
||||
type SDKMessage,
|
||||
type SDKControlGetContextUsageResponse,
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ModelSelection,
|
||||
ProviderItemId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderRuntimeTurnStatus,
|
||||
@@ -120,6 +122,13 @@ interface ClaudeResumeState {
|
||||
interface ClaudeTurnState {
|
||||
readonly turnId: TurnId;
|
||||
readonly startedAt: string;
|
||||
/**
|
||||
* True for turns auto-started by assistant output arriving without an
|
||||
* active turn (background agent/subagent responses between user prompts).
|
||||
* Synthetic turns are auto-closed by the next sendTurn; real turns are
|
||||
* steered instead (the queued message continues the same turn).
|
||||
*/
|
||||
readonly synthetic?: boolean;
|
||||
readonly items: Array<unknown>;
|
||||
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
|
||||
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
|
||||
@@ -159,6 +168,13 @@ interface ToolInFlight {
|
||||
readonly lastEmittedInputFingerprint?: string;
|
||||
}
|
||||
|
||||
interface ClaudeTaskState {
|
||||
readonly id: string;
|
||||
subject: string;
|
||||
status: PlanStep["status"];
|
||||
readonly blockedBy: Set<string>;
|
||||
}
|
||||
|
||||
interface ClaudeSessionContext {
|
||||
session: ProviderSession;
|
||||
readonly promptQueue: Queue.Queue<PromptQueueItem>;
|
||||
@@ -175,9 +191,11 @@ interface ClaudeSessionContext {
|
||||
items: Array<unknown>;
|
||||
}>;
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
readonly claudeTasks: Map<string, ClaudeTaskState>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
|
||||
lastKnownTotalProcessedTokens: number | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -188,6 +206,7 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
|
||||
readonly setModel: (model?: string) => Promise<void>;
|
||||
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
|
||||
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
|
||||
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
@@ -337,60 +356,220 @@ function maxClaudeContextWindowFromModelUsage(
|
||||
return maxContextWindow;
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
function selectedClaudeContextWindow(
|
||||
modelSelection: ModelSelection | undefined,
|
||||
): number | undefined {
|
||||
switch (modelSelection?.model) {
|
||||
case "claude-opus-4-8":
|
||||
case "claude-opus-4-7":
|
||||
return 1_000_000;
|
||||
}
|
||||
|
||||
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
if (optionValue === "1m") {
|
||||
return 1_000_000;
|
||||
}
|
||||
if (optionValue === "200k") {
|
||||
return 200_000;
|
||||
}
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
|
||||
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
|
||||
);
|
||||
if (hasContextWindowOption) {
|
||||
return 200_000;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function finiteNonNegativeInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
? Math.round(value)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function finitePositiveInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? Math.round(value)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function claudeUsageInputTokens(usage: Record<string, unknown>): number {
|
||||
return (
|
||||
(finiteNonNegativeInteger(usage.input_tokens) ?? 0) +
|
||||
(finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +
|
||||
(finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)
|
||||
);
|
||||
}
|
||||
|
||||
function claudeUsageOutputTokens(usage: Record<string, unknown>): number {
|
||||
return finiteNonNegativeInteger(usage.output_tokens) ?? 0;
|
||||
}
|
||||
|
||||
function lastClaudeUsageIteration(
|
||||
value: Record<string, unknown>,
|
||||
): Record<string, unknown> | undefined {
|
||||
const iterations = Array.isArray(value.iterations) ? value.iterations : [];
|
||||
return iterations.findLast(
|
||||
(iteration): iteration is Record<string, unknown> =>
|
||||
iteration !== null && typeof iteration === "object" && !Array.isArray(iteration),
|
||||
);
|
||||
}
|
||||
|
||||
function claudeTotalProcessedTokens(value: unknown): number | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);
|
||||
if (explicitTotal !== undefined && explicitTotal > 0) {
|
||||
return explicitTotal;
|
||||
}
|
||||
|
||||
const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);
|
||||
return total > 0 ? total : undefined;
|
||||
}
|
||||
|
||||
function makeClaudeTokenUsageSnapshot(input: {
|
||||
readonly activeTokens: number;
|
||||
readonly inputTokens?: number;
|
||||
readonly outputTokens?: number;
|
||||
readonly contextWindow?: number;
|
||||
readonly totalProcessedTokens?: number;
|
||||
readonly lastUsedTokens?: number;
|
||||
readonly compactsAutomatically?: boolean;
|
||||
}): ThreadTokenUsageSnapshot | undefined {
|
||||
const activeTokens = finiteNonNegativeInteger(input.activeTokens);
|
||||
if (activeTokens === undefined || activeTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens = finitePositiveInteger(input.contextWindow);
|
||||
const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;
|
||||
const lastUsedTokens =
|
||||
finiteNonNegativeInteger(input.lastUsedTokens) ??
|
||||
(maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);
|
||||
const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);
|
||||
const inputTokens = finiteNonNegativeInteger(input.inputTokens);
|
||||
const outputTokens = finiteNonNegativeInteger(input.outputTokens);
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens,
|
||||
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
|
||||
? { totalProcessedTokens }
|
||||
: {}),
|
||||
...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(input.compactsAutomatically !== undefined
|
||||
? { compactsAutomatically: input.compactsAutomatically }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeClaudeActiveTokenUsage(
|
||||
value: unknown,
|
||||
contextWindow?: number,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const inputTokens =
|
||||
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
|
||||
? usage.input_tokens
|
||||
: 0) +
|
||||
(typeof usage.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_creation_input_tokens)
|
||||
? usage.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof usage.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_read_input_tokens)
|
||||
? usage.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
|
||||
? usage.output_tokens
|
||||
: 0;
|
||||
const derivedTotalProcessedTokens = inputTokens + outputTokens;
|
||||
const totalProcessedTokens =
|
||||
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
|
||||
? usage.total_tokens
|
||||
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
|
||||
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
|
||||
const activeUsage = lastClaudeUsageIteration(usage) ?? usage;
|
||||
const inputTokens = claudeUsageInputTokens(activeUsage);
|
||||
const outputTokens = claudeUsageOutputTokens(activeUsage);
|
||||
const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;
|
||||
if (activeTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens =
|
||||
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? contextWindow
|
||||
: undefined;
|
||||
const usedTokens =
|
||||
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeClaudeContextUsageApiSnapshot(
|
||||
value: SDKControlGetContextUsageResponse,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens: value.totalTokens,
|
||||
contextWindow: value.maxTokens,
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
compactsAutomatically: value.isAutoCompactEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
function compactBoundaryTokenUsageSnapshot(
|
||||
message: Record<string, unknown>,
|
||||
contextWindow?: number,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
const metadata = message.compact_metadata;
|
||||
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const compactMetadata = metadata as Record<string, unknown>;
|
||||
const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);
|
||||
if (postTokens === undefined || postTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens: postTokens,
|
||||
...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeClaudeTaskProgressTokenUsage(
|
||||
value: unknown,
|
||||
context: ClaudeSessionContext,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
const totalTokens = claudeTotalProcessedTokens(value);
|
||||
if (totalTokens === undefined || totalTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;
|
||||
const activeTokens =
|
||||
lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;
|
||||
if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const snapshot = makeClaudeTokenUsageSnapshot({
|
||||
activeTokens,
|
||||
...(context.lastKnownContextWindow !== undefined
|
||||
? { contextWindow: context.lastKnownContextWindow }
|
||||
: {}),
|
||||
totalProcessedTokens: Math.max(
|
||||
totalTokens,
|
||||
context.lastKnownTotalProcessedTokens ?? totalTokens,
|
||||
),
|
||||
});
|
||||
if (!snapshot) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const toolUses = finiteNonNegativeInteger(usage.tool_uses);
|
||||
const durationMs = finiteNonNegativeInteger(usage.duration_ms);
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
|
||||
? { toolUses: usage.tool_uses }
|
||||
: {}),
|
||||
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
|
||||
? { durationMs: usage.duration_ms }
|
||||
: {}),
|
||||
...snapshot,
|
||||
...(toolUses !== undefined ? { toolUses } : {}),
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -539,6 +718,140 @@ function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep
|
||||
}));
|
||||
}
|
||||
|
||||
function isClaudeTaskTool(toolName: string): boolean {
|
||||
return toolName === "TaskCreate" || toolName === "TaskUpdate" || toolName === "TaskList";
|
||||
}
|
||||
|
||||
function normalizeClaudeTaskStatus(value: unknown): PlanStep["status"] {
|
||||
return value === "completed" ? "completed" : value === "in_progress" ? "inProgress" : "pending";
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function readStringArray(value: unknown): Array<string> {
|
||||
return Array.isArray(value)
|
||||
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
|
||||
: [];
|
||||
}
|
||||
|
||||
function readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {
|
||||
if (message.type !== "user") {
|
||||
return undefined;
|
||||
}
|
||||
const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;
|
||||
return result !== null && typeof result === "object" && !Array.isArray(result)
|
||||
? (result as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function readClaudeTaskFromResult(
|
||||
result: Record<string, unknown> | undefined,
|
||||
): Record<string, unknown> | undefined {
|
||||
const task = result?.task;
|
||||
return task !== null && typeof task === "object" && !Array.isArray(task)
|
||||
? (task as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function applyClaudeTaskToolResult(
|
||||
tasks: Map<string, ClaudeTaskState>,
|
||||
tool: ToolInFlight,
|
||||
result: Record<string, unknown> | undefined,
|
||||
): boolean {
|
||||
if (!isClaudeTaskTool(tool.toolName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
if (tool.toolName === "TaskList") {
|
||||
const resultTasks = result?.tasks;
|
||||
if (!Array.isArray(resultTasks)) {
|
||||
return false;
|
||||
}
|
||||
tasks.clear();
|
||||
for (const entry of resultTasks) {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
||||
continue;
|
||||
}
|
||||
const task = entry as Record<string, unknown>;
|
||||
const id = readString(task.id);
|
||||
const subject = readString(task.subject);
|
||||
if (!id || !subject) {
|
||||
continue;
|
||||
}
|
||||
tasks.set(id, {
|
||||
id,
|
||||
subject,
|
||||
status: normalizeClaudeTaskStatus(task.status),
|
||||
blockedBy: new Set(readStringArray(task.blockedBy)),
|
||||
});
|
||||
}
|
||||
return tasks.size > 0;
|
||||
}
|
||||
|
||||
if (tool.toolName === "TaskCreate") {
|
||||
const resultTask = readClaudeTaskFromResult(result);
|
||||
const id = readString(resultTask?.id);
|
||||
const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);
|
||||
if (!id || !subject) {
|
||||
return false;
|
||||
}
|
||||
tasks.set(id, {
|
||||
id,
|
||||
subject,
|
||||
status: normalizeClaudeTaskStatus(tool.input.status),
|
||||
blockedBy: new Set(readStringArray(tool.input.blockedBy)),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);
|
||||
if (!taskId) {
|
||||
return false;
|
||||
}
|
||||
const task = tasks.get(taskId);
|
||||
if (!task) {
|
||||
return false;
|
||||
}
|
||||
const subject = readString(tool.input.subject);
|
||||
if (subject && task.subject !== subject) {
|
||||
task.subject = subject;
|
||||
changed = true;
|
||||
}
|
||||
if (typeof tool.input.status === "string") {
|
||||
const status = normalizeClaudeTaskStatus(tool.input.status);
|
||||
if (task.status !== status) {
|
||||
task.status = status;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const dependency of readStringArray(tool.input.addBlockedBy)) {
|
||||
if (!task.blockedBy.has(dependency)) {
|
||||
task.blockedBy.add(dependency);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const dependency of readStringArray(tool.input.removeBlockedBy)) {
|
||||
if (task.blockedBy.delete(dependency)) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {
|
||||
return Array.from(tasks.values()).map((task) => {
|
||||
const blockedBy = Array.from(task.blockedBy);
|
||||
const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(", #")})` : "";
|
||||
return {
|
||||
step: `${task.subject}${blockedSuffix}`,
|
||||
status: task.status,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
|
||||
const commandValue = input.command ?? input.cmd;
|
||||
const command = typeof commandValue === "string" ? commandValue : undefined;
|
||||
@@ -1438,6 +1751,70 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const emitThreadTokenUsage = Effect.fn("emitThreadTokenUsage")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
usage: ThreadTokenUsageSnapshot | undefined,
|
||||
options?: {
|
||||
readonly rawMethod?: string;
|
||||
readonly rawPayload?: unknown;
|
||||
},
|
||||
) {
|
||||
if (!usage) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.lastKnownTokenUsage = usage;
|
||||
context.lastKnownTotalProcessedTokens =
|
||||
usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;
|
||||
|
||||
const turnState = context.turnState;
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(turnState ? { turnId: turnState.turnId } : {}),
|
||||
payload: {
|
||||
usage,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
...(options?.rawMethod || options?.rawPayload
|
||||
? {
|
||||
raw: {
|
||||
source: "claude.sdk.message" as const,
|
||||
...(options.rawMethod ? { method: options.rawMethod } : {}),
|
||||
payload: options.rawPayload,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
});
|
||||
|
||||
const queryCurrentContextUsage = Effect.fn("queryCurrentContextUsage")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
totalProcessedTokens?: number,
|
||||
) {
|
||||
if (!context.query.getContextUsage) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = yield* Effect.promise(async () => {
|
||||
try {
|
||||
return await context.query.getContextUsage?.();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
if (!usage) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
context.lastKnownContextWindow = usage.maxTokens;
|
||||
return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);
|
||||
});
|
||||
|
||||
const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
@@ -1485,6 +1862,42 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const emitClaudeTaskPlanUpdated = Effect.fn("emitClaudeTaskPlanUpdated")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
readonly toolUseId: string;
|
||||
readonly rawMethod: string;
|
||||
readonly rawPayload: unknown;
|
||||
},
|
||||
) {
|
||||
const plan = planStepsFromClaudeTasks(context.claudeTasks);
|
||||
if (plan.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.plan.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
payload: {
|
||||
explanation: "Claude Tasks",
|
||||
plan,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: input.toolUseId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: input.rawMethod,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const completeTurn = Effect.fn("completeTurn")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
status: ProviderRuntimeTurnStatus,
|
||||
@@ -1496,51 +1909,77 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
}
|
||||
|
||||
// The SDK result.usage contains *accumulated* totals across all API calls
|
||||
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
|
||||
// This does NOT represent the current context window size.
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
result?.usage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const accumulatedTotalProcessedTokens =
|
||||
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);
|
||||
if (accumulatedTotalProcessedTokens !== undefined) {
|
||||
context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;
|
||||
}
|
||||
|
||||
const contextUsageSnapshot = yield* queryCurrentContextUsage(
|
||||
context,
|
||||
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
|
||||
);
|
||||
const resultUsageRecord =
|
||||
result?.usage && typeof result.usage === "object" && !Array.isArray(result.usage)
|
||||
? (result.usage as Record<string, unknown>)
|
||||
: undefined;
|
||||
const hasResultUsageIteration =
|
||||
resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;
|
||||
const resultHasActiveUsage =
|
||||
resultUsageRecord !== undefined &&
|
||||
(hasResultUsageIteration ||
|
||||
claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);
|
||||
const resultTotalOnly =
|
||||
resultUsageRecord !== undefined &&
|
||||
!resultHasActiveUsage &&
|
||||
claudeTotalProcessedTokens(resultUsageRecord) !== undefined;
|
||||
const resultIterationSnapshot = resultUsageRecord
|
||||
? normalizeClaudeActiveTokenUsage(
|
||||
resultUsageRecord,
|
||||
maxTokens,
|
||||
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
|
||||
)
|
||||
: undefined;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined =
|
||||
contextUsageSnapshot ??
|
||||
(resultTotalOnly && lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: resultIterationSnapshot) ??
|
||||
(lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: undefined);
|
||||
|
||||
const turnState = context.turnState;
|
||||
if (!turnState) {
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: {},
|
||||
});
|
||||
}
|
||||
yield* emitThreadTokenUsage(context, usageSnapshot, {
|
||||
rawMethod: "claude/result",
|
||||
rawPayload: result ?? { status },
|
||||
});
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1611,21 +2050,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
items: [...turnState.items],
|
||||
});
|
||||
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
});
|
||||
}
|
||||
yield* emitThreadTokenUsage(context, usageSnapshot, {
|
||||
rawMethod: "claude/result",
|
||||
rawPayload: result ?? { status },
|
||||
});
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1670,6 +2098,23 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
|
||||
const { event } = message;
|
||||
|
||||
if (event.type === "message_delta") {
|
||||
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = normalizeClaudeActiveTokenUsage(
|
||||
event.usage,
|
||||
context.lastKnownContextWindow,
|
||||
context.lastKnownTotalProcessedTokens,
|
||||
);
|
||||
yield* emitThreadTokenUsage(context, snapshot, {
|
||||
rawMethod: "claude/stream_event/message_delta",
|
||||
rawPayload: message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "content_block_delta") {
|
||||
if (
|
||||
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
|
||||
@@ -1932,6 +2377,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
|
||||
const [index, tool] = toolEntry;
|
||||
const itemStatus = toolResult.isError ? "failed" : "completed";
|
||||
const toolUseResult = readClaudeToolUseResult(message);
|
||||
const toolData = {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
@@ -2016,6 +2462,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
!toolResult.isError &&
|
||||
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
|
||||
) {
|
||||
yield* emitClaudeTaskPlanUpdated(context, {
|
||||
toolUseId: tool.itemId,
|
||||
rawMethod: "claude/user",
|
||||
rawPayload: message,
|
||||
});
|
||||
}
|
||||
|
||||
context.inFlightTools.delete(index);
|
||||
}
|
||||
});
|
||||
@@ -2036,6 +2493,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
context.turnState = {
|
||||
turnId,
|
||||
startedAt,
|
||||
synthetic: true,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
@@ -2171,6 +2629,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "compact_boundary":
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
compactBoundaryTokenUsageSnapshot(
|
||||
message as unknown as Record<string, unknown>,
|
||||
context.lastKnownContextWindow,
|
||||
context.lastKnownTotalProcessedTokens,
|
||||
),
|
||||
{
|
||||
rawMethod: "claude/system/compact_boundary",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "thread.state.changed",
|
||||
@@ -2229,25 +2699,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "task_progress":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
{
|
||||
rawMethod: "claude/system/task_progress",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.progress",
|
||||
@@ -2261,25 +2720,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "task_notification":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
{
|
||||
rawMethod: "claude/system/task_notification",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.completed",
|
||||
@@ -2669,6 +3117,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const inFlightTools = new Map<number, ToolInFlight>();
|
||||
const claudeTasks = new Map<string, ClaudeTaskState>();
|
||||
|
||||
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
|
||||
|
||||
@@ -2969,6 +3418,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const descriptors = getProviderOptionDescriptors({ caps });
|
||||
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
|
||||
const initialContextWindow = selectedClaudeContextWindow(modelSelection);
|
||||
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
|
||||
const fastModeSupported = descriptors.some(
|
||||
@@ -3094,9 +3544,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
inFlightTools,
|
||||
claudeTasks,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastKnownContextWindow: initialContextWindow,
|
||||
lastKnownTokenUsage: undefined,
|
||||
lastKnownTotalProcessedTokens: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
@@ -3185,9 +3637,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
|
||||
if (context.turnState) {
|
||||
// Auto-close a stale synthetic turn (from background agent responses
|
||||
// between user prompts) to prevent blocking the user's next turn.
|
||||
// A sendTurn while a real turn is running is a steer: the message is
|
||||
// queued into the live SDK agent loop and the work continues as the same
|
||||
// turn — no synthetic turn boundary. Stale synthetic turns (from
|
||||
// background agent responses between user prompts) are auto-closed
|
||||
// instead, so they don't block the user's next turn.
|
||||
const steeringTurnState =
|
||||
context.turnState && context.turnState.synthetic !== true ? context.turnState : null;
|
||||
if (context.turnState && steeringTurnState === null) {
|
||||
yield* completeTurn(context, "completed");
|
||||
}
|
||||
|
||||
@@ -3222,37 +3679,39 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
if (steeringTurnState === null) {
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
context.turnState = turnState;
|
||||
context.session = {
|
||||
...context.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt,
|
||||
};
|
||||
const updatedAt = yield* nowIso;
|
||||
context.turnState = turnState;
|
||||
context.session = {
|
||||
...context.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
const turnStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
eventId: turnStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
payload: modelSelection?.model ? { model: modelSelection.model } : {},
|
||||
providerRefs: {},
|
||||
});
|
||||
const turnStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
eventId: turnStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
payload: modelSelection?.model ? { model: modelSelection.model } : {},
|
||||
providerRefs: {},
|
||||
});
|
||||
}
|
||||
|
||||
const message = yield* buildUserMessageEffect(input, {
|
||||
fileSystem,
|
||||
|
||||
@@ -48,60 +48,29 @@ 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-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
slug: "claude-fable-5",
|
||||
name: "Claude Fable 5",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
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"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
@@ -115,6 +84,33 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-8",
|
||||
name: "Claude Opus 4.8",
|
||||
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"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-7",
|
||||
name: "Claude Opus 4.7",
|
||||
@@ -124,16 +120,19 @@ 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"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
@@ -147,7 +146,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 +179,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 +202,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 +237,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 +253,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 +266,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 +322,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 +716,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))
|
||||
|
||||
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
cwd: process.cwd(),
|
||||
model: "gpt-5.3-codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
serviceTier: "fast",
|
||||
serviceTier: "priority",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
attachments: [],
|
||||
}),
|
||||
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
serviceTier: "priority",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
"gpt-5.3-codex",
|
||||
[
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "flex" },
|
||||
],
|
||||
),
|
||||
attachments: [],
|
||||
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
serviceTier: "flex",
|
||||
});
|
||||
}).pipe(Effect.provide(customLayer));
|
||||
});
|
||||
|
||||
@@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
import * as EffectCodexSchema from "effect-codex-app-server/schema";
|
||||
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
@@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
yield* Effect.suspend(() => stopSessionInternal(existing));
|
||||
}
|
||||
|
||||
const serviceTier =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getCodexServiceTierOptionValue(input.modelSelection)
|
||||
: undefined;
|
||||
const runtimeInput: CodexSessionRuntimeOptions = {
|
||||
threadId: input.threadId,
|
||||
providerInstanceId: boundInstanceId,
|
||||
@@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
...(input.modelSelection?.instanceId === boundInstanceId
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.instanceId === boundInstanceId &&
|
||||
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(serviceTier ? { serviceTier } : {}),
|
||||
};
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
@@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
|
||||
: undefined;
|
||||
const fastMode =
|
||||
const serviceTier =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
|
||||
? getCodexServiceTierOptionValue(input.modelSelection)
|
||||
: undefined;
|
||||
return yield* session.runtime
|
||||
.sendTurn({
|
||||
@@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
|
||||
}
|
||||
: {}),
|
||||
...(fastMode === true ? { serviceTier: "fast" } : {}),
|
||||
...(serviceTier ? { serviceTier } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
additionalSpeedTiers: [],
|
||||
defaultReasoningEffort: "super-high",
|
||||
description: "Test model",
|
||||
displayName: "GPT Test",
|
||||
hidden: false,
|
||||
id: "gpt-test",
|
||||
isDefault: true,
|
||||
model: "gpt-test",
|
||||
defaultServiceTier: "flex",
|
||||
serviceTiers: [
|
||||
{
|
||||
id: "priority",
|
||||
name: "Fast",
|
||||
description: "Lower latency responses.",
|
||||
},
|
||||
{
|
||||
id: "flex",
|
||||
name: "Flex",
|
||||
description: "Lower-cost asynchronous routing.",
|
||||
},
|
||||
],
|
||||
supportedReasoningEfforts: [
|
||||
{
|
||||
description: "Maximum reasoning",
|
||||
reasoningEffort: "super-high",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(capabilities.optionDescriptors, [
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [{ id: "super-high", label: "super-high", isDefault: true }],
|
||||
currentValue: "super-high",
|
||||
},
|
||||
{
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "default", label: "Standard" },
|
||||
{
|
||||
id: "priority",
|
||||
label: "Fast",
|
||||
description: "Lower latency responses.",
|
||||
},
|
||||
{
|
||||
id: "flex",
|
||||
label: "Flex",
|
||||
description: "Lower-cost asynchronous routing.",
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
currentValue: "flex",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses standard routing when the catalog has no default service tier", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
additionalSpeedTiers: ["fast"],
|
||||
defaultReasoningEffort: "medium",
|
||||
defaultServiceTier: null,
|
||||
description: "Test model",
|
||||
displayName: "GPT Test",
|
||||
hidden: false,
|
||||
id: "gpt-test",
|
||||
isDefault: true,
|
||||
model: "gpt-test",
|
||||
serviceTiers: [
|
||||
{
|
||||
id: "priority",
|
||||
name: "Fast",
|
||||
description: "1.5x speed, increased usage",
|
||||
},
|
||||
],
|
||||
supportedReasoningEfforts: [],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(capabilities.optionDescriptors, [
|
||||
{
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "default", label: "Standard", isDefault: true },
|
||||
{
|
||||
id: "priority",
|
||||
label: "Fast",
|
||||
description: "1.5x speed, increased usage",
|
||||
},
|
||||
],
|
||||
currentValue: "default",
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderState,
|
||||
ModelCapabilities,
|
||||
ProviderOptionDescriptor,
|
||||
ServerProviderModel,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot {
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
|
||||
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
|
||||
none: "None",
|
||||
minimal: "Minimal",
|
||||
low: "Low",
|
||||
@@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__Reasoning
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
|
||||
const DEFAULT_SERVICE_TIER_ID = "default";
|
||||
|
||||
function reasoningEffortLabel(reasoningEffort: string): string {
|
||||
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
|
||||
}
|
||||
|
||||
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
|
||||
if (!account) return undefined;
|
||||
if (account.type === "apiKey") return "OpenAI API Key";
|
||||
@@ -93,46 +100,71 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
|
||||
return account.email;
|
||||
}
|
||||
|
||||
function mapCodexModelCapabilities(
|
||||
export function mapCodexModelCapabilities(
|
||||
model: CodexSchema.V2ModelListResponse__Model,
|
||||
): ModelCapabilities {
|
||||
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
|
||||
reasoningEffort === model.defaultReasoningEffort
|
||||
? {
|
||||
id: reasoningEffort,
|
||||
label: REASONING_EFFORT_LABELS[reasoningEffort],
|
||||
label: reasoningEffortLabel(reasoningEffort),
|
||||
isDefault: true,
|
||||
}
|
||||
: {
|
||||
id: reasoningEffort,
|
||||
label: REASONING_EFFORT_LABELS[reasoningEffort],
|
||||
label: reasoningEffortLabel(reasoningEffort),
|
||||
},
|
||||
);
|
||||
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
|
||||
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
|
||||
const serviceTiers =
|
||||
model.serviceTiers && model.serviceTiers.length > 0
|
||||
? model.serviceTiers
|
||||
: (model.additionalSpeedTiers ?? []).map((id) => ({
|
||||
id,
|
||||
name: id === "fast" ? "Fast" : id,
|
||||
description: "",
|
||||
}));
|
||||
const catalogDefaultServiceTier = serviceTiers.some(
|
||||
(tier) => tier.id === model.defaultServiceTier,
|
||||
)
|
||||
? model.defaultServiceTier
|
||||
: null;
|
||||
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
|
||||
const optionDescriptors: ProviderOptionDescriptor[] = [];
|
||||
|
||||
if (reasoningOptions.length > 0) {
|
||||
optionDescriptors.push({
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: reasoningOptions,
|
||||
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
|
||||
});
|
||||
}
|
||||
if (serviceTiers.length > 0) {
|
||||
optionDescriptors.push({
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{
|
||||
id: DEFAULT_SERVICE_TIER_ID,
|
||||
label: "Standard",
|
||||
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
|
||||
},
|
||||
...serviceTiers.map((tier) => ({
|
||||
id: tier.id,
|
||||
label: tier.name,
|
||||
...(tier.description ? { description: tier.description } : {}),
|
||||
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
|
||||
})),
|
||||
],
|
||||
currentValue: defaultServiceTier,
|
||||
});
|
||||
}
|
||||
|
||||
return createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
...(reasoningOptions.length > 0
|
||||
? [
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select" as const,
|
||||
options: reasoningOptions,
|
||||
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(supportsFastMode
|
||||
? [
|
||||
{
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
type: "boolean" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
optionDescriptors,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
@@ -232,6 +233,82 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-steer-thread");
|
||||
|
||||
// Keep the first prompt in flight long enough for the steer to land.
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.threadId === threadId),
|
||||
Stream.takeUntil((event) => event.type === "turn.completed"),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
|
||||
});
|
||||
|
||||
const firstTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
// Poll until the first prompt is in flight — sendTurn binds the active
|
||||
// turn id before prompting. The mock agent runs on the real clock, so
|
||||
// each TestClock.adjust just provides the scheduler hops for its stdio
|
||||
// responses to land.
|
||||
yield* Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
if (session?.activeTurnId !== undefined) {
|
||||
return;
|
||||
}
|
||||
yield* TestClock.adjust("10 millis");
|
||||
}
|
||||
throw new Error("Timed out waiting for the first prompt to be in flight.");
|
||||
});
|
||||
|
||||
// Steer: a second sendTurn while the first prompt is still in flight
|
||||
// continues the same turn.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
attachments: [],
|
||||
});
|
||||
const firstTurn = yield* Fiber.join(firstTurnFiber);
|
||||
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
|
||||
|
||||
// One turn boundary for the whole run: the superseded first prompt
|
||||
// resolving must not settle the merged turn.
|
||||
assert.equal(turnStartedEvents.length, 1);
|
||||
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
|
||||
assert.equal(turnCompletedEvents.length, 1);
|
||||
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process when a session stops", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
@@ -132,6 +132,10 @@ interface CursorSessionContext {
|
||||
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
@@ -754,6 +758,7 @@ export function makeCursorAdapter(
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
promptsInFlight: 0,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -882,121 +887,152 @@ export function makeCursorAdapter(
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
modelSelection:
|
||||
model === undefined
|
||||
? undefined
|
||||
: {
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent folds
|
||||
// the new prompt into the ongoing work, so the active turn id is
|
||||
// reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; the matching
|
||||
// decrement is the `ensuring` below.
|
||||
ctx.promptsInFlight += 1;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
});
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
modelSelection:
|
||||
model === undefined
|
||||
? undefined
|
||||
: {
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
|
||||
if (input.input?.trim()) {
|
||||
promptParts.push({ type: "text", text: input.input.trim() });
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
|
||||
if (input.input?.trim()) {
|
||||
promptParts.push({ type: "text", text: input.input.trim() });
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = yield* ctx.acp
|
||||
.prompt({
|
||||
prompt: promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
model: resolvedModel,
|
||||
};
|
||||
const result = yield* ctx.acp
|
||||
.prompt({
|
||||
prompt: promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
|
||||
if (turnRecord) {
|
||||
turnRecord.items.push({ prompt: promptParts, result });
|
||||
} else {
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
model: resolvedModel,
|
||||
};
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another is
|
||||
// in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
|
||||
|
||||
@@ -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,988 @@
|
||||
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;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
currentModelId: string | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
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,
|
||||
promptsInFlight: 0,
|
||||
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);
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent
|
||||
// folds the new prompt into the ongoing work, so the active turn
|
||||
// id is reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; decremented on
|
||||
// preparation failure here, and after the prompt below otherwise.
|
||||
ctx.promptsInFlight += 1;
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
const requestedTurnModelId = turnModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(turnModelSelection.model)
|
||||
: undefined;
|
||||
const currentModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
requestedModelId: requestedTurnModelId,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
|
||||
const text = input.input?.trim();
|
||||
const imagePromptParts = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
} satisfies EffectAcpSchema.ContentBlock;
|
||||
}),
|
||||
);
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
|
||||
...(text ? [{ type: "text" as const, text }] : []),
|
||||
...imagePromptParts,
|
||||
];
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.currentModelId = currentModelId;
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
};
|
||||
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: displayModel ? { model: displayModel } : {},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
acp: ctx.acp,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
displayModel,
|
||||
promptParts,
|
||||
turnId,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* prepared.acp
|
||||
.prompt({
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === prepared.turnId
|
||||
? {
|
||||
...turn,
|
||||
items: [...turn.items, { prompt: prepared.promptParts, result }],
|
||||
}
|
||||
: turn,
|
||||
)
|
||||
: [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
};
|
||||
@@ -395,6 +395,85 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-steer");
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
// Steer: OpenCode queues the prompt into the busy session, so the
|
||||
// active turn id is reused instead of opening a new turn.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
|
||||
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
assert.equal(session?.status, "running");
|
||||
assert.equal(String(session?.activeTurnId), String(turn.turnId));
|
||||
assert.equal(runtimeMock.state.promptCalls.length, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the running turn when a steer prompt fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-steer-failure");
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
runtimeMock.state.promptAsyncError = new Error("steer failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
// The original turn keeps running — only the steer prompt failed.
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
assert.equal(session?.status, "running");
|
||||
assert.equal(String(session?.activeTurnId), String(turn.turnId));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
|
||||
const instanceId = ProviderInstanceId.make("opencode_zen");
|
||||
const adapterLayer = Layer.effect(
|
||||
|
||||
@@ -1151,7 +1151,11 @@ export function makeOpenCodeAdapter(
|
||||
|
||||
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const context = ensureSessionContext(sessions, input.threadId);
|
||||
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
|
||||
// A sendTurn while a turn is active is a steer: OpenCode queues the
|
||||
// prompt into the busy session and the work continues as one turn, so
|
||||
// the active turn id is reused instead of opening a new turn.
|
||||
const steeringTurnId = context.activeTurnId;
|
||||
const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
|
||||
const modelSelection =
|
||||
input.modelSelection ??
|
||||
(context.session.model
|
||||
@@ -1206,14 +1210,16 @@ export function makeOpenCodeAdapter(
|
||||
{ clearLastError: true },
|
||||
);
|
||||
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
...(variant ? { effort: variant } : {}),
|
||||
},
|
||||
});
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
...(variant ? { effort: variant } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* runOpenCodeSdk("session.promptAsync", () =>
|
||||
context.client.session.promptAsync({
|
||||
@@ -1225,35 +1231,38 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(toRequestError),
|
||||
// On failure: clear active-turn state, flip the session back to ready
|
||||
// with lastError set, emit turn.aborted, then let the typed error
|
||||
// propagate. We don't need to rebuild the error here — `toRequestError`
|
||||
// already produced the right shape.
|
||||
// On failure of a fresh turn: clear active-turn state, flip the
|
||||
// session back to ready with lastError set, emit turn.aborted, then
|
||||
// let the typed error propagate. We don't need to rebuild the error
|
||||
// here — `toRequestError` already produced the right shape. A failed
|
||||
// steer leaves the still-running original turn untouched.
|
||||
Effect.tapError((requestError) =>
|
||||
Effect.gen(function* () {
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
yield* updateProviderSession(
|
||||
context,
|
||||
{
|
||||
status: "ready",
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
lastError: requestError.detail,
|
||||
},
|
||||
{ clearActiveTurnId: true },
|
||||
);
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
})),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
},
|
||||
});
|
||||
}),
|
||||
steeringTurnId !== undefined
|
||||
? Effect.void
|
||||
: Effect.gen(function* () {
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
yield* updateProviderSession(
|
||||
context,
|
||||
{
|
||||
status: "ready",
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
lastError: requestError.detail,
|
||||
},
|
||||
{ clearActiveTurnId: true },
|
||||
);
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
})),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("does not run provider probes during layer construction", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
const initialProvider = {
|
||||
instanceId: codexInstanceId,
|
||||
driver: codexDriver,
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-06-10T00:00:00.000Z",
|
||||
version: null,
|
||||
message: "Checking Codex provider status.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshCalls = yield* Ref.make(0);
|
||||
const instance = {
|
||||
instanceId: codexInstanceId,
|
||||
driverKind: codexDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: codexDriver,
|
||||
continuationKey: "codex:instance:codex",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.never),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
|
||||
});
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-background-refresh-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
|
||||
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
@@ -992,6 +1063,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`;
|
||||
@@ -1041,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const providers = yield* registry.getProviders;
|
||||
let providers = yield* registry.getProviders;
|
||||
for (
|
||||
let attempts = 0;
|
||||
attempts < 50 &&
|
||||
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
|
||||
"error";
|
||||
attempts += 1
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
providers = yield* registry.getProviders;
|
||||
}
|
||||
const codexPersonal = providers.find(
|
||||
(provider) => provider.instanceId === "codex_personal",
|
||||
);
|
||||
@@ -1071,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// instance and rebuild it so a fresh probe runs with the new binary.
|
||||
// This test drives the real settings stream → registry reconcile →
|
||||
// aggregator sync pipeline and asserts that `getProviders` reflects
|
||||
// the new probe's outcome. If `syncLiveSources` stops awaiting the
|
||||
// rebuilt instance's refresh (previous bug mode), the aggregator
|
||||
// keeps the old snapshot and this test fails.
|
||||
// the new background probe's outcome.
|
||||
//
|
||||
it.effect("re-probes when settings change the codex binaryPath", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1086,6 +1166,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 },
|
||||
},
|
||||
}),
|
||||
@@ -1122,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// the two probe runs is `checkedAt` — each probe stamps a
|
||||
// fresh DateTime, so we capture it and assert it advances
|
||||
// after the settings mutation.
|
||||
const initialProviders = yield* registry.getProviders;
|
||||
let initialProviders = yield* registry.getProviders;
|
||||
for (
|
||||
let attempts = 0;
|
||||
attempts < 50 &&
|
||||
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
|
||||
"error";
|
||||
attempts += 1
|
||||
) {
|
||||
yield* TestClock.adjust("10 millis");
|
||||
yield* Effect.yieldNow;
|
||||
initialProviders = yield* registry.getProviders;
|
||||
}
|
||||
const initialCodex = initialProviders.find(
|
||||
(provider) => provider.instanceId === "codex",
|
||||
);
|
||||
@@ -1142,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// envelope changed because `binaryPath` differs → `entryEqual`
|
||||
// is false). The registry's `Stream.runForEach(
|
||||
// instanceRegistry.streamChanges, () => syncLiveSources)`
|
||||
// fires `syncLiveSources`, which subscribes + awaits a fresh
|
||||
// refresh on the rebuilt instance.
|
||||
// fires `syncLiveSources`, which subscribes and launches a fresh
|
||||
// background refresh on the rebuilt instance.
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: { enabled: true, binaryPath: secondMissing },
|
||||
@@ -1156,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
for (let attempts = 0; attempts < 60; attempts += 1) {
|
||||
const providers = yield* registry.getProviders;
|
||||
const codex = providers.find((provider) => provider.instanceId === "codex");
|
||||
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
|
||||
if (
|
||||
codex !== undefined &&
|
||||
codex.status === "error" &&
|
||||
codex.checkedAt !== initialCheckedAt
|
||||
) {
|
||||
return providers;
|
||||
}
|
||||
yield* TestClock.adjust("50 millis");
|
||||
@@ -1186,6 +1282,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 +1342,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
cursor: {
|
||||
enabled: false,
|
||||
},
|
||||
grok: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1305,6 +1405,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
"claudeAgent",
|
||||
"codex",
|
||||
"cursor",
|
||||
"grok",
|
||||
"opencode",
|
||||
]);
|
||||
assert.strictEqual(cursorProvider?.enabled, false);
|
||||
@@ -1360,6 +1461,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",
|
||||
() =>
|
||||
|
||||
@@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - force-refresh each newly-added/rebuilt instance and feed the
|
||||
* result directly into `providersRef`, bypassing the PubSub
|
||||
* attachment race that otherwise drops the initial probe;
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Initial refreshes are awaited in parallel rather than forked, so
|
||||
* callers (layer build; `streamChanges` watcher) see fully-probed
|
||||
* state on return. This matters for layer build in particular:
|
||||
* consumers reading `getProviders` immediately after layer build
|
||||
* expect the probe to have already landed.
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
@@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream BEFORE kicking off refreshes — if the driver's
|
||||
// own initial probe (line 140 in `makeManagedServerProvider`)
|
||||
// wins the refreshSemaphore race, its PubSub publish must land
|
||||
// in an active subscriber or the result is dropped.
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Force-refresh every new/rebuilt instance in parallel and wait
|
||||
// for them all to complete. The refresh's result is piped
|
||||
// directly into `syncProvider`, so `providersRef` is populated
|
||||
// deterministically by the time this block returns — regardless
|
||||
// of PubSub subscription timing. Failures are logged and
|
||||
// swallowed so one bad driver can't wedge the whole registry.
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([, instance]) =>
|
||||
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
);
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
@@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync: subscribe + kick off refreshes for every instance
|
||||
// present at boot. Run synchronously so consumers pulling immediately
|
||||
// after the layer build see the correct aggregator state.
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
|
||||
@@ -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,
|
||||
];
|
||||
@@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => {
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
|
||||
|
||||
@@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orDie,
|
||||
),
|
||||
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
|
||||
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -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";
|
||||
@@ -87,6 +87,12 @@ import * as NetService from "@t3tools/shared/Net";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
|
||||
|
||||
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
|
||||
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
|
||||
// already closes the websocket gracefully. Do not add an artificial drain before
|
||||
// those finalizers get a chance to run.
|
||||
const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
if (typeof Bun !== "undefined") {
|
||||
@@ -116,6 +122,7 @@ const HttpServerLive = Layer.unwrap(
|
||||
return BunHttpServer.layer({
|
||||
port: config.port,
|
||||
...(config.host ? { hostname: config.host } : {}),
|
||||
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
|
||||
});
|
||||
} else {
|
||||
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
|
||||
@@ -125,6 +132,7 @@ const HttpServerLive = Layer.unwrap(
|
||||
return NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
|
||||
});
|
||||
}
|
||||
}),
|
||||
@@ -321,7 +329,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 +437,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,
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@ function makeFakeCodexBinary(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireServiceTier?: string;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
@@ -52,7 +52,7 @@ function makeFakeCodexBinary(
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
'seen_image="0"',
|
||||
'seen_fast_service_tier="0"',
|
||||
'seen_service_tier=""',
|
||||
'seen_reasoning_effort=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--image" ]; then',
|
||||
@@ -65,9 +65,11 @@ function makeFakeCodexBinary(
|
||||
" fi",
|
||||
' if [ "$1" = "--config" ]; then',
|
||||
" shift",
|
||||
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
||||
' seen_fast_service_tier="1"',
|
||||
" fi",
|
||||
' case "$1" in',
|
||||
" service_tier=*)",
|
||||
' seen_service_tier="$1"',
|
||||
" ;;",
|
||||
" esac",
|
||||
' case "$1" in',
|
||||
" model_reasoning_effort=*)",
|
||||
' seen_reasoning_effort="$1"',
|
||||
@@ -93,10 +95,10 @@ function makeFakeCodexBinary(
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireFastServiceTier
|
||||
...(input.requireServiceTier
|
||||
? [
|
||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
`if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
|
||||
' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
|
||||
` exit 5`,
|
||||
"fi",
|
||||
]
|
||||
@@ -161,7 +163,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireServiceTier?: string;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
@@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
||||
"forwards codex service tier and non-default reasoning effort into codex exec config",
|
||||
() =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
@@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
}),
|
||||
requireFastServiceTier: true,
|
||||
requireServiceTier: "priority",
|
||||
requireReasoningEffort: "xhigh",
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
@@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -32,10 +32,8 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
@@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
const reasoningEffort =
|
||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
|
||||
const command = ChildProcess.make(
|
||||
codexConfig.binaryPath || "codex",
|
||||
[
|
||||
@@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
|
||||
? ["--config", `service_tier="fast"`]
|
||||
: []),
|
||||
...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -68,6 +68,17 @@ export interface GitStatusDetails {
|
||||
aheadOfDefaultCount: number;
|
||||
}
|
||||
|
||||
export interface GitRemoteStatusDetails {
|
||||
isRepo: boolean;
|
||||
isDefaultBranch: boolean;
|
||||
branch: string | null;
|
||||
upstreamRef: string | null;
|
||||
hasUpstream: boolean;
|
||||
aheadCount: number;
|
||||
behindCount: number;
|
||||
aheadOfDefaultCount: number;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
@@ -162,6 +173,9 @@ export interface GitVcsDriverShape {
|
||||
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsRemote: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
|
||||
@@ -155,6 +155,67 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports remote divergence without reading working-tree details", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/remote-status"]);
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* git(cwd, ["add", "feature.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "feature commit"]);
|
||||
yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]);
|
||||
yield* writeTextFile(cwd, "untracked.txt", "local-only\n");
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
|
||||
|
||||
assert.equal(status.isRepo, true);
|
||||
assert.equal(status.branch, "feature/remote-status");
|
||||
assert.equal(status.hasUpstream, true);
|
||||
assert.equal(status.aheadCount, 0);
|
||||
assert.equal(status.behindCount, 0);
|
||||
assert.equal(status.aheadOfDefaultCount, 1);
|
||||
assert.notProperty(status, "workingTree");
|
||||
assert.notProperty(status, "hasWorkingTreeChanges");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
|
||||
const upstream = yield* makeTmpDir("git-vcs-driver-upstream-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(origin, ["init", "--bare"]);
|
||||
yield* git(upstream, ["init", "--bare"]);
|
||||
yield* git(cwd, ["branch", "-M", "main"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", origin]);
|
||||
yield* git(cwd, ["remote", "add", "upstream", upstream]);
|
||||
yield* git(cwd, ["push", "origin", "main"]);
|
||||
yield* git(cwd, ["push", "upstream", "main"]);
|
||||
yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
|
||||
yield* git(cwd, ["checkout", "-b", "release"]);
|
||||
yield* writeTextFile(cwd, "release.txt", "release\n");
|
||||
yield* git(cwd, ["add", "release.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "release commit"]);
|
||||
yield* git(cwd, ["push", "-u", "upstream", "release"]);
|
||||
yield* git(cwd, [
|
||||
"symbolic-ref",
|
||||
"refs/remotes/upstream/HEAD",
|
||||
"refs/remotes/upstream/release",
|
||||
]);
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
|
||||
|
||||
assert.equal(status.branch, "release");
|
||||
assert.equal(status.upstreamRef, "upstream/release");
|
||||
assert.equal(status.isDefaultBranch, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("disables SSH askpass for background upstream status fetches", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -71,6 +71,16 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
|
||||
isRepo: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
@@ -1154,6 +1164,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
|
||||
});
|
||||
|
||||
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
|
||||
const branchResult = yield* executeGit(
|
||||
"GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (branchResult === null) {
|
||||
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
|
||||
}
|
||||
if (branchResult.exitCode !== 0) {
|
||||
const stderr = branchResult.stderr.trim();
|
||||
return yield* createGitCommandError(
|
||||
"GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
stderr || "git branch lookup failed",
|
||||
);
|
||||
}
|
||||
|
||||
const branchValue = branchResult.stdout.trim();
|
||||
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
const upstreamRef = upstream?.upstreamRef ?? null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
|
||||
if (upstreamRef) {
|
||||
const divergence = yield* executeGit(
|
||||
"GitVcsDriver.statusDetailsRemote.divergence",
|
||||
cwd,
|
||||
["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`],
|
||||
{ allowNonZeroExit: true },
|
||||
);
|
||||
if (divergence.exitCode === 0) {
|
||||
const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/);
|
||||
const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10);
|
||||
const parsedBehind = Number.parseInt(behindRaw ?? "0", 10);
|
||||
aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;
|
||||
behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;
|
||||
}
|
||||
} else if (branch) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin");
|
||||
const isDefaultBranch =
|
||||
branch !== null &&
|
||||
(branch === defaultBranch ||
|
||||
(defaultBranch === null && (branch === "main" || branch === "master")));
|
||||
const aheadOfDefaultCount =
|
||||
branch && !isDefaultBranch
|
||||
? upstreamRef === null
|
||||
? aheadCount
|
||||
: yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0))
|
||||
: 0;
|
||||
|
||||
return {
|
||||
isRepo: true,
|
||||
isDefaultBranch,
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
aheadOfDefaultCount,
|
||||
};
|
||||
});
|
||||
|
||||
const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitVcsDriver.readBranchRecency",
|
||||
@@ -1356,6 +1438,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
},
|
||||
);
|
||||
|
||||
const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn(
|
||||
"statusDetailsRemote",
|
||||
)(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsRemote(cwd);
|
||||
});
|
||||
|
||||
const status: GitVcsDriver.GitVcsDriverShape["status"] = (input) =>
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
@@ -1402,7 +1494,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const stagedPatch = yield* runGitStdoutWithOptions(
|
||||
"GitVcsDriver.prepareCommitContext.stagedPatch",
|
||||
cwd,
|
||||
["diff", "--cached", "--patch", "--minimal"],
|
||||
["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"],
|
||||
{
|
||||
maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
@@ -1639,7 +1731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
runGitStdoutWithOptions(
|
||||
"GitVcsDriver.readRangeContext.diffPatch",
|
||||
cwd,
|
||||
["diff", "--patch", "--minimal", range],
|
||||
["diff", "--no-ext-diff", "--patch", "--minimal", range],
|
||||
{
|
||||
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
@@ -2302,6 +2394,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
status,
|
||||
statusDetails,
|
||||
statusDetailsLocal,
|
||||
statusDetailsRemote,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import type {
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
@@ -310,6 +311,48 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const scope = yield* Scope.make();
|
||||
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
|
||||
yield* Deferred.await(snapshotDeferred);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(59));
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
});
|
||||
|
||||
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
|
||||
|
||||
@@ -257,6 +257,7 @@ export const layer = Layer.effect(
|
||||
const makeRemoteRefreshLoop = (
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
refreshImmediately: boolean,
|
||||
) => {
|
||||
return Effect.gen(function* () {
|
||||
const consecutiveFailuresRef = yield* Ref.make(0);
|
||||
@@ -289,6 +290,15 @@ export const layer = Layer.effect(
|
||||
return nextDelay;
|
||||
});
|
||||
|
||||
if (!refreshImmediately) {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
yield* Effect.sleep(
|
||||
Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval,
|
||||
);
|
||||
}
|
||||
|
||||
return yield* refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.repeat(
|
||||
Schedule.identity<Duration.Duration>().pipe(
|
||||
@@ -303,6 +313,7 @@ export const layer = Layer.effect(
|
||||
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
refreshImmediately: boolean,
|
||||
) {
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
@@ -315,7 +326,7 @@ export const layer = Layer.effect(
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
@@ -363,11 +374,13 @@ export const layer = Layer.effect(
|
||||
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(cwd);
|
||||
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
|
||||
const cachedStatus = yield* getCachedStatus(cwd);
|
||||
const initialRemote = cachedStatus?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(
|
||||
cwd,
|
||||
options?.automaticRemoteRefreshInterval ??
|
||||
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
|
||||
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
|
||||
);
|
||||
|
||||
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user