Compare commits

..
Author SHA1 Message Date
Cursor Agent 44ee7a6c3a fix: resolve background activity bugs (scope mismatch, leak on disconnect, dialog reset)
- VCS scope cwd mismatch: Pass raw (un-normalized) cwd to shouldRunScopeWork
  so the scope key matches what the client sends in activity lease scopes,
  while keeping the normalized path for filesystem operations.

- Disconnect never clears leases: Add removeSession to BackgroundPolicy and
  call it in the WebSocket disconnect handler so activity leases are cleaned
  up immediately when a client disconnects rather than waiting for TTL expiry.

- Advanced dialog clears overrides: In BackgroundActivityAdvancedDialog, change
  the shared policy Select to update baseProfile while keeping profile as
  'custom' and preserving existing overrides, instead of calling the preset
  helper that wipes overrides.
2026-06-16 17:17:29 +00:00
Julius Marminge 79ad071184 Merge origin/main into t3code/a55b49df
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/server/src/provider/Drivers/CodexDriver.ts
#	apps/server/src/provider/Drivers/CursorDriver.ts
#	apps/server/src/provider/Drivers/OpenCodeDriver.ts
#	apps/server/src/server.ts
#	apps/server/src/ws.ts
#	apps/web/src/environments/runtime/service.ts
#	apps/web/src/lib/gitStatusState.ts
#	packages/client-runtime/src/wsRpcClient.ts
#	packages/contracts/src/rpc.ts
#	packages/shared/src/serverSettings.test.ts
2026-06-16 10:01:03 -07:00
Julius Marmingeandcodex 8da08596ca Add background activity policy and host power monitoring
- Track client leases, host power, and background work eligibility
- Route provider snapshot refreshes through shared background policy
- Add tests for the new policy and related server settings wiring

Co-authored-by: codex <[email protected]>
2026-05-20 10:42:02 +02:00
93 changed files with 3445 additions and 4721 deletions

No files matched your search

@@ -99,7 +99,6 @@ export const layer = Layer.effect(
width: 12,
height: 12,
});
icon.setTemplateImage(true);
destructiveMenuIconCache = icon.isEmpty() ? Option.none() : Option.some(icon);
} catch {
destructiveMenuIconCache = Option.none();
+15 -43
View File
@@ -1,6 +1,4 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
interface Props {
title?: string;
description?: string;
@@ -38,17 +36,17 @@ const {
</a>
<div class="nav-right">
<a
class="nav-stars"
href={GITHUB_REPOSITORY_URL}
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
aria-label={`Star T3 Code on GitHub — ${MARKETING_STATS.githubStars} stars`}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 2.3l2.9 5.88 6.49.94-4.7 4.58 1.11 6.47L12 17.12l-5.8 3.05 1.11-6.47-4.7-4.58 6.49-.94L12 2.3z"/>
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span><strong>{MARKETING_STATS.githubStars}</strong> GitHub stars</span>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
@@ -64,7 +62,7 @@ const {
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
@@ -331,36 +329,23 @@ const {
gap: 8px;
}
.nav-stars {
.nav-gh {
display: inline-flex;
align-items: center;
gap: 7px;
height: 36px;
padding: 0 14px;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.02);
border-radius: 8px;
color: var(--fg-muted);
font-size: 13px;
letter-spacing: -0.01em;
white-space: nowrap;
transition: color 0.18s ease, border-color 0.18s ease, background 0.18s ease;
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-stars:hover {
.nav-gh:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.04);
}
.nav-stars strong {
color: var(--fg);
font-weight: 600;
}
.nav-stars svg {
color: var(--warn);
flex-shrink: 0;
border-color: var(--border-strong);
}
.main {
@@ -422,17 +407,4 @@ const {
padding-right: 20px;
}
}
@media (max-width: 420px) {
.nav-inner {
gap: 12px;
}
.nav-stars {
height: 34px;
gap: 6px;
padding: 0 12px;
font-size: 12px;
}
}
</style>
-6
View File
@@ -1,6 +0,0 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
users: "100,000",
} as const;
+66 -181
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -56,12 +55,11 @@ const mobileEndorsementRows = [
<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 class="hero-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
<svg class="hero-source-mark" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
Star on GitHub
</a>
</div>
@@ -84,8 +82,8 @@ const mobileEndorsementRows = [
<section id="endorsements" class="sec-endorsements" aria-labelledby="endorsements-title">
<div class="container">
<div class="endorsements-head">
<h2 id="endorsements-title">Tolerated by over <span class="endorsements-count">{MARKETING_STATS.users}</span> devs</h2>
<p>Some of them even tweeted about it.</p>
<h2 id="endorsements-title">Developers love T3 Code</h2>
<p>Real reactions from people building with T3 Code today.</p>
</div>
</div>
@@ -284,6 +282,10 @@ const mobileEndorsementRows = [
<div class="section-head open-head">
<div class="eyebrow">Open source</div>
<h2>If you don't like something, fork it.</h2>
<p>
T3 Code is as open as they come. We built this app to be modifiable,
customizable, and forkable. Go nuts - that's the whole point.
</p>
</div>
<div class="open-grid">
@@ -303,44 +305,43 @@ const mobileEndorsementRows = [
</div>
</div>
<div class="tile open-pitch">
<div class="open-pitch-copy">
<ul class="open-pitch-list">
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Change the UI.</strong> Restyle every surface to match your taste.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Add an agent.</strong> Wire in your own tools, models, and flows.</span>
</li>
<li>
<span class="open-pitch-mark" aria-hidden="true"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span>
<span><strong>Ship your own build.</strong> Self-host it or distribute it as your own.</span>
</li>
</ul>
<div class="open-stats">
<div class="tile open-stat">
<div class="open-stat-val">MIT</div>
<div class="open-stat-lbl">License · commercial-friendly</div>
</div>
<div class="open-pitch-footer">
<div class="open-pitch-meta">
<span>MIT licensed</span>
<span aria-hidden="true">·</span>
<span>{MARKETING_STATS.githubStars} stars</span>
</div>
<div class="open-pitch-actions">
<a class="btn btn-primary" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork on GitHub
</a>
<a class="open-source-link" href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">
Browse source
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
<div class="tile open-stat">
<div class="open-stat-val">TypeScript</div>
<div class="open-stat-lbl">End-to-end, strictly typed</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">1 monorepo</div>
<div class="open-stat-lbl">Desktop · web · server · harnesses</div>
</div>
<div class="tile open-stat">
<div class="open-stat-val">No telemetry</div>
<div class="open-stat-lbl">Unless you opt in. Full stop.</div>
</div>
</div>
</div>
<div class="open-ctas">
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/></svg>
Star on GitHub
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/fork" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.2"/><circle cx="18" cy="5" r="2.2"/><circle cx="12" cy="19" r="2.2"/><path d="M6 7.2v2A3 3 0 009 12.2h6A3 3 0 0018 9.2v-2M12 14v2.8"/></svg>
Fork the repo
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<a class="btn btn-ghost" href="https://github.com/pingdotgg/t3code/blob/main/CONTRIBUTING.md" target="_blank" rel="noopener noreferrer">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="4.5" width="19" height="15" rx="2"/><path d="M7 10l3 2-3 2M12 16h5"/></svg>
Read CONTRIBUTING.md
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
</div>
</div>
</section>
@@ -514,7 +515,7 @@ const mobileEndorsementRows = [
.hero-title {
font-size: clamp(38px, 5.6vw, 76px);
margin: 48px auto 22px;
margin: 28px auto 22px;
max-width: 20ch;
text-wrap: balance;
}
@@ -530,42 +531,12 @@ const mobileEndorsementRows = [
.hero-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
gap: 10px;
justify-content: center;
flex-wrap: wrap;
margin-bottom: 56px;
}
.hero-source-link {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--fg-muted);
font-size: 14px;
font-weight: 500;
letter-spacing: -0.01em;
transition: color 0.18s ease;
}
.hero-source-link:hover {
color: var(--fg);
}
.hero-source-mark {
flex-shrink: 0;
}
.hero-source-arrow {
flex-shrink: 0;
opacity: 0.6;
transition: transform 0.18s ease, opacity 0.18s ease;
}
.hero-source-link:hover .hero-source-arrow {
transform: translate(2px, -2px);
opacity: 1;
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
@@ -685,30 +656,6 @@ const mobileEndorsementRows = [
}
}
@media (max-width: 340px) {
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode {
left: 0;
}
.hero-float-mark.hf-cursor {
right: 0;
}
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
height: 30px;
}
}
.hero-preview {
max-width: 1180px;
margin: 0 auto;
@@ -812,11 +759,6 @@ const mobileEndorsementRows = [
margin-bottom: 18px;
}
.endorsements-count {
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.endorsements-head p {
color: var(--fg-muted);
font-size: 18px;
@@ -1020,11 +962,12 @@ const mobileEndorsementRows = [
text-align: center;
margin: 0 auto 56px;
}
.open-head p { margin: 0 auto; }
.open-grid {
display: grid;
grid-template-columns: 1.25fr 1fr;
gap: 20px;
gap: 20px; margin-bottom: 32px;
}
.open-term { padding: 0; overflow: hidden; }
@@ -1066,85 +1009,27 @@ const mobileEndorsementRows = [
animation: blink 1s steps(2) infinite;
}
.open-pitch {
padding: 32px;
display: flex;
flex-direction: column;
justify-content: center;
gap: 32px;
background:
radial-gradient(110% 75% at 100% 0%, var(--accent-dim), transparent 60%),
linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent);
}
.open-pitch-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 16px;
}
.open-pitch-list li {
display: flex;
align-items: flex-start;
gap: 12px;
font-size: 15px;
line-height: 1.5;
color: var(--fg-muted);
}
.open-pitch-list strong {
color: var(--fg);
font-weight: 600;
}
.open-pitch-mark {
flex: none;
.open-stats {
display: grid;
place-items: center;
width: 22px;
height: 22px;
margin-top: 1px;
border-radius: 7px;
color: var(--accent);
background: var(--accent-dim);
border: 1px solid color-mix(in srgb, var(--accent) 28%, transparent);
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.open-stat {
padding: 22px;
display: flex; flex-direction: column; gap: 6px;
}
.open-stat-val {
font-size: 22px; font-weight: 500;
letter-spacing: -0.015em;
}
.open-stat-lbl {
font-family: var(--font-mono); font-size: 10.5px;
color: var(--fg-dim); letter-spacing: 0.04em;
}
.open-pitch-footer {
display: flex;
flex-direction: column;
gap: 18px;
}
.open-pitch-meta {
display: flex;
align-items: center;
gap: 8px;
color: var(--fg-dim);
font-family: var(--font-mono);
font-size: 11px;
}
.open-pitch-actions {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.open-source-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-muted);
font-size: 13px;
font-weight: 500;
transition: color 0.18s ease;
}
.open-source-link:hover {
color: var(--fg);
.open-ctas {
display: flex; gap: 10px;
justify-content: center; flex-wrap: wrap;
}
/* ── Final CTA ────────────────────────────────────────── */
+6 -6
View File
@@ -49,10 +49,10 @@
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.2.0",
"@shikijs/langs": "4.2.0",
"@shikijs/themes": "4.2.0",
"@shikijs/core": "3.23.0",
"@shikijs/engine-javascript": "3.23.0",
"@shikijs/langs": "3.23.0",
"@shikijs/themes": "3.23.0",
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/mobile-markdown-text": "file:./modules/t3-markdown-text",
@@ -98,10 +98,10 @@
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.12",
"react-native-shiki-engine": "^0.3.9",
"react-native-svg": "15.15.4",
"react-native-worklets": "0.8.3",
"shiki": "4.2.0",
"shiki": "3.23.0",
"tailwind-merge": "^3.5.0",
"uniwind": "^1.6.2"
},
@@ -78,68 +78,4 @@ describe("review comment serialization", () => {
);
expect(segments[2]).toEqual(expect.objectContaining({ kind: "text", text: "\nAfter" }));
});
it("parses source-language review comments created by the web file viewer", () => {
const [segment] = parseReviewCommentMessageSegments(
[
'<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
"Clarify this.",
"```md",
"# Plan",
"- Step one",
"```",
"</review_comment>",
].join("\n"),
);
expect(segment).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({
filePath: "docs/plan.md",
fenceLanguage: "md",
diff: "# Plan\n- Step one",
}),
}),
);
});
it("keeps fenced examples in comment prose separate from the context fence", () => {
const [segment] = parseReviewCommentMessageSegments(
[
'<review_comment sectionId="section-1" sectionTitle="Working tree" filePath="src/app.ts" startIndex="0" endIndex="0" rangeLabel="+1">',
"Try this:",
"```ts",
"const value = 1;",
"```",
"Then retry.",
"```diff",
"@@ -0,0 +1,1 @@",
"+one",
"```",
"</review_comment>",
].join("\n"),
);
expect(segment).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({
text: ["Try this:", "```ts", "const value = 1;", "```", "Then retry."].join("\n"),
diff: "@@ -0,0 +1,1 @@\n+one",
}),
}),
);
});
it("round-trips greater-than signs in review attributes", () => {
const serialized = formatReviewCommentContext(
{ ...makeTarget(), sectionTitle: "Changes > 5" },
"Check this.",
);
const [comment] = parseReviewInlineComments(serialized);
expect(serialized).toContain('sectionTitle="Changes &gt; 5"');
expect(comment?.sectionTitle).toBe("Changes > 5");
});
});
@@ -21,7 +21,6 @@ export interface ReviewInlineComment {
readonly rangeLabel: string;
readonly text: string;
readonly diff: string;
readonly fenceLanguage?: string;
}
export type ReviewCommentMessageSegment =
@@ -39,7 +38,6 @@ let currentTarget: ReviewCommentTarget | null = null;
const listeners = new Set<() => void>();
const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
function emitChange() {
listeners.forEach((listener) => listener());
@@ -172,17 +170,12 @@ function formatReviewSelectedDiff(target: ReviewCommentTarget): string {
}
function escapeReviewCommentAttribute(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
}
function unescapeReviewCommentAttribute(value: string): string {
return value
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&");
}
@@ -202,19 +195,15 @@ function readNonNegativeInteger(value: string | undefined): number | null {
return Number(value);
}
function extractReviewCommentBody(rawBody: string): {
text: string;
language: string;
contents: string;
} {
const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
const match = matches.at(-1);
const fenceIndex = match?.index;
return {
text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
language: match?.[2]?.trim() || "diff",
contents: match?.[3] ?? "",
};
function extractReviewCommentText(rawBody: string): string {
const fenceIndex = rawBody.indexOf("```diff");
const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody;
return commentBody.trim();
}
function extractReviewCommentDiff(rawBody: string): string {
const match = rawBody.match(/```diff\s*\n([\s\S]*?)\n```/);
return match?.[1]?.trim() ?? "";
}
function parseReviewInlineComment(
@@ -230,7 +219,6 @@ function parseReviewInlineComment(
if (!filePath || !sectionId || startIndex === null || endIndex === null) {
return null;
}
const body = extractReviewCommentBody(rawBody);
return {
id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
@@ -240,20 +228,13 @@ function parseReviewInlineComment(
startIndex: Math.min(startIndex, endIndex),
endIndex: Math.max(startIndex, endIndex),
rangeLabel: attributes.rangeLabel?.trim() || "line",
text: body.text,
diff: body.contents,
fenceLanguage: body.language,
text: extractReviewCommentText(rawBody),
diff: extractReviewCommentDiff(rawBody),
};
}
export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
const rangeLabel = formatReviewSelectedRangeLabel(target);
const diff = formatReviewSelectedDiff(target);
const longestBacktickRun = Math.max(
0,
...Array.from(diff.matchAll(/`+/g), (match) => match[0].length),
);
const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
return [
[
"<review_comment",
@@ -266,9 +247,9 @@ export function formatReviewCommentContext(target: ReviewCommentTarget, comment:
">",
].join(""),
comment.trim(),
`${fence}diff`,
diff,
fence,
"```diff",
formatReviewSelectedDiff(target),
"```",
"</review_comment>",
].join("\n");
}
@@ -1193,9 +1193,6 @@ const ReviewCommentCard = memo(function ReviewCommentCard(props: {
});
function buildReviewCommentPatch(comment: ReviewInlineComment): string {
if ((comment.fenceLanguage ?? "diff") !== "diff") {
return "";
}
const diff = comment.diff.trim();
if (!diff) {
return "";
@@ -0,0 +1,191 @@
import { assert, describe, it } from "@effect/vitest";
import {
AuthSessionId,
RpcClientId,
type HostPowerSnapshot,
type ClientActivityReportInput,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
const nominalHostPower: HostPowerSnapshot = {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_NOW,
};
const constrainedHostPower: HostPowerSnapshot = {
...nominalHostPower,
lowPowerMode: "true",
stale: false,
};
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
return {
clientId: "client-1",
clientKind: "web",
visible: true,
focused: true,
recentlyInteracted: true,
scopes: [{ type: "vcs-status", cwd: "/repo" }],
ttlMs: 45_000,
observedAt: TEST_NOW,
...overrides,
};
}
function makeLayer(
hostPower: HostPowerSnapshot,
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
) {
const hostLayer = Layer.effect(
HostPowerMonitor.HostPowerMonitor,
Effect.gen(function* () {
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
let snapshot = hostPower;
return HostPowerMonitor.HostPowerMonitor.of({
snapshot: Effect.sync(() => snapshot),
report: (next) =>
Effect.sync(() => {
snapshot = next;
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
setDemandActive: () => Effect.void,
streamChanges: Stream.fromPubSub(changes),
});
}),
);
return BackgroundPolicy.layer.pipe(
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
);
}
describe("BackgroundPolicy", () => {
it.effect("records foreground scoped client demand", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 1);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(snapshot.shouldRunOpportunisticWork, true);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect("removes all leases for a disconnected websocket connection", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
yield* policy.removeRpcClient(RpcClientId.make(1));
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 0);
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
assert.equal(snapshot.shouldRunOpportunisticWork, false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 1);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(snapshot.shouldRunOpportunisticWork, false);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
);
it.effect("keeps background demand visible while preventing scoped work", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport({ focused: false, visible: false }),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 0);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect(
"performance profile allows background scoped work while a scoped lease is active",
() =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport({ focused: false, visible: false }),
);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
}).pipe(
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
),
);
it.effect("battery saver profile pauses scoped work on battery", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(
Effect.provide(
makeLayer(
{
...nominalHostPower,
onBattery: "true",
stale: false,
},
{ backgroundActivityProfile: "battery-saver" },
),
),
),
);
});
@@ -0,0 +1,289 @@
import {
type AuthSessionId,
type BackgroundPolicySnapshot,
type BackgroundScope,
type ClientActivityLease,
type ClientActivityReportInput,
type HostPowerSnapshot,
type RpcClientId,
} from "@t3tools/contracts";
import {
getBackgroundActivityPresetSettings,
resolveServerBackgroundActivitySettings,
type ResolvedBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
export interface BackgroundPolicyShape {
readonly reportClientActivity: (
sessionId: AuthSessionId,
rpcClientId: RpcClientId,
input: ClientActivityReportInput,
) => Effect.Effect<void>;
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
readonly removeSession: (sessionId: AuthSessionId) => Effect.Effect<void>;
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
}
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
"t3/background/BackgroundPolicy",
) {}
const DEFAULT_LEASE_TTL_MS = 45_000;
const MAX_LEASE_TTL_MS = 120_000;
function scopeKey(scope: BackgroundScope): string {
switch (scope.type) {
case "server-config":
case "diagnostics":
return scope.type;
case "provider-status":
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
case "vcs-status":
case "git-refs":
return `${scope.type}:${scope.cwd}`;
case "thread":
return `${scope.type}:${scope.threadId}`;
}
}
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
return DateTime.isGreaterThan(lease.expiresAt, now);
}
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
return isLeaseActive(lease, now) && lease.visible && lease.focused;
}
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
const key = scopeKey(scope);
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
}
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
}
function isHostConstrained(
hostPower: HostPowerSnapshot,
settings: ResolvedBackgroundActivitySettings,
): boolean {
if (
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
hasThermalPressure(hostPower)
) {
return true;
}
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
}
function isClientConstrained(
lease: ClientActivityLease,
settings: ResolvedBackgroundActivitySettings,
): boolean {
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
}
function leaseMayRunScopedWork(
lease: ClientActivityLease,
scope: BackgroundScope,
now: DateTime.Utc,
settings: ResolvedBackgroundActivitySettings,
): boolean {
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
if (!activeWithScope || isClientConstrained(lease, settings)) {
return false;
}
if (settings.profile === "performance") {
return true;
}
return isForegroundLease(lease, now);
}
function computeSnapshot(input: {
readonly hostPower: HostPowerSnapshot;
readonly leases: ReadonlyMap<string, ClientActivityLease>;
readonly now: DateTime.Utc;
readonly settings: ResolvedBackgroundActivitySettings;
readonly updatedAt: DateTime.Utc;
}): BackgroundPolicySnapshot {
const activeLeases = [...input.leases.values()].filter((lease) =>
isLeaseActive(lease, input.now),
);
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
const activeScopeKeys = new Set<string>();
for (const lease of activeLeases) {
for (const scope of lease.scopes) {
activeScopeKeys.add(scopeKey(scope));
}
}
return {
hostPower: input.hostPower,
leases: activeLeases,
activeForegroundLeaseCount: foregroundLeases.length,
activeScopeKeys: [...activeScopeKeys].toSorted(),
shouldRunOpportunisticWork:
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
!isHostConstrained(input.hostPower, input.settings),
updatedAt: input.updatedAt,
};
}
export const make = Effect.fn("background.policy.make")(function* () {
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
const serverSettings = yield* ServerSettingsService;
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
const backgroundActivitySettings = serverSettings.getSettings.pipe(
Effect.map(resolveServerBackgroundActivitySettings),
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
);
const snapshot = Effect.gen(function* () {
const [hostPower, leases, now, settings] = yield* Effect.all([
hostPowerMonitor.snapshot,
Ref.get(leasesRef),
DateTime.now,
backgroundActivitySettings,
]);
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
});
const publishSnapshot = snapshot.pipe(
Effect.tap((next) => hostPowerMonitor.setDemandActive(next.activeForegroundLeaseCount > 0)),
Effect.flatMap((next) => PubSub.publish(changes, next)),
);
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
sessionId,
rpcClientId,
input,
) =>
Effect.gen(function* () {
const ttlMs = Math.min(
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
MAX_LEASE_TTL_MS,
);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
const lease: ClientActivityLease = {
sessionId,
rpcClientId,
clientId: input.clientId,
clientKind: input.clientKind,
visible: input.visible,
focused: input.focused,
recentlyInteracted: input.recentlyInteracted,
...(input.appState !== undefined ? { appState: input.appState } : {}),
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
scopes: input.scopes,
updatedAt: now,
expiresAt,
};
yield* Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
next.set(`${rpcClientId}:${input.clientId}`, lease);
return next;
});
yield* publishSnapshot;
});
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
for (const key of next.keys()) {
if (key.startsWith(`${rpcClientId}:`)) {
next.delete(key);
}
}
return next;
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
const removeSession: BackgroundPolicyShape["removeSession"] = (sessionId) =>
Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
for (const [key, lease] of next) {
if (lease.sessionId === sessionId) {
next.delete(key);
}
}
return next;
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
Effect.gen(function* () {
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
if (isHostConstrained(current.hostPower, settings)) {
return false;
}
return current.leases.some((lease) =>
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
);
});
const shouldRunOpportunisticWork = Effect.map(
snapshot,
(current) => current.shouldRunOpportunisticWork,
);
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
Effect.forkScoped,
);
yield* Effect.forever(
Effect.sleep("15 seconds").pipe(
Effect.andThen(
Effect.gen(function* () {
const now = yield* DateTime.now;
yield* Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
for (const [key, lease] of next) {
if (!isLeaseActive(lease, now)) {
next.delete(key);
}
}
return next;
});
}),
),
Effect.andThen(publishSnapshot),
),
).pipe(Effect.forkScoped);
return BackgroundPolicy.of({
reportClientActivity,
removeRpcClient,
removeSession,
reportHostPowerState: hostPowerMonitor.report,
snapshot,
streamChanges: Stream.fromPubSub(changes),
hasDemand,
shouldRunScopeWork,
shouldRunOpportunisticWork,
});
});
export const layer = Layer.effect(BackgroundPolicy, make());
@@ -0,0 +1,211 @@
import {
type BackgroundBooleanState,
type HostPowerSnapshot,
type HostPowerThermalState,
} from "@t3tools/contracts";
import {
getBackgroundActivityPresetSettings,
resolveServerBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as ProcessRunner from "../processRunner.ts";
import { ServerSettingsService } from "../serverSettings.ts";
export interface HostPowerMonitorShape {
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
readonly setDemandActive: (active: boolean) => Effect.Effect<void>;
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
}
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
"t3/background/HostPowerMonitor",
) {}
const COMMAND_TIMEOUT = Duration.seconds(3);
export const makeUnknownSnapshot = (
source: HostPowerSnapshot["source"],
updatedAt: HostPowerSnapshot["updatedAt"],
): HostPowerSnapshot => ({
source,
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt,
});
function boolState(value: boolean | null): BackgroundBooleanState {
if (value === null) return "unknown";
return value ? "true" : "false";
}
function parseIdleSeconds(ioregOutput: string): number | null {
const match = /"HIDIdleTime"\s*=\s*(\d+)/u.exec(ioregOutput);
if (!match) return null;
const nanoseconds = Number(match[1]);
return Number.isFinite(nanoseconds) ? Math.floor(nanoseconds / 1_000_000_000) : null;
}
function parseOnBattery(pmsetBatteryOutput: string): boolean | null {
if (/Now drawing from 'Battery Power'/iu.test(pmsetBatteryOutput)) return true;
if (/Now drawing from 'AC Power'/iu.test(pmsetBatteryOutput)) return false;
return null;
}
function parseLowPowerMode(pmsetOutput: string): boolean | null {
const match = /^\s*lowpowermode\s+([01])\s*$/imu.exec(pmsetOutput);
if (!match) return null;
return match[1] === "1";
}
function parseThermalState(_output: string): HostPowerThermalState {
// The stable shell adapter intentionally does not parse `pmset thermlog`;
// native adapters can provide this without depending on human-formatted text.
return "unknown";
}
function runOptional(
runner: ProcessRunner.ProcessRunnerShape,
command: string,
args: ReadonlyArray<string>,
) {
return runner
.run({
command,
args,
timeout: COMMAND_TIMEOUT,
timeoutBehavior: "timedOutResult",
outputMode: "truncate",
maxOutputBytes: 32_000,
})
.pipe(Effect.option);
}
const readMacShellSnapshot = Effect.fn("background.hostPower.readMacShellSnapshot")(function* () {
const runner = yield* ProcessRunner.ProcessRunner;
const updatedAt = yield* DateTime.now;
const [idleOutput, batteryOutput, pmsetOutput] = yield* Effect.all(
[
runOptional(runner, "ioreg", ["-c", "IOHIDSystem"]),
runOptional(runner, "pmset", ["-g", "batt"]),
runOptional(runner, "pmset", ["-g"]),
],
{ concurrency: "unbounded" },
);
const idleSeconds = idleOutput._tag === "Some" ? parseIdleSeconds(idleOutput.value.stdout) : null;
const onBattery =
batteryOutput._tag === "Some" ? parseOnBattery(batteryOutput.value.stdout) : null;
const lowPowerMode =
pmsetOutput._tag === "Some" ? parseLowPowerMode(pmsetOutput.value.stdout) : null;
return {
source: "node-macos-shell",
idle: boolState(idleSeconds === null ? null : idleSeconds >= 60),
idleSeconds,
locked: "unknown",
suspended: false,
onBattery: boolState(onBattery),
lowPowerMode: boolState(lowPowerMode),
thermalState: parseThermalState(""),
stale: false,
updatedAt,
} satisfies HostPowerSnapshot;
});
export const make = Effect.fn("background.hostPower.make")(function* (
initialSource: HostPowerSnapshot["source"] = "unknown",
) {
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
const latestRef = yield* Ref.make(initial);
const demandActiveRef = yield* Ref.make(false);
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
const report: HostPowerMonitorShape["report"] = (snapshot) =>
Ref.set(latestRef, snapshot).pipe(
Effect.andThen(PubSub.publish(changes, snapshot)),
Effect.asVoid,
);
return HostPowerMonitor.of({
snapshot: Ref.get(latestRef),
report,
setDemandActive: (active) => Ref.set(demandActiveRef, active),
streamChanges: Stream.fromPubSub(changes),
});
});
const unknownLayer = Layer.effect(HostPowerMonitor, make("unknown"));
const linuxLayer = Layer.effect(HostPowerMonitor, make("node-linux"));
const windowsLayer = Layer.effect(HostPowerMonitor, make("node-windows"));
const macShellLayer = Layer.effect(
HostPowerMonitor,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const monitor = yield* make("node-macos-shell");
const demandActiveRef = yield* Ref.make(true);
const setDemandActive: HostPowerMonitorShape["setDemandActive"] = (active) =>
Ref.set(demandActiveRef, active);
const getPollInterval = Effect.gen(function* () {
const demandActive = yield* Ref.get(demandActiveRef);
const settings = yield* serverSettings.getSettings.pipe(
Effect.map(resolveServerBackgroundActivitySettings),
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
);
return demandActive
? settings.hostPowerMonitorActiveInterval
: settings.hostPowerMonitorIdleInterval;
});
const adaptiveMonitor = HostPowerMonitor.of({
snapshot: monitor.snapshot,
report: monitor.report,
setDemandActive,
streamChanges: monitor.streamChanges,
});
yield* readMacShellSnapshot().pipe(
Effect.flatMap(adaptiveMonitor.report),
Effect.ignoreCause({ log: true }),
);
yield* Effect.forever(
getPollInterval.pipe(
Effect.flatMap((interval) => Effect.sleep(Duration.max(interval, Duration.seconds(5)))),
Effect.andThen(readMacShellSnapshot()),
Effect.flatMap(adaptiveMonitor.report),
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
return adaptiveMonitor;
}),
).pipe(Layer.provide(ProcessRunner.layer));
export const layer = Layer.unwrap(
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
switch (platform) {
case "darwin":
return macShellLayer;
case "linux":
return linuxLayer;
case "win32":
return windowsLayer;
default:
return unknownLayer;
}
}),
);
+1 -3
View File
@@ -1361,9 +1361,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
},
);
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)], {
concurrency: "unbounded",
});
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
});
const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
+1 -55
View File
@@ -1,11 +1,10 @@
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import { HttpServerResponse } from "effect/unstable/http";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -49,59 +48,6 @@ it("normalizes empty successful notification responses to accepted", () => {
expect(resultResponse.status).toBe(200);
});
it.effect("terminates HTTP MCP sessions with DELETE", () =>
Effect.scoped(
Effect.gen(function* () {
const serverLayer = McpServer.layerHttp({
name: "MCP termination test",
version: "1.0.0",
path: "/mcp",
});
yield* HttpRouter.serve(serverLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(Layer.build);
const httpClient = yield* HttpClient.HttpClient;
const initializeResponse = yield* httpClient.post("/mcp", {
headers: { accept: "application/json, text/event-stream" },
body: HttpBody.text(
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
"application/json",
),
});
const sessionId = initializeResponse.headers["mcp-session-id"];
expect(initializeResponse.status).toBe(200);
expect(sessionId).not.toBeNull();
const missingSessionResponse = yield* httpClient.del("/mcp");
expect(missingSessionResponse.status).toBe(400);
const unknownSessionResponse = yield* httpClient.del("/mcp", {
headers: { "mcp-session-id": "unknown-session" },
});
expect(unknownSessionResponse.status).toBe(404);
const terminateResponse = yield* httpClient.del("/mcp", {
headers: { "mcp-session-id": sessionId! },
});
expect(terminateResponse.status).toBe(204);
const reusedSessionResponse = yield* httpClient.post("/mcp", {
headers: {
accept: "application/json, text/event-stream",
"mcp-session-id": sessionId!,
},
body: HttpBody.text(
`{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
"application/json",
),
});
expect(reusedSessionResponse.status).toBe(404);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("registers annotated tools and preserves authenticated request context", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -25,7 +25,9 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
import {
@@ -52,7 +54,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
function isClaudeNativeCommandPath(commandPath: string): boolean {
@@ -77,13 +78,15 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type ClaudeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -176,7 +179,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -22,7 +22,6 @@
* @module provider/Drivers/CodexDriver
*/
import { CodexSettings, 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";
@@ -33,7 +32,9 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
@@ -55,7 +56,6 @@ import {
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const DRIVER_KIND = ProviderDriverKind.make("codex");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makePackageManagedProviderMaintenanceResolver({
provider: DRIVER_KIND,
npmPackageName: "@openai/codex",
@@ -69,13 +69,15 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
* registered driver and the runtime satisfies them once.
*/
export type CodexDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
/**
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
@@ -176,7 +178,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -12,7 +12,6 @@
* @module provider/Drivers/CursorDriver
*/
import { CursorSettings, 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";
@@ -23,6 +22,8 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
@@ -48,7 +49,6 @@ import {
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
@@ -60,13 +60,15 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
);
export type CursorDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -148,8 +150,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
publishSnapshot,
stampIdentity,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
}).pipe(
Effect.mapError(
(cause) =>
@@ -1,5 +1,4 @@
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";
@@ -9,7 +8,9 @@ import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
@@ -35,7 +36,6 @@ import {
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,
@@ -44,13 +44,15 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
);
export type GrokDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -125,7 +127,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
publishSnapshot,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -13,7 +13,6 @@
* @module provider/Drivers/OpenCodeDriver
*/
import { OpenCodeSettings, 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";
@@ -24,7 +23,9 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
@@ -50,7 +51,6 @@ import {
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DRIVER_KIND = ProviderDriverKind.make("opencode");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
const normalized = normalizeCommandPath(commandPath);
@@ -73,6 +73,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type OpenCodeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -80,7 +81,8 @@ export type OpenCodeDriverEnv =
| OpenCodeRuntime
| Path.Path
| ProviderEventLoggers
| ServerConfig;
| ServerConfig
| ServerSettingsService;
const withInstanceIdentity =
(input: {
@@ -155,7 +157,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -34,11 +34,15 @@ import {
type ProviderInstanceConfigMap,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
@@ -55,6 +59,38 @@ const TestHttpClientLive = Layer.succeed(
),
);
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
reportClientActivity: () => Effect.void,
removeRpcClient: () => Effect.void,
removeSession: () => Effect.void,
reportHostPowerState: () => Effect.void,
snapshot: Effect.succeed({
hostPower: {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_EPOCH,
},
leases: [],
activeForegroundLeaseCount: 0,
activeScopeKeys: [],
shouldRunOpportunisticWork: true,
updatedAt: TEST_EPOCH,
}),
streamChanges: Stream.empty,
hasDemand: () => Effect.succeed(true),
shouldRunScopeWork: () => Effect.succeed(true),
shouldRunOpportunisticWork: Effect.succeed(true),
});
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
enabled: false,
binaryPath: "codex",
@@ -107,6 +143,8 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
@@ -244,6 +282,8 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
@@ -32,6 +33,7 @@ import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
@@ -64,6 +66,7 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const TestHttpClientLive = Layer.succeed(
HttpClient.HttpClient,
@@ -72,6 +75,36 @@ const TestHttpClientLive = Layer.succeed(
),
);
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
reportClientActivity: () => Effect.void,
removeRpcClient: () => Effect.void,
removeSession: () => Effect.void,
reportHostPowerState: () => Effect.void,
snapshot: Effect.succeed({
hostPower: {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_EPOCH,
},
leases: [],
activeForegroundLeaseCount: 0,
activeScopeKeys: [],
shouldRunOpportunisticWork: true,
updatedAt: TEST_EPOCH,
}),
streamChanges: Stream.empty,
hasDemand: () => Effect.succeed(true),
shouldRunScopeWork: () => Effect.succeed(true),
shouldRunOpportunisticWork: Effect.succeed(true),
});
function selectDescriptor(
id: string,
label: string,
@@ -806,6 +839,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
prefix: "t3-provider-registry-merged-persist-",
}),
),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
@@ -900,6 +934,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
prefix: "t3-provider-registry-refresh-failure-",
}),
),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
@@ -1004,6 +1039,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
prefix: "t3-provider-registry-sync-failure-",
}),
),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
@@ -1101,6 +1137,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
// NO spawner mock — `ChildProcessSpawner` is supplied by the
// outer `NodeServices.layer` on `it.layer(...)` and will
// genuinely spawn a subprocess. The missing-binary ENOENT is
@@ -1193,6 +1230,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
}),
),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
Scope.provide(scope),
@@ -1301,6 +1339,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
Scope.provide(scope),
@@ -1354,6 +1393,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
@@ -1,16 +1,22 @@
import { describe, it, assert } from "@effect/vitest";
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const fastModeCapabilities = createModelCapabilities({
optionDescriptors: [
{
@@ -87,6 +93,44 @@ const refreshedSnapshotSecond: ServerProvider = {
message: "Refreshed provider availability again.",
};
function makeBackgroundPolicyLayer(shouldRunScopeWork: boolean) {
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
reportClientActivity: () => Effect.void,
removeRpcClient: () => Effect.void,
removeSession: () => Effect.void,
reportHostPowerState: () => Effect.void,
snapshot: Effect.succeed({
hostPower: {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_EPOCH,
},
leases: [],
activeForegroundLeaseCount: 0,
activeScopeKeys: [],
shouldRunOpportunisticWork: true,
updatedAt: TEST_EPOCH,
}),
streamChanges: Stream.empty,
hasDemand: () => Effect.succeed(shouldRunScopeWork),
shouldRunScopeWork: () => Effect.succeed(shouldRunScopeWork),
shouldRunOpportunisticWork: Effect.succeed(shouldRunScopeWork),
});
}
const BackgroundPolicyAlwaysRunLayer = makeBackgroundPolicyLayer(true);
const BackgroundPolicyNeverRunLayer = makeBackgroundPolicyLayer(false);
const ServerSettingsTestLayer = ServerSettingsService.layerTest();
const AlwaysRunTestLayer = Layer.merge(BackgroundPolicyAlwaysRunLayer, ServerSettingsTestLayer);
const NeverRunTestLayer = Layer.merge(BackgroundPolicyNeverRunLayer, ServerSettingsTestLayer);
const enrichedSnapshotSecond: ServerProvider = {
...refreshedSnapshotSecond,
checkedAt: "2026-04-10T00:00:04.000Z",
@@ -140,7 +184,38 @@ describe("makeManagedServerProvider", () => {
assert.deepStrictEqual(latest, refreshedSnapshot);
assert.strictEqual(yield* Ref.get(checkCalls), 1);
}),
),
).pipe(Effect.provide(AlwaysRunTestLayer)),
);
it.effect("skips periodic provider refreshes without foreground provider-status demand", () =>
Effect.scoped(
Effect.gen(function* () {
const checkCalls = yield* Ref.make(0);
const initialCheckDone = yield* Deferred.make<void>();
yield* makeManagedServerProvider<TestSettings>({
maintenanceCapabilities,
getSettings: Effect.succeed({ enabled: true }),
streamSettings: Stream.empty,
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
initialSnapshot: () => Effect.succeed(initialSnapshot),
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
Effect.tap((count) =>
count === 1
? Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.as(refreshedSnapshot),
),
refreshInterval: "1 second",
});
yield* Deferred.await(initialCheckDone);
yield* TestClock.adjust("1 second");
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(checkCalls), 1);
}),
).pipe(Effect.provide(Layer.mergeAll(NeverRunTestLayer, TestClock.layer()))),
);
it.effect("reruns the provider check when streamed settings change", () =>
@@ -185,7 +260,7 @@ describe("makeManagedServerProvider", () => {
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
assert.strictEqual(yield* Ref.get(checkCalls), 2);
}),
),
).pipe(Effect.provide(AlwaysRunTestLayer)),
);
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
@@ -223,7 +298,7 @@ describe("makeManagedServerProvider", () => {
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
assert.deepStrictEqual(latest, enrichedSnapshot);
}),
),
).pipe(Effect.provide(AlwaysRunTestLayer)),
);
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
@@ -284,6 +359,6 @@ describe("makeManagedServerProvider", () => {
]);
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
}),
),
).pipe(Effect.provide(AlwaysRunTestLayer)),
);
});
@@ -1,4 +1,9 @@
import type { ServerProvider } from "@t3tools/contracts";
import {
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
type ServerProvider,
ServerSettingsError,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
@@ -9,8 +14,9 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Semaphore from "effect/Semaphore";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
import { ServerSettingsError } from "@t3tools/contracts";
interface ProviderSnapshotState {
readonly snapshot: ServerProvider;
@@ -33,7 +39,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
}) => Effect.Effect<void>;
readonly refreshInterval?: Duration.Input;
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
}): Effect.fn.Return<
ServerProviderShape,
ServerSettingsError,
Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
> {
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const serverSettings = yield* ServerSettingsService;
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
@@ -134,13 +146,45 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
const hasProviderStatusDemand = Effect.gen(function* () {
const state = yield* Ref.get(snapshotStateRef);
const instanceId = state.snapshot.instanceId;
const [genericDemand, instanceDemand] = yield* Effect.all([
backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
]);
return genericDemand || instanceDemand;
});
const getRefreshInterval = input.refreshInterval
? Effect.succeed(input.refreshInterval)
: serverSettings.getSettings.pipe(
Effect.map(
(settings) =>
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
),
Effect.catch(() => Effect.succeed(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
);
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
).pipe(Effect.forkScoped);
yield* Effect.forever(
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
Effect.flatMap(() => refreshSnapshot()),
getRefreshInterval.pipe(
Effect.flatMap((refreshInterval) =>
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
? Effect.sleep("60 seconds")
: Effect.sleep(refreshInterval).pipe(
Effect.flatMap(() =>
hasProviderStatusDemand.pipe(
Effect.flatMap((shouldRefresh) =>
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
),
),
),
),
),
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
+32
View File
@@ -69,6 +69,7 @@ import { vi } from "vite-plus/test";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import type { ServerConfigShape } from "./config.ts";
import { deriveServerPaths, ServerConfig } from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
@@ -772,6 +773,37 @@ const buildAppUnderTest = (options?: {
...options?.layers?.serverRuntimeStartup,
}),
),
Layer.provide(
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
reportClientActivity: () => Effect.void,
removeRpcClient: () => Effect.void,
removeSession: () => Effect.void,
reportHostPowerState: () => Effect.void,
snapshot: Effect.succeed({
hostPower: {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_EPOCH,
},
leases: [],
activeForegroundLeaseCount: 0,
activeScopeKeys: [],
shouldRunOpportunisticWork: false,
updatedAt: TEST_EPOCH,
}),
streamChanges: Stream.empty,
hasDemand: () => Effect.succeed(false),
shouldRunScopeWork: () => Effect.succeed(false),
shouldRunOpportunisticWork: Effect.succeed(false),
}),
),
Layer.provide(
Layer.mock(ServerEnvironment)({
getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId),
+9 -1
View File
@@ -5,6 +5,8 @@ import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { ServerConfig } from "./config.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
@@ -110,6 +112,11 @@ const PtyAdapterLive = Layer.unwrap(
}),
);
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
Layer.provide(HostPowerMonitor.layer),
Layer.provideMerge(ServerSettingsLive),
);
const RelayClientLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
@@ -285,6 +292,7 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(GitLayerLive),
@@ -312,7 +320,6 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// no longer transitively provides it. Exposing it at the runtime level
// keeps a single Live for all opencode consumers.
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(ProjectFaviconResolverLayerLive),
Layer.provideMerge(RepositoryIdentityResolverLive),
@@ -329,6 +336,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
// Misc.
Layer.provideMerge(BackgroundLayerLive),
Layer.provideMerge(ProcessDiagnostics.layer),
Layer.provideMerge(ProcessResourceMonitor.layer),
Layer.provideMerge(TraceDiagnostics.layer),
+8
View File
@@ -462,6 +462,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
backgroundActivity: {
schemaVersion: 1,
profile: "custom",
baseProfile: "balanced",
overrides: {
automaticGitFetchInterval: 10_000,
},
},
automaticGitFetchInterval: 10_000,
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
+7 -1
View File
@@ -135,13 +135,17 @@ export class ServerSettingsService extends Context.Service<
Layer.effect(
ServerSettingsService,
Effect.gen(function* () {
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
overrides;
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
const initialSettings = yield* normalizeServerSettings({
...merged,
...(automaticGitFetchInterval !== undefined
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
: {}),
...(providerHealthRefreshInterval !== undefined
? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
@@ -216,7 +220,9 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"backgroundActivity",
"automaticGitFetchInterval",
"providerHealthRefreshInterval",
"textGenerationModelSelection",
]);
+20 -34
View File
@@ -216,7 +216,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("makes background upstream status fetches non-interactive", () =>
it.effect("disables SSH askpass for background upstream status fetches", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const tempDir = yield* makeTmpDir("git-vcs-driver-ssh-env-");
@@ -225,26 +225,15 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
const pathService = yield* Path.Path;
const sshLogPath = pathService.join(tempDir, "ssh-env.txt");
const sshWrapperPath = pathService.join(tempDir, "ssh-wrapper.sh");
const envKeys = [
"GCM_INTERACTIVE",
"GIT_ASKPASS",
"GIT_SSH",
"GIT_TERMINAL_PROMPT",
"SSH_ASKPASS",
"SSH_ASKPASS_REQUIRE",
"T3_TEST_SSH_ASKPASS_LOG",
] as const;
const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
const previousGitSsh = process.env.GIT_SSH;
const previousAskpassRequire = process.env.SSH_ASKPASS_REQUIRE;
const previousAskpassLog = process.env.T3_TEST_SSH_ASKPASS_LOG;
yield* fileSystem.writeFileString(
sshWrapperPath,
[
"#!/bin/sh",
'printf "GCM_INTERACTIVE=%s\\n" "${GCM_INTERACTIVE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "GIT_ASKPASS=%s\\n" "${GIT_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "GIT_TERMINAL_PROMPT=%s\\n" "${GIT_TERMINAL_PROMPT:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "SSH_ASKPASS=%s\\n" "${SSH_ASKPASS:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "SSH_ASKPASS_REQUIRE=%s\\n" "${SSH_ASKPASS_REQUIRE:-}" >> "$T3_TEST_SSH_ASKPASS_LOG"',
'printf "%s\\n" "${SSH_ASKPASS_REQUIRE:-}" > "$T3_TEST_SSH_ASKPASS_LOG"',
"exit 1",
"",
].join("\n"),
@@ -256,32 +245,29 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
yield* Effect.gen(function* () {
process.env.GIT_SSH = sshWrapperPath;
process.env.GCM_INTERACTIVE = "always";
process.env.GIT_ASKPASS = "git-askpass";
process.env.GIT_TERMINAL_PROMPT = "1";
process.env.SSH_ASKPASS = "ssh-askpass";
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
"GCM_INTERACTIVE=never",
"GIT_ASKPASS=",
"GIT_TERMINAL_PROMPT=0",
"SSH_ASKPASS=",
"SSH_ASKPASS_REQUIRE=never",
]);
assert.equal((yield* fileSystem.readFileString(sshLogPath)).trim(), "never");
}).pipe(
Effect.ensuring(
Effect.sync(() => {
for (const key of envKeys) {
const previous = previousEnv.get(key);
if (previous === undefined) {
delete process.env[key];
} else {
process.env[key] = previous;
}
if (previousGitSsh === undefined) {
delete process.env.GIT_SSH;
} else {
process.env.GIT_SSH = previousGitSsh;
}
if (previousAskpassRequire === undefined) {
delete process.env.SSH_ASKPASS_REQUIRE;
} else {
process.env.SSH_ASKPASS_REQUIRE = previousAskpassRequire;
}
if (previousAskpassLog === undefined) {
delete process.env.T3_TEST_SSH_ASKPASS_LOG;
} else {
process.env.T3_TEST_SSH_ASKPASS_LOG = previousAskpassLog;
}
}),
),
-4
View File
@@ -54,10 +54,6 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
GCM_INTERACTIVE: "never",
GIT_ASKPASS: "",
GIT_TERMINAL_PROMPT: "0",
SSH_ASKPASS: "",
SSH_ASKPASS_REQUIRE: "never",
} satisfies NodeJS.ProcessEnv);
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
@@ -1,6 +1,7 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Deferred from "effect/Deferred";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -12,16 +13,19 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type {
BackgroundScope,
VcsStatusLocalResult,
VcsStatusRemoteResult,
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { GitManagerError } from "@t3tools/contracts";
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const baseLocalStatus: VcsStatusLocalResult = {
isRepo: true,
sourceControlProvider: {
@@ -58,6 +62,7 @@ function makeTestLayer(state: {
}) {
return VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
@@ -83,6 +88,38 @@ function makeTestLayer(state: {
);
}
function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
reportClientActivity: () => Effect.void,
removeRpcClient: () => Effect.void,
removeSession: () => Effect.void,
reportHostPowerState: () => Effect.void,
snapshot: Effect.succeed({
hostPower: {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_EPOCH,
},
leases: [],
activeForegroundLeaseCount: 0,
activeScopeKeys: [],
shouldRunOpportunisticWork: false,
updatedAt: TEST_EPOCH,
}),
streamChanges: Stream.empty,
hasDemand: () => Effect.succeed(true),
shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
shouldRunOpportunisticWork: Effect.succeed(true),
});
}
describe("VcsStatusBroadcaster", () => {
it.effect("reuses the cached VCS status across repeated reads", () => {
const state = {
@@ -150,71 +187,6 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
failRemoteStatus: false,
};
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.suspend(() => {
state.remoteStatusCalls += 1;
return state.failRemoteStatus
? Effect.fail(
new GitManagerError({
operation: "VcsStatusBroadcaster.test",
detail: "remote status failed",
}),
)
: Effect.succeed(state.currentRemoteStatus);
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
}),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/partial-refresh",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 3,
};
state.failRemoteStatus = true;
const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.isTrue(Exit.isFailure(refreshExit));
assert.deepStrictEqual(cached, baseStatus);
}).pipe(Effect.provide(testLayer));
});
it.effect("refreshes only the cached local snapshot when requested", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -263,6 +235,7 @@ describe("VcsStatusBroadcaster", () => {
};
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: (input) =>
@@ -442,6 +415,57 @@ describe("VcsStatusBroadcaster", () => {
);
});
it.effect("does not start automatic remote refreshes without foreground client demand", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => false)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const snapshot = yield* Stream.runHead(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
),
);
assert.isTrue(Option.isSome(snapshot));
assert.equal(state.remoteStatusCalls, 0);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(testLayer));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -455,6 +479,7 @@ describe("VcsStatusBroadcaster", () => {
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
+49 -73
View File
@@ -21,6 +21,7 @@ import type {
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
@@ -98,6 +99,7 @@ export const layer = Layer.effect(
VcsStatusBroadcaster,
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const fs = yield* FileSystem.FileSystem;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<VcsStatusChange>(),
@@ -179,48 +181,6 @@ export const layer = Layer.effect(
},
);
const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
cwd: string,
local: VcsStatusLocalResult,
remote: VcsStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
local: nextLocal,
remote: nextRemote,
});
return [
previous.local?.fingerprint !== nextLocal.fingerprint ||
previous.remote?.fingerprint !== nextRemote.fingerprint,
nextCache,
] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "snapshot",
local,
remote,
},
});
}
return mergeGitStatusParts(local, remote);
});
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
cwd: string,
) {
@@ -228,6 +188,13 @@ export const layer = Layer.effect(
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("VcsStatusBroadcaster.loadRemoteStatus")(function* (
cwd: string,
) {
const remote = yield* workflow.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
cwd: string,
) {
@@ -238,39 +205,36 @@ export const layer = Layer.effect(
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadRemoteStatus")(
function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
},
);
const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
"VcsStatusBroadcaster.getStatus",
)(function* (input) {
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const cached = yield* getCachedStatus(cwd);
if (cached?.local && cached.remote) {
return mergeGitStatusParts(cached.local.value, cached.remote.value);
}
const [local, remote] = yield* Effect.all(
[
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(cwd),
getOrLoadRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
},
);
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshLocalStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
return yield* refreshLocalStatusCore(cwd);
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
@@ -285,19 +249,16 @@ export const layer = Layer.effect(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
yield* Effect.all(
[workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)],
{ concurrency: "unbounded", discard: true },
);
const [local, remote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
const [local, remote] = yield* Effect.all([
refreshLocalStatus(cwd),
refreshRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
});
const makeRemoteRefreshLoop = (
cwd: string,
scopeCwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) => {
@@ -312,6 +273,14 @@ export const layer = Layer.effect(
return activeInterval;
}
const shouldRun = yield* backgroundPolicy.shouldRunScopeWork({
type: "vcs-status",
cwd: scopeCwd,
});
if (!shouldRun) {
return activeInterval;
}
const exit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit);
if (Exit.isSuccess(exit)) {
yield* Ref.set(consecutiveFailuresRef, 0);
@@ -354,6 +323,7 @@ export const layer = Layer.effect(
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
scopeCwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) {
@@ -368,7 +338,12 @@ export const layer = Layer.effect(
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
return makeRemoteRefreshLoop(
cwd,
scopeCwd,
automaticRemoteRefreshInterval,
refreshImmediately,
).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
@@ -420,6 +395,7 @@ export const layer = Layer.effect(
const initialRemote = cachedStatus?.remote?.value ?? null;
yield* retainRemotePoller(
cwd,
input.cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
+42 -2
View File
@@ -42,6 +42,7 @@ import {
type RelayClientInstallProgressEvent,
OrchestrationReplayEventsError,
FilesystemBrowseError,
RpcClientId,
AssetAccessError,
EnvironmentAuthorizationError,
ThreadId,
@@ -52,6 +53,7 @@ import {
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import { clamp } from "effect/Number";
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
@@ -88,6 +90,7 @@ import { ReviewService } from "./review/ReviewService.ts";
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import type { AuthenticatedSession } from "./auth/EnvironmentAuth.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
@@ -277,10 +280,13 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
const serverEnvironment = yield* ServerEnvironment;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.automaticGitFetchInterval),
Effect.map(
(settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
detail: cause.message,
@@ -1103,6 +1109,26 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverReportClientActivity]: (input, metadata) =>
observeRpcEffect(
WS_METHODS.serverReportClientActivity,
backgroundPolicy.reportClientActivity(
currentSessionId,
RpcClientId.make(metadata.client.id),
input,
),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverReportHostPowerState]: (input) =>
observeRpcEffect(
WS_METHODS.serverReportHostPowerState,
backgroundPolicy.reportHostPowerState(input),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverGetBackgroundPolicy]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {
"rpc.aggregate": "server",
}),
[WS_METHODS.cloudGetRelayClientStatus]: (_input) =>
observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, {
"rpc.aggregate": "cloud",
@@ -1621,6 +1647,15 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
}),
{ "rpc.aggregate": "auth" },
),
[WS_METHODS.subscribeBackgroundPolicy]: (_input) =>
observeRpcStream(
WS_METHODS.subscribeBackgroundPolicy,
Stream.concat(
Stream.unwrap(Effect.map(backgroundPolicy.snapshot, Stream.make)),
backgroundPolicy.streamChanges,
),
{ "rpc.aggregate": "server" },
),
});
}),
);
@@ -1634,6 +1669,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
@@ -1675,7 +1711,11 @@ export const websocketRpcRouteLayer = Layer.unwrap(
return yield* Effect.acquireUseRelease(
sessions.markConnected(session.sessionId),
() => rpcWebSocketHttpEffect,
() => sessions.markDisconnected(session.sessionId),
() =>
Effect.all([
sessions.markDisconnected(session.sessionId),
backgroundPolicy.removeSession(session.sessionId),
]).pipe(Effect.asVoid),
);
}).pipe(
Effect.catchTags({
@@ -69,26 +69,6 @@ describe("ChatMarkdown", () => {
document.body.innerHTML = "";
});
it("makes task-list checkboxes interactive when a change handler is provided", async () => {
const onTaskListChange = vi.fn();
const screen = await render(
<ChatMarkdown
text={"- [ ] Ship it"}
cwd="/repo/project"
onTaskListChange={onTaskListChange}
/>,
);
try {
const checkbox = page.getByRole("checkbox", { name: "Toggle task" });
await expect.element(checkbox).not.toBeDisabled();
await checkbox.click();
expect(onTaskListChange).toHaveBeenCalledWith({ markerOffset: 2, checked: true });
} finally {
await screen.unmount();
}
});
it("rewrites file uri hrefs into direct paths before rendering", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
@@ -288,13 +268,6 @@ describe("ChatMarkdown", () => {
).toMatchObject({
isOpen: true,
activeSurfaceId: "file:apps/web/src/components/ChatMarkdown.tsx",
surfaces: [
expect.objectContaining({
relativePath: "apps/web/src/components/ChatMarkdown.tsx",
revealLine: 978,
revealRequestId: 1,
}),
],
});
expect(openInPreferredEditorMock).not.toHaveBeenCalled();
expect(openFileInPreviewMock).not.toHaveBeenCalled();
+4 -59
View File
@@ -91,7 +91,6 @@ interface ChatMarkdownProps {
text: string;
cwd: string | undefined;
threadRef?: ScopedThreadRef | undefined;
onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
isStreaming?: boolean;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
className?: string;
@@ -109,17 +108,6 @@ const highlightedCodeCache = new LRUCache<string>(
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
);
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
const firstLineEnd = markdown.indexOf("\n", listItemStart);
const firstLine = markdown.slice(
listItemStart,
firstLineEnd === -1 ? markdown.length : firstLineEnd,
);
const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);
if (!match?.[1]) return null;
return listItemStart + firstLine.indexOf(match[1]);
}
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
...defaultSchema,
attributes: {
@@ -671,7 +659,6 @@ interface MarkdownFileLinkProps {
iconPath: string;
displayPath: string;
workspaceRelativePath: string | null;
line?: number | undefined;
label: string;
copyMarkdown: string;
theme: "light" | "dark";
@@ -996,7 +983,6 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
iconPath,
displayPath,
workspaceRelativePath,
line,
label,
copyMarkdown,
theme,
@@ -1029,8 +1015,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
handleOpenInEditor();
return;
}
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line);
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath);
}, [handleOpenInEditor, threadRef, workspaceRelativePath]);
const handleOpenInBrowser = useCallback(() => {
if (!threadRef) return;
@@ -1171,7 +1157,6 @@ function areMarkdownFileLinkPropsEqual(
previous.iconPath === next.iconPath &&
previous.displayPath === next.displayPath &&
previous.workspaceRelativePath === next.workspaceRelativePath &&
previous.line === next.line &&
previous.label === next.label &&
previous.copyMarkdown === next.copyMarkdown &&
previous.theme === next.theme &&
@@ -1185,7 +1170,6 @@ function ChatMarkdown({
text,
cwd,
threadRef,
onTaskListChange,
isStreaming = false,
skills = EMPTY_MARKDOWN_SKILLS,
className,
@@ -1231,44 +1215,8 @@ function ChatMarkdown({
p({ node: _node, children, ...props }) {
return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
},
li({ node, children, ...props }) {
const listItemStart = node?.position?.start.offset;
const markerOffset =
typeof listItemStart === "number" ? findTaskListMarkerOffset(text, listItemStart) : null;
return (
<li {...props} data-task-marker-offset={markerOffset ?? undefined}>
{renderSkillInlineMarkdownChildren(children, skills)}
</li>
);
},
input({ node: _node, type, checked, disabled: _disabled, ...props }) {
if (type !== "checkbox" || !onTaskListChange) {
return (
<input
{...props}
type={type}
checked={checked}
disabled={_disabled}
readOnly={type === "checkbox"}
/>
);
}
return (
<input
{...props}
type="checkbox"
name="markdown-task"
aria-label="Toggle task"
checked={checked}
onChange={(event) => {
const markerOffset = Number(
event.currentTarget.closest("li")?.dataset.taskMarkerOffset,
);
if (!Number.isSafeInteger(markerOffset)) return;
onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
}}
/>
);
li({ node: _node, children, ...props }) {
return <li {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</li>;
},
a({ node, href, children, ...props }) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
@@ -1334,7 +1282,6 @@ function ChatMarkdown({
iconPath={fileLinkMeta.filePath}
displayPath={fileLinkMeta.displayPath}
workspaceRelativePath={fileLinkMeta.workspaceRelativePath}
line={fileLinkMeta.line}
label={labelParts.join(" · ")}
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
theme={resolvedTheme}
@@ -1383,11 +1330,9 @@ function ChatMarkdown({
fileLinkParentSuffixByPath,
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
threadRef,
resolvedTheme,
skills,
text,
],
);
+4 -275
View File
@@ -2110,48 +2110,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps the compact chat header on one row", async () => {
const mounted = await mountChatView({
viewport: COMPACT_FOOTER_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-compact-header" as MessageId,
targetText: "keep the compact header aligned",
}),
});
try {
const chatHeader = await waitForElement(
() => document.querySelector<HTMLElement>("[data-chat-header]"),
"Unable to find chat header.",
);
const threadTitle = await waitForElement(
() => chatHeader.querySelector<HTMLElement>("h2"),
"Unable to find thread title.",
);
const headerActions = await waitForElement(
() => document.querySelector<HTMLElement>("[data-chat-header-actions]"),
"Unable to find chat header actions.",
);
const headerRect = chatHeader.getBoundingClientRect();
const titleRect = threadTitle.getBoundingClientRect();
const actionsRect = headerActions.getBoundingClientRect();
const headerCenter = headerRect.top + headerRect.height / 2;
expect(headerRect.height).toBe(52);
expect(titleRect.top).toBeGreaterThanOrEqual(headerRect.top);
expect(titleRect.bottom).toBeLessThanOrEqual(headerRect.bottom);
expect(actionsRect.top).toBeGreaterThanOrEqual(headerRect.top);
expect(actionsRect.bottom).toBeLessThanOrEqual(headerRect.bottom);
expect(Math.abs(titleRect.top + titleRect.height / 2 - headerCenter)).toBeLessThanOrEqual(1);
expect(Math.abs(actionsRect.top + actionsRect.height / 2 - headerCenter)).toBeLessThanOrEqual(
1,
);
} finally {
await mounted.cleanup();
}
});
it("keeps panel toggles fixed and can maximize the right panel", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
@@ -2318,151 +2276,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("renders the plan surface in the inline right panel", async () => {
useRightPanelStore.getState().open(THREAD_REF, "plan");
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-inline-plan-panel" as MessageId,
targetText: "show the inline plan panel",
}),
});
try {
await waitForElement(
() =>
Array.from(document.querySelectorAll<HTMLElement>("p")).find(
(element) => element.textContent?.trim() === "No active plan yet.",
) ?? null,
"Unable to find inline plan panel content.",
);
expect(
document.querySelector<HTMLElement>("[data-right-panel-tabbar]")?.textContent,
).toContain("Plan");
expect(document.body.textContent).toContain("Plans will appear here when generated.");
} finally {
await mounted.cleanup();
}
});
it("renders the shared panel toggles in the responsive right-panel sheet", async () => {
useRightPanelStore.getState().open(THREAD_REF, "plan");
useRightPanelStore.getState().openTerminal(THREAD_REF, DEFAULT_TERMINAL_ID);
useRightPanelStore.getState().activateSurface(THREAD_REF, "plan");
const baseSnapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-responsive-plan-panel-controls" as MessageId,
targetText: "show responsive plan panel controls",
});
const snapshot: OrchestrationReadModel = {
...baseSnapshot,
threads: baseSnapshot.threads.map((thread) =>
thread.id === THREAD_ID
? {
...thread,
activities: [
{
id: EventId.make("activity-responsive-panel-plan"),
tone: "info",
kind: "turn.plan.updated",
summary: "Plan updated",
payload: {
explanation: "Claude Tasks",
plan: [{ step: "Keep terminal navigation available", status: "inProgress" }],
},
turnId: null,
sequence: 1,
createdAt: isoAt(1_000),
},
],
}
: thread,
),
};
const mounted = await mountChatView({
viewport: COMPACT_FOOTER_VIEWPORT,
snapshot,
});
try {
const sheet = await waitForElement(
() => document.querySelector<HTMLElement>('[data-slot="sheet-popup"]'),
"Unable to find responsive right-panel sheet.",
);
const controls = await waitForElement(
() => sheet.querySelector<HTMLElement>("[data-panel-layout-controls]"),
"Unable to find shared controls in the responsive right-panel sheet.",
);
const tabbar = await waitForElement(
() => sheet.querySelector<HTMLElement>("[data-right-panel-tabbar]"),
"Unable to find responsive right-panel tabbar.",
);
const controlButtons = Array.from(controls.querySelectorAll<HTMLButtonElement>("button"));
const tabbarRect = tabbar.getBoundingClientRect();
const controlsRect = controls.getBoundingClientRect();
expect(controlButtons.map((button) => button.getAttribute("aria-label"))).toEqual([
"Toggle terminal drawer",
"Toggle right panel",
]);
expect(tabbarRect.height).toBe(52);
expect(controlsRect.height).toBe(52);
expect(controlsRect.top).toBe(tabbarRect.top);
expect(window.innerWidth - controlsRect.right).toBe(12);
for (const button of controlButtons) {
const rect = button.getBoundingClientRect();
const buttonCenter = rect.top + rect.height / 2;
const tabbarCenter = tabbarRect.top + tabbarRect.height / 2;
expect(rect.width).toBe(32);
expect(rect.height).toBe(32);
expect(Math.abs(buttonCenter - tabbarCenter)).toBeLessThanOrEqual(1);
}
expect(
controlButtons[1]!.getBoundingClientRect().left -
controlButtons[0]!.getBoundingClientRect().right,
).toBe(4);
expect(sheet.querySelector('button[aria-label="Maximize panel"]')).toBeNull();
expect(sheet.querySelector('button[aria-label="Close tasks sidebar"]')).toBeNull();
const terminalTab = Array.from(
sheet.querySelectorAll<HTMLButtonElement>("[data-right-panel-tab-list] button"),
).find((button) => button.textContent?.includes("Terminal"));
terminalTab?.click();
await vi.waitFor(() => {
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF)
.activeSurfaceId,
).toBe(`terminal:${DEFAULT_TERMINAL_ID}`);
expect(sheet.querySelector('[data-terminal-owner="right-panel"]')).not.toBeNull();
expect(sheet.textContent).not.toContain("Claude Tasks");
});
sheet.querySelector<HTMLButtonElement>('button[aria-label="Close Plan"]')?.click();
await vi.waitFor(() => {
const panelState = selectThreadRightPanelState(
useRightPanelStore.getState().byThreadKey,
THREAD_REF,
);
expect(panelState.surfaces.some((surface) => surface.kind === "plan")).toBe(false);
expect(panelState.activeSurfaceId).toBe(`terminal:${DEFAULT_TERMINAL_ID}`);
});
controls.querySelector<HTMLButtonElement>('button[aria-label="Toggle right panel"]')?.click();
await vi.waitFor(() => {
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF).isOpen,
).toBe(false);
});
} finally {
await mounted.cleanup();
}
});
it("loads file previews from the active thread worktree", async () => {
const worktreePath = "/repo/worktrees/file-preview-thread";
const snapshot = createSnapshotForTargetUser({
@@ -2700,97 +2513,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
expect(fileTree.shadowRoot?.activeElement).toBe(fileSearchInput);
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe("");
const previousCodeVirtualizer = document.querySelector<HTMLElement>(
".file-preview-virtualizer",
useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts");
const codeVirtualizer = await waitForElement(
() => document.querySelector<HTMLElement>(".file-preview-virtualizer"),
"Unable to find the virtualized file preview.",
);
useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts", 4_000);
const codeVirtualizer = await waitForElement(() => {
const current = document.querySelector<HTMLElement>(".file-preview-virtualizer");
return current !== previousCodeVirtualizer ? current : null;
}, "Unable to find the virtualized file preview.");
expect(codeVirtualizer.querySelector("diffs-container")).not.toBeNull();
expect(codeVirtualizer.classList.contains("overflow-auto")).toBe(true);
await vi.waitFor(
() => {
const fileHost = codeVirtualizer.querySelector<HTMLElement>("diffs-container");
const targetLine = fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-line="4000"]');
const targetLineNumber = fileHost?.shadowRoot?.querySelector<HTMLElement>(
'[data-column-number="4000"]',
);
const previousLine =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-line="3999"]');
const previousLineNumber = fileHost?.shadowRoot?.querySelector<HTMLElement>(
'[data-column-number="3999"]',
);
expect(codeVirtualizer.scrollTop).toBeGreaterThan(0);
expect(targetLine).not.toBeNull();
expect(previousLine).not.toBeNull();
expect(targetLine?.hasAttribute("data-file-link-reveal")).toBe(true);
expect(targetLineNumber?.hasAttribute("data-file-link-reveal")).toBe(true);
expect(targetLine?.hasAttribute("data-selected-line")).toBe(false);
expect(targetLineNumber?.hasAttribute("data-selected-line")).toBe(false);
expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).toBeNull();
expect(window.getComputedStyle(targetLine!).backgroundColor).not.toBe(
window.getComputedStyle(previousLine!).backgroundColor,
);
expect(window.getComputedStyle(targetLineNumber!).backgroundColor).not.toBe(
window.getComputedStyle(previousLineNumber!).backgroundColor,
);
const viewportRect = codeVirtualizer.getBoundingClientRect();
const lineRect = targetLine!.getBoundingClientRect();
expect(lineRect.top).toBeGreaterThanOrEqual(viewportRect.top);
expect(lineRect.bottom).toBeLessThanOrEqual(viewportRect.bottom);
},
{ timeout: 8_000, interval: 16 },
);
const fileHost = codeVirtualizer.querySelector<HTMLElement>("diffs-container");
const targetLineNumber =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-column-number="4000"]') ?? null;
const previousLineNumber =
fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-column-number="3999"]') ?? null;
expect(targetLineNumber).not.toBeNull();
expect(previousLineNumber).not.toBeNull();
targetLineNumber!.dispatchEvent(
new PointerEvent("pointermove", {
bubbles: true,
cancelable: true,
composed: true,
pointerType: "mouse",
}),
);
await vi.waitFor(() => {
expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).not.toBeNull();
});
previousLineNumber!.dispatchEvent(
new PointerEvent("pointermove", {
bubbles: true,
cancelable: true,
composed: true,
pointerType: "mouse",
}),
);
await vi.waitFor(() => {
expect(targetLineNumber?.querySelector("[data-gutter-utility-slot]")).toBeNull();
expect(previousLineNumber?.querySelector("[data-gutter-utility-slot]")).not.toBeNull();
});
codeVirtualizer.scrollTop = 0;
useRightPanelStore.getState().openFile(THREAD_REF, "src/large.ts", 4_000);
await vi.waitFor(
() => {
const fileHost = codeVirtualizer.querySelector<HTMLElement>("diffs-container");
const targetLine = fileHost?.shadowRoot?.querySelector<HTMLElement>('[data-line="4000"]');
expect(targetLine).not.toBeNull();
expect(targetLine?.hasAttribute("data-file-link-reveal")).toBe(true);
expect(targetLine?.hasAttribute("data-selected-line")).toBe(false);
expect(codeVirtualizer.scrollTop).toBeGreaterThan(0);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
+159 -258
View File
@@ -164,13 +164,12 @@ import {
formatElementContextLabel,
} from "../lib/elementContext";
import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation";
import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../reviewCommentContext";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import { PanelLayoutControls } from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
@@ -1120,7 +1119,6 @@ function ChatViewContent(props: ChatViewProps) {
const setComposerDraftPreviewAnnotations = useComposerDraftStore(
(store) => store.setPreviewAnnotations,
);
const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
const setComposerDraftInteractionMode = useComposerDraftStore(
@@ -1292,8 +1290,6 @@ function ChatViewContent(props: ChatViewProps) {
const activeRightPanelSurface = useRightPanelStore((store) =>
selectActiveRightPanelSurface(store.byThreadKey, activeThreadRef),
);
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = usePreviewStateStore((state) =>
selectThreadPreviewState(state.byThreadKey, activeThreadRef),
);
@@ -1335,8 +1331,9 @@ function ChatViewContent(props: ChatViewProps) {
const planSidebarOpen = activeRightPanelKind === "plan";
const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
const rightPanelOpen = rightPanelState.isOpen;
const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet;
const rightPanelMaximized =
rightPanelOpen && !shouldUsePlanSidebarSheet && maximizedRightPanelThreadKey === routeThreadKey;
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
useEffect(() => {
@@ -3037,25 +3034,23 @@ function ChatViewContent(props: ChatViewProps) {
const toggleInteractionMode = useCallback(() => {
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
}, [handleInteractionModeChange, interactionMode]);
const dismissPlanSidebarForCurrentTurn = useCallback(() => {
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
const togglePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
} else {
planSidebarDismissedForTurnRef.current = null;
}
useRightPanelStore.getState().toggle(activeThreadRef, "plan");
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]);
}, [activePlan?.turnId, activeThreadRef, planSidebarOpen, sidebarProposedPlan?.turnId]);
const closePlanSidebar = useCallback(() => {
if (!activeThreadRef) return;
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
dismissPlanSidebarForCurrentTurn();
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn]);
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
}, [activePlan?.turnId, activeThreadRef, sidebarProposedPlan?.turnId]);
const closePreviewPanel = useCallback(() => {
if (!activeThreadRef) return;
setMaximizedRightPanelThreadKey(null);
@@ -3064,11 +3059,6 @@ function ChatViewContent(props: ChatViewProps) {
const activateRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
if (surface.kind === "plan") {
planSidebarDismissedForTurnRef.current = null;
} else if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
}
useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
if (surface.kind === "preview" && surface.resourceId) {
usePreviewStateStore.getState().setActiveTab(activeThreadRef, surface.resourceId);
@@ -3093,51 +3083,41 @@ function ChatViewContent(props: ChatViewProps) {
});
}
},
[
activeThreadRef,
diffOpen,
dismissPlanSidebarForCurrentTurn,
environmentId,
navigate,
onDiffPanelOpen,
planSidebarOpen,
threadId,
],
[activeThreadRef, diffOpen, environmentId, navigate, onDiffPanelOpen, threadId],
);
const toggleRightPanel = useCallback(() => {
if (!activeThreadRef) return;
if (rightPanelOpen) {
if (planSidebarOpen) {
closePlanSidebar();
} else {
closePreviewPanel();
}
return;
setMaximizedRightPanelThreadKey(null);
}
useRightPanelStore.getState().toggleVisibility(activeThreadRef);
}, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]);
}, [activeThreadRef, rightPanelOpen]);
const toggleRightPanelMaximized = () => {
if (!rightPanelOpen || shouldUsePlanSidebarSheet) return;
if (!canMaximizeRightPanel) return;
setMaximizedRightPanelThreadKey((threadKey) =>
threadKey === routeThreadKey ? null : routeThreadKey,
);
};
const cleanupRightPanelSurfaces = useCallback(
(surfaces: readonly RightPanelSurface[]) => {
const closeRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
if (surfaces.some((surface) => surface.kind === "plan")) {
dismissPlanSidebarForCurrentTurn();
if (surface.kind === "preview" && surface.resourceId) {
usePreviewStateStore.getState().removeSession(activeThreadRef, surface.resourceId);
const api = readEnvironmentApi(activeThreadRef.environmentId);
void api?.preview
.close({ threadId: activeThreadRef.threadId, tabId: surface.resourceId })
.catch(() => undefined);
}
const api = readEnvironmentApi(activeThreadRef.environmentId);
for (const surface of surfaces) {
if (surface.kind === "preview" && surface.resourceId) {
usePreviewStateStore.getState().removeSession(activeThreadRef, surface.resourceId);
void api?.preview
.close({ threadId: activeThreadRef.threadId, tabId: surface.resourceId })
.catch(() => undefined);
}
if (surface.kind !== "terminal") continue;
useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id);
const nextActiveSurface = selectActiveRightPanelSurface(
useRightPanelStore.getState().byThreadKey,
activeThreadRef,
);
if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
usePreviewStateStore.getState().setActiveTab(activeThreadRef, nextActiveSurface.resourceId);
}
if (surface.kind === "terminal") {
const api = readEnvironmentApi(activeThreadRef.environmentId);
for (const terminalId of surface.terminalIds) {
void api?.terminal
.close({
@@ -3148,8 +3128,7 @@ function ChatViewContent(props: ChatViewProps) {
.catch(() => undefined);
}
}
if (diffOpen && surfaces.some((surface) => surface.kind === "diff")) {
if (surface.kind === "diff" && diffOpen) {
void navigate({
to: "/$environmentId/$threadId",
params: { environmentId, threadId },
@@ -3158,102 +3137,8 @@ function ChatViewContent(props: ChatViewProps) {
});
}
},
[
activeThreadRef,
diffOpen,
dismissPlanSidebarForCurrentTurn,
environmentId,
navigate,
threadId,
],
[activeThreadRef, diffOpen, environmentId, navigate, threadId],
);
const syncActivePreviewSurface = useCallback(() => {
if (!activeThreadRef) return;
const nextActiveSurface = selectActiveRightPanelSurface(
useRightPanelStore.getState().byThreadKey,
activeThreadRef,
);
if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
usePreviewStateStore.getState().setActiveTab(activeThreadRef, nextActiveSurface.resourceId);
}
}, [activeThreadRef]);
const closeRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
cleanupRightPanelSurfaces([surface]);
useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id);
syncActivePreviewSurface();
},
[activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface],
);
const closeOtherRightPanelSurfaces = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id);
cleanupRightPanelSurfaces(surfaces);
useRightPanelStore.getState().closeOtherSurfaces(activeThreadRef, surface.id);
syncActivePreviewSurface();
},
[
activeThreadRef,
cleanupRightPanelSurfaces,
rightPanelState.surfaces,
syncActivePreviewSurface,
],
);
const closeRightPanelSurfacesToRight = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id);
if (surfaceIndex < 0) return;
const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1);
cleanupRightPanelSurfaces(surfaces);
useRightPanelStore.getState().closeSurfacesToRight(activeThreadRef, surface.id);
syncActivePreviewSurface();
},
[
activeThreadRef,
cleanupRightPanelSurfaces,
rightPanelState.surfaces,
syncActivePreviewSurface,
],
);
const closeAllRightPanelSurfaces = useCallback(() => {
if (!activeThreadRef) return;
cleanupRightPanelSurfaces(rightPanelState.surfaces);
useRightPanelStore.getState().closeAllSurfaces(activeThreadRef);
}, [activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces]);
const copyRightPanelFilePath = useCallback((relativePath: string) => {
if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to copy path",
description: "Clipboard API unavailable.",
}),
);
return;
}
void navigator.clipboard.writeText(relativePath).then(
() => {
toastManager.add({
type: "success",
title: "Path copied",
description: relativePath,
});
},
(error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to copy path",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
},
);
}, []);
const persistThreadSettingsForNextTurn = useCallback(
async (input: {
threadId: ThreadId;
@@ -3751,7 +3636,6 @@ function ChatViewContent(props: ChatViewProps) {
terminalContexts: composerTerminalContexts,
elementContexts: composerElementContexts,
previewAnnotations: composerPreviewAnnotations,
reviewComments: composerReviewComments,
selectedProvider: ctxSelectedProvider,
selectedModel: ctxSelectedModel,
selectedProviderModels: ctxSelectedProviderModels,
@@ -3768,10 +3652,7 @@ function ChatViewContent(props: ChatViewProps) {
prompt: promptForSend,
imageCount: composerImages.length,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
composerPreviewAnnotations.length +
composerReviewComments.length,
elementContextCount: composerElementContexts.length + composerPreviewAnnotations.length,
});
if (showPlanFollowUpPrompt && activeProposedPlan) {
const followUp = resolvePlanFollowUpSubmission({
@@ -3791,8 +3672,7 @@ function ChatViewContent(props: ChatViewProps) {
composerImages.length === 0 &&
sendableComposerTerminalContexts.length === 0 &&
composerElementContexts.length === 0 &&
composerPreviewAnnotations.length === 0 &&
composerReviewComments.length === 0
composerPreviewAnnotations.length === 0
? parseStandaloneComposerSlashCommand(trimmed)
: null;
if (standaloneSlashCommand) {
@@ -3842,19 +3722,14 @@ function ChatViewContent(props: ChatViewProps) {
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
const composerElementContextsSnapshot = [...composerElementContexts];
const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations];
const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments];
const messageTextWithContexts = appendElementContextsToPrompt(
appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot),
composerElementContextsSnapshot,
);
const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce(
const messageTextForSend = composerPreviewAnnotationsSnapshot.reduce(
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
messageTextWithContexts,
);
const messageTextForSend = appendReviewCommentsToPrompt(
messageTextWithPreviewAnnotations,
composerReviewCommentsSnapshot,
);
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const outgoingMessageText = formatOutgoingPrompt({
@@ -4024,8 +3899,6 @@ function ChatViewContent(props: ChatViewProps) {
composerTerminalContextsRef.current.length === 0 &&
composerElementContextsRef.current.length === 0 &&
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations
.length ?? 0) === 0 &&
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments
.length ?? 0) === 0
) {
setOptimisticUserMessages((existing) => {
@@ -4046,7 +3919,6 @@ function ChatViewContent(props: ChatViewProps) {
setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);
setComposerDraftElementContexts(composerDraftTarget, composerElementContextsSnapshot);
setComposerDraftPreviewAnnotations(composerDraftTarget, composerPreviewAnnotationsSnapshot);
setComposerDraftReviewComments(composerDraftTarget, composerReviewCommentsSnapshot);
composerRef.current?.resetCursorState({
cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length),
prompt: promptForSend,
@@ -4686,7 +4558,7 @@ function ChatViewContent(props: ChatViewProps) {
return <NoActiveThreadState />;
}
const panelToggleControls = (
const panelLayoutControls = (
<PanelLayoutControls
terminalAvailable={Boolean(activeProject)}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
@@ -4694,97 +4566,20 @@ function ChatViewContent(props: ChatViewProps) {
rightPanelAvailable={Boolean(activeProject)}
rightPanelOpen={rightPanelOpen}
rightPanelShortcutLabel={rightPanelToggleShortcutLabel}
rightPanelMaximized={rightPanelMaximized}
canMaximizeRightPanel={canMaximizeRightPanel}
onToggleTerminal={toggleTerminalVisibility}
onToggleRightPanel={toggleRightPanel}
onToggleRightPanelMaximized={toggleRightPanelMaximized}
/>
);
const panelLayoutControls = (
<div className="workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]">
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelMaximizeControl
maximized={rightPanelMaximized}
onToggle={toggleRightPanelMaximized}
/>
) : null}
{panelToggleControls}
</div>
);
const rightPanelContent = activeThreadRef ? (
activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
</Suspense>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
threadRef={activeThreadRef}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="embedded"
/>
) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") &&
activeProject &&
activeWorkspaceRoot ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeWorkspaceRoot}
projectName={activeProject.name}
threadRef={activeThreadRef}
composerDraftTarget={composerDraftTarget}
keybindings={keybindings}
availableEditors={availableEditors}
relativePath={
activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath : null
}
revealLine={activeFileSurface?.revealLine ?? null}
revealRequestId={activeFileSurface?.revealRequestId ?? 0}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null
) : null;
return (
<div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
{isElectron && activeThreadRef ? (
<PreviewAutomationOwner threadRef={activeThreadRef} visible={previewPanelOpen} />
) : null}
{rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
{rightPanelOpen ? panelLayoutControls : null}
<div
className={cn(
"flex min-h-0 min-w-0 flex-col overflow-hidden",
@@ -5041,10 +4836,6 @@ function ChatViewContent(props: ChatViewProps) {
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
onCopyFilePath={copyRightPanelFilePath}
onAddBrowser={createBrowserSurface}
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
@@ -5053,15 +4844,65 @@ function ChatViewContent(props: ChatViewProps) {
diffAvailable={isServerThread && isGitRepo}
filesAvailable={Boolean(activeProject)}
>
{rightPanelContent}
{activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<Suspense fallback={null}>
<DiffPanel mode="embedded" />
</Suspense>
) : (activeRightPanelSurface?.kind === "files" ||
activeRightPanelSurface?.kind === "file") &&
activeProject &&
activeWorkspaceRoot ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeWorkspaceRoot}
projectName={activeProject.name}
relativePath={
activeRightPanelSurface.kind === "file"
? activeRightPanelSurface.relativePath
: null
}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null}
</RightPanelTabs>
) : null}
{shouldUsePlanSidebarSheet && rightPanelOpen && activeThreadRef ? (
<RightPanelSheet open onClose={planSidebarOpen ? closePlanSidebar : closePreviewPanel}>
<RightPanelSheet open onClose={closePreviewPanel}>
<RightPanelTabs
mode="sheet"
layoutControls={panelToggleControls}
surfaces={rightPanelState.surfaces}
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
@@ -5069,10 +4910,6 @@ function ChatViewContent(props: ChatViewProps) {
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
onCopyFilePath={copyRightPanelFilePath}
onAddBrowser={createBrowserSurface}
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
@@ -5081,7 +4918,71 @@ function ChatViewContent(props: ChatViewProps) {
diffAvailable={isServerThread && isGitRepo}
filesAvailable={Boolean(activeProject)}
>
{rightPanelContent}
{activeRightPanelSurface?.kind === "preview" ? (
<Suspense fallback={null}>
<PreviewPanel
mode="embedded"
threadRef={activeThreadRef}
tabId={activeRightPanelSurface.resourceId}
configuredUrls={configuredPreviewUrls}
visible
/>
</Suspense>
) : activeRightPanelSurface?.kind === "terminal" ? (
<PersistentThreadTerminalPanel
threadRef={activeThreadRef}
surface={activeRightPanelSurface}
launchContext={activeTerminalLaunchContext ?? null}
focusRequestId={terminalFocusRequestId}
keybindings={keybindings}
onAddTerminalContext={addTerminalContextToDraft}
onSplitTerminal={splitPanelTerminal}
onSplitTerminalVertical={splitPanelTerminalVertical}
onNewTerminal={addTerminalSurface}
onActiveTerminalChange={activatePanelTerminal}
onCloseTerminal={closePanelTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<Suspense fallback={null}>
<DiffPanel mode="embedded" />
</Suspense>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
label={planSidebarLabel}
environmentId={environmentId}
threadRef={activeThreadRef}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
mode="embedded"
onClose={closePlanSidebar}
/>
) : (activeRightPanelSurface?.kind === "files" ||
activeRightPanelSurface?.kind === "file") &&
activeProject &&
activeWorkspaceRoot ? (
<Suspense fallback={null}>
<FilePreviewPanel
key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}
environmentId={activeProject.environmentId}
cwd={activeWorkspaceRoot}
projectName={activeProject.name}
relativePath={
activeRightPanelSurface.kind === "file"
? activeRightPanelSurface.relativePath
: null
}
onOpenFile={openFileSurface}
onPendingChange={handleFilePendingChange}
/>
</Suspense>
) : null}
</RightPanelTabs>
</RightPanelSheet>
) : null}
+4 -15
View File
@@ -1,7 +1,7 @@
import { Virtualizer } from "@pierre/diffs/react";
import { FileDiff, Virtualizer } from "@pierre/diffs/react";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { scopeThreadRef } from "@t3tools/client-runtime";
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
import type { TurnId } from "@t3tools/contracts";
import {
ChevronDownIcon,
ChevronLeftIcon,
@@ -20,7 +20,6 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { type DraftId } from "../composerDraftStore";
import { useCheckpointDiff } from "~/lib/checkpointDiffState";
import { useVcsStatus } from "~/lib/vcsStatusState";
import { cn } from "~/lib/utils";
@@ -42,7 +41,6 @@ import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { AnnotatableFileDiff } from "./diffs/AnnotatableFileDiff";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -149,12 +147,11 @@ const DIFF_PANEL_UNSAFE_CSS = `
interface DiffPanelProps {
mode?: DiffPanelMode;
composerDraftTarget: ScopedThreadRef | DraftId;
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline", composerDraftTarget }: DiffPanelProps) {
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const settings = useSettings();
@@ -221,10 +218,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
const selectedCheckpointTurnCount =
selectedTurn &&
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : "conversation";
const reviewSectionTitle = selectedTurn
? `Turn ${selectedCheckpointTurnCount ?? "?"}`
: "All turns";
const selectedCheckpointRange = useMemo(
() =>
typeof selectedCheckpointTurnCount === "number"
@@ -680,12 +673,8 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
openDiffFile(filePath);
}}
>
<AnnotatableFileDiff
<FileDiff
fileDiff={fileDiff}
filePath={filePath}
sectionId={reviewSectionId}
sectionTitle={reviewSectionTitle}
composerDraftTarget={composerDraftTarget}
renderHeaderPrefix={() => (
<Tooltip>
<TooltipTrigger
+12
View File
@@ -11,6 +11,7 @@ import {
ChevronRightIcon,
EllipsisIcon,
LoaderIcon,
PanelRightCloseIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import type { ActivePlanState } from "../session-logic";
@@ -60,6 +61,7 @@ interface PlanSidebarProps {
workspaceRoot: string | undefined;
timestampFormat: TimestampFormat;
mode?: "sheet" | "sidebar" | "embedded";
onClose: () => void;
}
const PlanSidebar = memo(function PlanSidebar({
@@ -72,6 +74,7 @@ const PlanSidebar = memo(function PlanSidebar({
workspaceRoot,
timestampFormat,
mode = "sidebar",
onClose,
}: PlanSidebarProps) {
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
@@ -179,6 +182,15 @@ const PlanSidebar = memo(function PlanSidebar({
</MenuPopup>
</Menu>
) : null}
<Button
size="icon-xs"
variant="ghost"
onClick={onClose}
aria-label={`Close ${label.toLowerCase()} sidebar`}
className="text-muted-foreground/50 hover:text-foreground/70"
>
<PanelRightCloseIcon className="size-3.5" />
</Button>
</div>
</div>
+4 -80
View File
@@ -1,20 +1,11 @@
import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type ReactElement,
type ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { type ReactElement, type ReactNode, useEffect, useRef, useState } from "react";
import { isElectron } from "~/env";
import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
@@ -27,7 +18,6 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon";
interface RightPanelTabsProps {
mode: PreviewPanelMode;
maximized?: boolean;
layoutControls?: ReactNode;
surfaces: readonly RightPanelSurface[];
activeSurfaceId: string | null;
pendingSurfaceIds: ReadonlySet<string>;
@@ -35,10 +25,6 @@ interface RightPanelTabsProps {
terminalLabelsById: ReadonlyMap<string, string>;
onActivate: (surface: RightPanelSurface) => void;
onCloseSurface: (surface: RightPanelSurface) => void;
onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
onCloseAllSurfaces: () => void;
onCopyFilePath: (relativePath: string) => void;
onAddBrowser: () => void;
onAddTerminal: () => void;
onAddDiff: () => void;
@@ -55,8 +41,6 @@ const SURFACE_DISABLED_REASONS = {
diff: "Diff is only available for server threads in Git repositories.",
} as const;
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
return (
<Tooltip>
@@ -273,64 +257,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
const { resolvedTheme } = useTheme();
const tabListRef = useRef<HTMLDivElement>(null);
const handleTabContextMenu = useCallback(
async (event: ReactMouseEvent, surface: RightPanelSurface) => {
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
if (surfaceIndex < 0) return;
const items: ContextMenuItem<TabContextMenuAction>[] = [];
if (surface.kind === "file") {
items.push({ id: "copy-path", label: "Copy path" });
}
items.push(
{ id: "close", label: "Close" },
{
id: "close-others",
label: "Close others",
disabled: props.surfaces.length <= 1,
},
{
id: "close-to-right",
label: "Close to the right",
disabled: surfaceIndex >= props.surfaces.length - 1,
},
{
id: "close-all",
label: "Close all",
disabled: props.surfaces.length === 0,
},
);
const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
switch (action) {
case "copy-path":
if (surface.kind === "file") props.onCopyFilePath(surface.relativePath);
break;
case "close":
props.onCloseSurface(surface);
break;
case "close-others":
props.onCloseOtherSurfaces(surface);
break;
case "close-to-right":
props.onCloseSurfacesToRight(surface);
break;
case "close-all":
props.onCloseAllSurfaces();
break;
case null:
break;
}
},
[props],
);
useEffect(() => {
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
@@ -343,8 +269,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
>
<div
className={cn(
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-28" : "pr-3",
"px-2 pr-28",
props.mode === "inline" ? "workspace-topbar" : "flex h-10 shrink-0 items-center",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
)}
data-right-panel-tabbar
@@ -365,7 +291,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<div
key={surface.id}
data-active-tab={active}
onContextMenu={(event) => void handleTabContextMenu(event, surface)}
className={cn(
"group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
active
@@ -458,7 +383,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
) : null}
</div>
</ScrollArea>
{props.layoutControls}
</div>
<div className="flex min-h-0 flex-1 flex-col">
{props.activeSurfaceId === null ? (
@@ -1,255 +0,0 @@
import "../index.css";
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { useCallback, useRef, useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";
import { cleanup, render } from "vitest-browser-react";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { DEFAULT_INTERACTION_MODE } from "../types";
import type { SidebarThreadSummary } from "../types";
import { SidebarThreadRow } from "./Sidebar";
// Double-click-to-rename is a desktop affordance; force the non-mobile path so
// the rename input is reachable regardless of the test browser viewport.
vi.mock("~/hooks/useMediaQuery", () => ({
useIsMobile: () => false,
useMediaQuery: () => false,
}));
const THREAD_ID = ThreadId.make("thread-1");
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const PROJECT_ID = ProjectId.make("project-1");
const INITIAL_TITLE = "Original title";
const ROW_TESTID = `thread-row-${THREAD_ID}`;
const TITLE_TESTID = `thread-title-${THREAD_ID}`;
// Spies live at module scope so their call history survives the row's
// re-renders; reset between tests.
const spies = {
handleThreadClick: vi.fn(),
startThreadRename: vi.fn(),
navigateToThread: vi.fn(),
handleMultiSelectContextMenu: vi.fn(async () => {}),
handleThreadContextMenu: vi.fn(async () => {}),
clearSelection: vi.fn(),
commitRename: vi.fn(),
attemptArchiveThread: vi.fn(async () => {}),
openPrLink: vi.fn(),
};
function buildThread(title: string): SidebarThreadSummary {
return {
id: THREAD_ID,
environmentId: ENVIRONMENT_ID,
projectId: PROJECT_ID,
title,
interactionMode: DEFAULT_INTERACTION_MODE,
session: null,
createdAt: "2024-01-01T00:00:00.000Z",
archivedAt: null,
updatedAt: undefined,
latestTurn: null,
branch: null,
worktreePath: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
}
// Mirrors the real parent (`SidebarProjectItem`): holds the rename state, wires
// `startThreadRename`, and commits by clearing the rename state and persisting
// the new title back onto the thread so the row re-renders with it.
function Harness() {
const [title, setTitle] = useState(INITIAL_TITLE);
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const renamingCommittedRef = useRef(false);
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
const startThreadRename = useCallback((threadKey: string, nextTitle: string) => {
spies.startThreadRename(threadKey, nextTitle);
setRenamingThreadKey(threadKey);
setRenamingTitle(nextTitle);
renamingCommittedRef.current = false;
}, []);
const commitRename = useCallback(
async (threadRef: unknown, newTitle: string, originalTitle: string) => {
spies.commitRename(threadRef, newTitle, originalTitle);
const trimmed = newTitle.trim();
if (trimmed.length > 0) {
setTitle(trimmed);
}
setRenamingThreadKey(null);
renamingInputRef.current = null;
},
[],
);
const cancelRename = useCallback(() => {
setRenamingThreadKey(null);
renamingInputRef.current = null;
}, []);
return (
<AppAtomRegistryProvider>
<ul>
<SidebarThreadRow
thread={buildThread(title)}
projectCwd={null}
orderedProjectThreadKeys={[]}
isActive={false}
jumpLabel={null}
appSettingsConfirmThreadArchive={false}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
startThreadRename={startThreadRename}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
handleThreadClick={spies.handleThreadClick}
navigateToThread={spies.navigateToThread}
handleMultiSelectContextMenu={spies.handleMultiSelectContextMenu}
handleThreadContextMenu={spies.handleThreadContextMenu}
clearSelection={spies.clearSelection}
commitRename={commitRename}
cancelRename={cancelRename}
attemptArchiveThread={spies.attemptArchiveThread}
openPrLink={spies.openPrLink}
/>
</ul>
</AppAtomRegistryProvider>
);
}
describe("SidebarThreadRow double-click rename", () => {
beforeEach(() => {
for (const spy of Object.values(spies)) spy.mockClear();
});
afterEach(() => {
cleanup();
});
it("double-clicking a row starts the inline rename, focused with text selected", async () => {
render(<Harness />);
await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible();
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
const input = page.getByRole("textbox");
await expect.element(input).toBeVisible();
const element = input.element() as HTMLInputElement;
expect(element.value).toBe(INITIAL_TITLE);
// The existing rename-input ref focuses + selects the whole title.
expect(document.activeElement).toBe(element);
expect(element.selectionStart).toBe(0);
expect(element.selectionEnd).toBe(INITIAL_TITLE.length);
});
it("Enter commits the rename and the new title persists on the row", async () => {
render(<Harness />);
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
const input = page.getByRole("textbox");
await expect.element(input).toBeVisible();
await userEvent.fill(input, "Renamed thread");
await userEvent.keyboard("{Enter}");
// commitRename was invoked with (threadRef, newTitle, originalTitle).
expect(spies.commitRename).toHaveBeenCalledTimes(1);
expect(spies.commitRename).toHaveBeenCalledWith(
expect.anything(),
"Renamed thread",
INITIAL_TITLE,
);
// Input is gone and the row now shows the persisted title.
const title = page.getByTestId(TITLE_TESTID);
await expect.element(title).toBeVisible();
await expect.element(title).toHaveTextContent("Renamed thread");
});
it("Escape cancels the rename without committing", async () => {
render(<Harness />);
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
await expect.element(page.getByRole("textbox")).toBeVisible();
await userEvent.keyboard("{Escape}");
expect(spies.commitRename).not.toHaveBeenCalled();
const title = page.getByTestId(TITLE_TESTID);
await expect.element(title).toBeVisible();
await expect.element(title).toHaveTextContent(INITIAL_TITLE);
});
it("double-clicking inside the rename input keeps the edit (does not reset to the title)", async () => {
render(<Harness />);
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
const input = page.getByRole("textbox");
await expect.element(input).toBeVisible();
await userEvent.fill(input, "Edited but not committed");
// Double-clicking inside the input (e.g. to select a word) must not bubble
// to the row and restart the rename, which would wipe the edit.
await userEvent.dblClick(input);
expect((input.element() as HTMLInputElement).value).toBe("Edited but not committed");
expect(spies.commitRename).not.toHaveBeenCalled();
});
it("double-clicking the row chrome while already renaming does not restart/reset it", async () => {
render(<Harness />);
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
const input = page.getByRole("textbox");
await expect.element(input).toBeVisible();
await userEvent.fill(input, "Edited");
expect(spies.startThreadRename).toHaveBeenCalledTimes(1);
// Double-click the row element itself (chrome, not the input).
const rowEl = page.getByTestId(ROW_TESTID).element();
rowEl.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true, detail: 2 }));
// Guard short-circuits: rename is not restarted and the edit is preserved.
expect(spies.startThreadRename).toHaveBeenCalledTimes(1);
expect((input.element() as HTMLInputElement).value).toBe("Edited");
});
it("modifier double-click is multi-select intent and does not start a rename", async () => {
render(<Harness />);
await userEvent.keyboard("{Shift>}");
await userEvent.dblClick(page.getByTestId(ROW_TESTID));
await userEvent.keyboard("{/Shift}");
await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible();
expect(page.getByRole("textbox").elements()).toHaveLength(0);
});
it("single click routes through the navigation handler and does not start a rename", async () => {
render(<Harness />);
await userEvent.click(page.getByTestId(ROW_TESTID));
expect(spies.handleThreadClick).toHaveBeenCalledTimes(1);
// No rename input: the title span is still shown.
await expect.element(page.getByTestId(TITLE_TESTID)).toBeVisible();
expect(page.getByRole("textbox").elements()).toHaveLength(0);
});
});
@@ -11,7 +11,6 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
isTrailingDoubleClick,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
@@ -172,24 +171,6 @@ describe("shouldClearThreadSelectionOnMouseDown", () => {
});
});
describe("isTrailingDoubleClick", () => {
it("treats a single click as a normal activation", () => {
expect(isTrailingDoubleClick(1)).toBe(false);
});
it("treats synthetic/keyboard activations (detail 0) as a normal activation", () => {
expect(isTrailingDoubleClick(0)).toBe(false);
});
it("ignores the second click of a double-click so it does not navigate", () => {
expect(isTrailingDoubleClick(2)).toBe(true);
});
it("ignores further clicks of a triple-click", () => {
expect(isTrailingDoubleClick(3)).toBe(true);
});
});
describe("resolveSidebarNewThreadEnvMode", () => {
it("uses the app default when the caller does not request a specific mode", () => {
expect(
-9
View File
@@ -160,15 +160,6 @@ export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null
return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
}
// A double-click dispatches two `click` events before `dblclick`: the first has
// `detail === 1`, the second `detail === 2`. The second click must not run the
// row's single-click navigation, otherwise double-click-to-rename would also
// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
// still count as a normal single activation.
export function isTrailingDoubleClick(detail: number): boolean {
return detail > 1;
}
export function resolveSidebarNewThreadEnvMode(input: {
requestedEnvMode?: SidebarNewThreadEnvMode;
defaultEnvMode: SidebarNewThreadEnvMode;
+4 -48
View File
@@ -164,7 +164,6 @@ import {
getSidebarThreadIdsToPrewarm,
resolveAdjacentThreadId,
isContextMenuPointerDown,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
@@ -179,7 +178,6 @@ import {
import { sortThreads } from "../lib/threadSort";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { readEnvironmentApi } from "../environmentApi";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
@@ -294,7 +292,6 @@ interface SidebarThreadRowProps {
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
startThreadRename: (threadKey: string, title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
confirmingArchiveThreadKey: string | null;
@@ -322,7 +319,7 @@ interface SidebarThreadRowProps {
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
}
export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
isActive,
@@ -331,7 +328,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
renamingThreadKey,
renamingTitle,
setRenamingTitle,
startThreadRename,
renamingInputRef,
renamingCommittedRef,
confirmingArchiveThreadKey,
@@ -356,7 +352,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
environmentId: thread.environmentId,
threadId: thread.id,
});
const isMobile = useIsMobile();
const discoveredPorts = useThreadDiscoveredPorts({
environmentId: thread.environmentId,
threadId: thread.id,
@@ -442,24 +437,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
},
[discoveredPorts, navigateToThread, threadRef],
);
const handleRowDoubleClick = useCallback(
(event: React.MouseEvent) => {
// Already renaming this row: a double-click on the row chrome (outside the
// input) must not restart and discard the in-progress edit.
if (renamingThreadKey === threadKey) return;
// On mobile the first tap navigates and closes the sidebar sheet, so the
// inline rename can't be shown. Renaming there stays on the context menu.
if (isMobile) return;
// cmd/ctrl/shift double-clicks are multi-select intent, not rename.
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
// Ignore double-clicks bubbling from nested controls (PR status, port,
// archive buttons) — only the row body should enter inline rename.
if ((event.target as HTMLElement).closest("button, a")) return;
event.preventDefault();
startThreadRename(threadKey, thread.title);
},
[isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title],
);
const handleRowKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (event.key !== "Enter" && event.key !== " ") return;
@@ -533,9 +510,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
void commitRename(threadRef, renamingTitle, thread.title);
}
}, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
// Keep clicks/double-clicks inside the rename input from bubbling to the row.
// Without stopping `dblclick`, double-clicking to select a word would re-fire
// the row's rename handler and reset the in-progress edit back to the title.
const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
}, []);
@@ -602,7 +576,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
isSelected,
})} relative isolate`}
onClick={handleRowClick}
onDoubleClick={handleRowDoubleClick}
onKeyDown={handleRowKeyDown}
onContextMenu={handleRowContextMenu}
>
@@ -634,7 +607,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
onKeyDown={handleRenameInputKeyDown}
onBlur={handleRenameInputBlur}
onClick={handleRenameInputClick}
onDoubleClick={handleRenameInputClick}
/>
) : (
<Tooltip>
@@ -817,7 +789,6 @@ interface SidebarProjectThreadListProps {
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
startThreadRename: (threadKey: string, title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
confirmingArchiveThreadKey: string | null;
@@ -868,7 +839,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
renamingThreadKey,
renamingTitle,
setRenamingTitle,
startThreadRename,
renamingInputRef,
renamingCommittedRef,
confirmingArchiveThreadKey,
@@ -920,7 +890,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
startThreadRename={startThreadRename}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
@@ -1657,13 +1626,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
// Ignore the trailing click of a plain double-click so it doesn't navigate
// while a double-click is starting an inline rename. Placed after the
// modifier branches so cmd/shift selection still processes every click.
if (isTrailingDoubleClick(event.detail)) {
return;
}
if (currentSelectionCount > 0) {
clearSelection();
}
@@ -1858,12 +1820,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
renamingInputRef.current = null;
}, []);
const startThreadRename = useCallback((threadKey: string, title: string) => {
setRenamingThreadKey(threadKey);
setRenamingTitle(title);
renamingCommittedRef.current = false;
}, []);
const commitRename = useCallback(
async (threadRef: ScopedThreadRef, newTitle: string, originalTitle: string) => {
const threadKey = scopedThreadKey(threadRef);
@@ -2023,7 +1979,9 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
);
if (clicked === "rename") {
startThreadRename(threadKey, thread.title);
setRenamingThreadKey(threadKey);
setRenamingTitle(thread.title);
renamingCommittedRef.current = false;
return;
}
@@ -2071,7 +2029,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
markThreadUnread,
memberProjectByScopedKey,
project.cwd,
startThreadRename,
],
);
@@ -2194,7 +2151,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
startThreadRename={startThreadRename}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
+73 -61
View File
@@ -56,7 +56,6 @@ import {
import { useComposerPathSearch } from "../../lib/composerPathSearchState";
import { type ElementContextDraft } from "../../lib/elementContext";
import { ComposerPendingElementContexts } from "./ComposerPendingElementContexts";
import { ComposerPendingReviewComments } from "./ComposerPendingReviewComments";
import { ComposerPreviewAnnotationCards } from "./ComposerPreviewAnnotationCards";
import {
shouldUseCompactComposerPrimaryActions,
@@ -71,13 +70,13 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import {
getComposerProviderState,
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
} from "./composerProviderState";
import { useComposerMenuHighlight } from "./useComposerMenuHighlight";
import { ContextWindowMeter } from "./ContextWindowMeter";
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
import { basenameOfPath } from "../../pierre-icons";
@@ -118,7 +117,6 @@ import {
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -408,7 +406,6 @@ export interface ChatComposerHandle {
terminalContexts: TerminalContextDraft[];
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
reviewComments: ReviewCommentContext[];
selectedPromptEffort: string | null;
selectedModelOptionsForDispatch: unknown;
selectedModelSelection: ModelSelection;
@@ -618,7 +615,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerTerminalContexts = composerDraft.terminalContexts;
const composerElementContexts = composerDraft.elementContexts;
const composerPreviewAnnotations = composerDraft.previewAnnotations;
const composerReviewComments = composerDraft.reviewComments;
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
@@ -640,9 +636,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const removeComposerDraftPreviewAnnotation = useComposerDraftStore(
(store) => store.removePreviewAnnotation,
);
const removeComposerDraftReviewComment = useComposerDraftStore(
(store) => store.removeReviewComment,
);
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
@@ -865,6 +858,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const [composerTrigger, setComposerTrigger] = useState<ComposerTrigger | null>(() =>
detectComposerTrigger(prompt, prompt.length),
);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
null,
);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
@@ -899,16 +896,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
prompt,
imageCount: composerImages.length,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
composerPreviewAnnotations.length +
composerReviewComments.length,
elementContextCount: composerElementContexts.length + composerPreviewAnnotations.length,
}),
[
composerElementContexts.length,
composerImages.length,
composerPreviewAnnotations.length,
composerReviewComments.length,
composerTerminalContexts,
prompt,
],
@@ -1001,19 +994,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerMenuSearchKey = composerTrigger
? `${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}`
: null;
const {
activeItemId: activeComposerMenuItemId,
nudge: nudgeStoredComposerMenuHighlight,
reset: resetComposerMenuHighlight,
setHighlightedItemId: setComposerMenuHighlightedItemId,
} = useComposerMenuHighlight({
items: composerMenuItems,
menuOpen: composerMenuOpen,
searchKey: composerMenuSearchKey,
});
const activeComposerMenuItem = useMemo(() => {
return composerMenuItems.find((item) => item.id === activeComposerMenuItemId) ?? null;
}, [activeComposerMenuItemId, composerMenuItems]);
const activeItemId = resolveComposerMenuActiveItemId({
items: composerMenuItems,
highlightedItemId: composerHighlightedItemId,
currentSearchKey: composerMenuSearchKey,
highlightedSearchKey: composerHighlightedSearchKey,
});
return composerMenuItems.find((item) => item.id === activeItemId) ?? null;
}, [
composerHighlightedItemId,
composerHighlightedSearchKey,
composerMenuItems,
composerMenuSearchKey,
]);
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
@@ -1203,6 +1197,35 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerElementContextsRef.current = composerElementContexts;
}, [composerElementContexts, composerElementContextsRef]);
// ------------------------------------------------------------------
// Composer menu highlight sync
// ------------------------------------------------------------------
useEffect(() => {
if (!composerMenuOpen) {
setComposerHighlightedItemId(null);
setComposerHighlightedSearchKey(null);
return;
}
const nextActiveItemId = resolveComposerMenuActiveItemId({
items: composerMenuItems,
highlightedItemId: composerHighlightedItemId,
currentSearchKey: composerMenuSearchKey,
highlightedSearchKey: composerHighlightedSearchKey,
});
setComposerHighlightedItemId((existing) =>
existing === nextActiveItemId ? existing : nextActiveItemId,
);
setComposerHighlightedSearchKey((existing) =>
existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
);
}, [
composerHighlightedItemId,
composerHighlightedSearchKey,
composerMenuItems,
composerMenuOpen,
composerMenuSearchKey,
]);
const lastSyncedPendingInputRef = useRef<{
requestId: string | null;
questionId: string | null;
@@ -1240,25 +1263,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
expandCollapsedComposerCursor(nextCustomAnswer, nextCursor),
),
);
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
}, [
activePendingProgress?.customAnswer,
activePendingProgress?.activeQuestion?.id,
activePendingUserInput?.requestId,
promptRef,
resetComposerMenuHighlight,
]);
// ------------------------------------------------------------------
// Reset compositor state on thread/draft change
// ------------------------------------------------------------------
useEffect(() => {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
}, [activeThreadId, draftId, promptRef, resetComposerMenuHighlight]);
}, [draftId, activeThreadId, promptRef]);
// ------------------------------------------------------------------
// Footer compact layout observation
@@ -1544,7 +1566,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
);
if (applied) {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
}
return;
}
@@ -1555,7 +1577,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusEditorAfterReplace: false,
});
if (applied) {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
setIsComposerModelPickerOpen(true);
}
return;
@@ -1565,7 +1587,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
});
if (applied) {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
}
return;
}
@@ -1583,7 +1605,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
);
if (applied) {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
}
return;
}
@@ -1601,31 +1623,37 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{ expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
);
if (applied) {
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
}
return;
}
},
[
applyPromptReplacement,
handleInteractionModeChange,
resolveActiveComposerTrigger,
resetComposerMenuHighlight,
],
[applyPromptReplacement, handleInteractionModeChange, resolveActiveComposerTrigger],
);
const onComposerMenuItemHighlighted = useCallback(
(itemId: string | null) => {
setComposerMenuHighlightedItemId(itemId);
setComposerHighlightedItemId(itemId);
setComposerHighlightedSearchKey(composerMenuSearchKey);
},
[setComposerMenuHighlightedItemId],
[composerMenuSearchKey],
);
const nudgeComposerMenuHighlight = useCallback(
(key: "ArrowDown" | "ArrowUp") => {
nudgeStoredComposerMenuHighlight(key);
if (composerMenuItems.length === 0) return;
const highlightedIndex = composerMenuItems.findIndex(
(item) => item.id === composerHighlightedItemId,
);
const normalizedIndex =
highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
const offset = key === "ArrowDown" ? 1 : -1;
const nextIndex =
(normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
const nextItem = composerMenuItems[nextIndex];
setComposerHighlightedItemId(nextItem?.id ?? null);
},
[nudgeStoredComposerMenuHighlight],
[composerHighlightedItemId, composerMenuItems],
);
const blurMobileComposerAfterSend = useCallback(() => {
@@ -1918,7 +1946,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}) => {
const promptForState = options?.prompt ?? promptRef.current;
const cursor = clampCollapsedComposerCursor(promptForState, options?.cursor ?? 0);
resetComposerMenuHighlight();
setComposerHighlightedItemId(null);
setComposerCursor(cursor);
setComposerTrigger(
options?.detectTrigger
@@ -1970,7 +1998,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
terminalContexts: composerTerminalContextsRef.current,
elementContexts: composerElementContextsRef.current,
previewAnnotations: composerPreviewAnnotations,
reviewComments: composerReviewComments,
selectedPromptEffort,
selectedModelOptionsForDispatch,
selectedModelSelection,
@@ -1990,7 +2017,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerTerminalContextsRef,
composerElementContextsRef,
composerPreviewAnnotations,
composerReviewComments,
isConnecting,
isComposerApprovalState,
pendingUserInputs.length,
@@ -2005,7 +2031,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
selectedPromptEffort,
selectedProvider,
selectedProviderModels,
resetComposerMenuHighlight,
],
);
@@ -2247,19 +2272,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/>
)}
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerReviewComments.length > 0 && (
<ComposerPendingReviewComments
comments={composerReviewComments}
onRemove={(commentId) =>
removeComposerDraftReviewComment(composerDraftTarget, commentId)
}
className="mb-3"
/>
)}
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
+4 -4
View File
@@ -72,15 +72,15 @@ export const ChatHeader = memo(function ChatHeader({
primaryEnvironmentId,
});
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<Tooltip>
<TooltipTrigger
render={
<h2
aria-label={activeThreadTitle}
className="min-w-0 flex-1 truncate text-sm font-medium text-foreground"
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
>
{activeThreadTitle}
</h2>
@@ -92,7 +92,7 @@ export const ChatHeader = memo(function ChatHeader({
<div
data-chat-header-actions
className={cn(
"flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
"flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3",
rightPanelOpen ? "pr-0" : "pr-16",
)}
>
@@ -1,41 +0,0 @@
import "../../index.css";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
import { render } from "vitest-browser-react";
import { ComposerPendingReviewComments } from "./ComposerPendingReviewComments";
describe("ComposerPendingReviewComments", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("renders a removable file comment pill", async () => {
const onRemove = vi.fn();
const screen = await render(
<ComposerPendingReviewComments
comments={[
{
id: "comment-1",
sectionId: "file:src/app.ts",
sectionTitle: "File comment",
filePath: "src/app.ts",
startIndex: 1,
endIndex: 2,
rangeLabel: "L2 to L3",
text: "Keep this configurable.",
diff: "@@ -2,2 +2,2 @@\n two\n three",
},
]}
onRemove={onRemove}
/>,
);
await expect.element(page.getByText("src/app.ts L2 to L3")).toBeVisible();
await page.getByRole("button", { name: "Remove comment on src/app.ts L2 to L3" }).click();
expect(onRemove).toHaveBeenCalledWith("comment-1");
await screen.unmount();
});
});
@@ -1,60 +0,0 @@
import { MessageCircle, X } from "lucide-react";
import {
COMPOSER_INLINE_CHIP_CLASS_NAME,
COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
} from "../composerInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import type { ReviewCommentContext } from "~/reviewCommentContext";
import { cn } from "~/lib/utils";
interface ComposerPendingReviewCommentsProps {
comments: ReadonlyArray<ReviewCommentContext>;
onRemove: (commentId: string) => void;
className?: string;
}
export function ComposerPendingReviewComments({
comments,
onRemove,
className,
}: ComposerPendingReviewCommentsProps) {
if (comments.length === 0) return null;
return (
<div className={cn("flex flex-wrap gap-1.5", className)}>
{comments.map((comment) => {
const label = `${comment.filePath} ${comment.rangeLabel}`;
return (
<Tooltip key={comment.id}>
<TooltipTrigger
render={
<span className={cn(COMPOSER_INLINE_CHIP_CLASS_NAME, "pr-1")}>
<MessageCircle className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>
<button
type="button"
aria-label={`Remove comment on ${label}`}
className={COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onRemove(comment.id);
}}
>
<X className="size-3" aria-hidden />
</button>
</span>
}
/>
<TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap leading-tight">
{comment.text}
</TooltipPopup>
</Tooltip>
);
})}
</div>
);
}
@@ -296,42 +296,6 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("&lt;/review_comment&gt;");
});
it("renders file review comments as source code instead of diffs", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-source-comment"),
role: "user",
text: [
'<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
"Clarify this.",
"```md",
"# Plan",
"- Step one",
"```",
"</review_comment>",
].join("\n"),
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain("plan.md");
expect(markup).toContain("Clarify this.");
expect(markup).toContain("# Plan");
expect(markup).not.toContain('data-testid="file-diff"');
});
it("renders a failure marker for failed tool lifecycle entries", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
@@ -102,7 +102,6 @@ import { SkillInlineText } from "./SkillInlineText";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
import {
buildReviewCommentRenderablePatch,
formatReviewCommentFence,
parseReviewCommentMessageSegments,
type ReviewCommentContext,
} from "../../reviewCommentContext";
@@ -1271,7 +1270,6 @@ const UserMessageBody = memo(function UserMessageBody(props: {
function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
const ctx = use(TimelineRowCtx);
const fenceLanguage = comment.fenceLanguage ?? "diff";
const renderablePatch = getRenderablePatch(
buildReviewCommentRenderablePatch(comment),
`review-comment:${comment.id}`,
@@ -1292,15 +1290,6 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
<SkillInlineText text={comment.text} skills={ctx.skills} />
</div>
)}
{fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
<ChatMarkdown
text={formatReviewCommentFence(fenceLanguage, comment.diff)}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={ctx.skills}
className="text-foreground"
/>
)}
{renderablePatch?.kind === "files" &&
renderablePatch.files.map((fileDiff) => (
<FileDiff
+5 -25
View File
@@ -154,14 +154,10 @@ export const OpenInPicker = memo(function OpenInPicker({
keybindings,
availableEditors,
openInCwd,
compact = false,
enableShortcut = true,
}: {
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
openInCwd: string | null;
compact?: boolean;
enableShortcut?: boolean;
}) {
const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
const options = useMemo(
@@ -188,7 +184,6 @@ export const OpenInPicker = memo(function OpenInPicker({
);
useEffect(() => {
if (!enableShortcut) return;
const handler = (e: globalThis.KeyboardEvent) => {
const api = readLocalApi();
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
@@ -200,39 +195,24 @@ export const OpenInPicker = memo(function OpenInPicker({
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [enableShortcut, preferredEditor, keybindings, openInCwd]);
}, [preferredEditor, keybindings, openInCwd]);
return (
<Group aria-label="Open in editor">
<Group aria-label="Subscription actions">
<Button
aria-label={compact ? "Open file in preferred editor" : undefined}
size="xs"
variant="outline"
disabled={!preferredEditor || !openInCwd}
onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
<span
className={
compact
? "sr-only"
: "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5"
}
>
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
Open
</span>
</Button>
<GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu>
<MenuTrigger
render={
<Button
aria-label={compact ? "Choose editor" : "Copy options"}
size="icon-xs"
variant="outline"
/>
}
>
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
<ChevronDownIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
@@ -1,6 +1,8 @@
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react";
import { memo } from "react";
import { cn } from "~/lib/utils";
import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -11,8 +13,11 @@ interface PanelLayoutControlsProps {
rightPanelAvailable: boolean;
rightPanelOpen: boolean;
rightPanelShortcutLabel: string | null;
rightPanelMaximized: boolean;
canMaximizeRightPanel: boolean;
onToggleTerminal: () => void;
onToggleRightPanel: () => void;
onToggleRightPanelMaximized: () => void;
}
export const PanelLayoutControls = memo(function PanelLayoutControls({
@@ -22,14 +27,47 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
rightPanelAvailable,
rightPanelOpen,
rightPanelShortcutLabel,
rightPanelMaximized,
canMaximizeRightPanel,
onToggleTerminal,
onToggleRightPanel,
onToggleRightPanelMaximized,
}: PanelLayoutControlsProps) {
return (
<div
className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]"
className={cn("workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]")}
data-panel-layout-controls
>
{rightPanelOpen ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={rightPanelMaximized}
onPressedChange={onToggleRightPanelMaximized}
aria-label={rightPanelMaximized ? "Restore panel size" : "Maximize panel"}
variant="ghost"
size="sm"
disabled={!canMaximizeRightPanel}
>
{rightPanelMaximized ? (
<Minimize2Icon className="size-3.5" />
) : (
<Maximize2Icon className="size-3.5" />
)}
</Toggle>
}
/>
<TooltipPopup side="bottom">
{canMaximizeRightPanel
? rightPanelMaximized
? "Restore panel size"
: "Maximize panel"
: "Panel maximization is unavailable at this width"}
</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -77,36 +115,3 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
</div>
);
});
export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl({
maximized,
onToggle,
}: {
maximized: boolean;
onToggle: () => void;
}) {
const label = maximized ? "Restore panel size" : "Maximize panel";
return (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={maximized}
onPressedChange={onToggle}
aria-label={label}
variant="ghost"
size="sm"
>
{maximized ? (
<Minimize2Icon className="size-3.5" />
) : (
<Maximize2Icon className="size-3.5" />
)}
</Toggle>
}
/>
<TooltipPopup side="bottom">{label}</TooltipPopup>
</Tooltip>
);
});
@@ -1,124 +0,0 @@
import { useCallback, useMemo, useRef, useState } from "react";
import type { ComposerCommandItem } from "./ComposerCommandMenu";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
type ComposerMenuHighlightState = {
readonly itemId: string | null;
readonly searchKey: string | null;
readonly observedSearchKey: string | null;
readonly menuOpen: boolean;
};
function createResetHighlightState(input: {
readonly menuOpen: boolean;
readonly searchKey: string | null;
}): ComposerMenuHighlightState {
return {
itemId: null,
searchKey: null,
observedSearchKey: input.searchKey,
menuOpen: input.menuOpen,
};
}
function sameHighlightState(
left: ComposerMenuHighlightState,
right: ComposerMenuHighlightState,
): boolean {
return (
left.itemId === right.itemId &&
left.searchKey === right.searchKey &&
left.observedSearchKey === right.observedSearchKey &&
left.menuOpen === right.menuOpen
);
}
export function useComposerMenuHighlight(input: {
readonly items: ReadonlyArray<ComposerCommandItem>;
readonly menuOpen: boolean;
readonly searchKey: string | null;
}) {
const inputRef = useRef(input);
inputRef.current = input;
const [storedHighlightState, setStoredHighlightState] = useState<ComposerMenuHighlightState>(() =>
createResetHighlightState(input),
);
let highlightState = storedHighlightState;
if (
highlightState.menuOpen !== input.menuOpen ||
highlightState.observedSearchKey !== input.searchKey
) {
highlightState = createResetHighlightState(input);
setStoredHighlightState(highlightState);
}
const activeItemId = useMemo(() => {
if (!input.menuOpen) return null;
return resolveComposerMenuActiveItemId({
items: input.items,
highlightedItemId: highlightState.itemId,
currentSearchKey: input.searchKey,
highlightedSearchKey: highlightState.searchKey,
});
}, [
highlightState.itemId,
highlightState.searchKey,
input.items,
input.menuOpen,
input.searchKey,
]);
const activeItemIdRef = useRef(activeItemId);
activeItemIdRef.current = activeItemId;
const reset = useCallback(() => {
const currentInput = inputRef.current;
setStoredHighlightState((existing) => {
const next = createResetHighlightState(currentInput);
return sameHighlightState(existing, next) ? existing : next;
});
}, []);
const setHighlightedItemId = useCallback((itemId: string | null) => {
const currentInput = inputRef.current;
setStoredHighlightState((existing) => {
const next: ComposerMenuHighlightState = {
itemId,
searchKey: itemId === null ? null : currentInput.searchKey,
observedSearchKey: currentInput.searchKey,
menuOpen: currentInput.menuOpen,
};
return sameHighlightState(existing, next) ? existing : next;
});
}, []);
const nudge = useCallback(
(key: "ArrowDown" | "ArrowUp") => {
const currentInput = inputRef.current;
if (!currentInput.menuOpen || currentInput.items.length === 0) return;
const currentActiveItemId = activeItemIdRef.current;
const activeIndex = currentActiveItemId
? currentInput.items.findIndex((item) => item.id === currentActiveItemId)
: -1;
const normalizedIndex = activeIndex >= 0 ? activeIndex : key === "ArrowDown" ? -1 : 0;
const offset = key === "ArrowDown" ? 1 : -1;
const nextIndex =
(normalizedIndex + offset + currentInput.items.length) % currentInput.items.length;
const nextItem = currentInput.items[nextIndex];
setHighlightedItemId(nextItem?.id ?? null);
},
[setHighlightedItemId],
);
return useMemo(
() => ({
activeItemId,
nudge,
reset,
setHighlightedItemId,
}),
[activeItemId, nudge, reset, setHighlightedItemId],
);
}
@@ -1,122 +0,0 @@
import "../../index.css";
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "~/composerDraftStore";
import { AnnotatableFileDiff } from "./AnnotatableFileDiff";
function dispatchPointer(target: EventTarget, type: string, pointerId: number): void {
target.dispatchEvent(
new PointerEvent(type, {
bubbles: true,
cancelable: true,
composed: true,
pointerId,
pointerType: "mouse",
}),
);
}
const threadRef = scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread-1"));
function TestDiff() {
const fileDiff = parsePatchFiles(
[
"diff --git a/src/app.ts b/src/app.ts",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,3 +1,3 @@",
" one",
"-two",
"+TWO",
" three",
].join("\n"),
"annotatable-file-diff-test",
)[0]!.files[0]!;
return (
<AnnotatableFileDiff
fileDiff={fileDiff}
filePath="src/app.ts"
sectionId="turn:2"
sectionTitle="Turn 2"
composerDraftTarget={threadRef}
renderHeaderPrefix={() => null}
options={{
diffStyle: "unified",
lineDiffType: "none",
themeType: "light",
}}
/>
);
}
async function getRenderedDiff() {
return vi.waitFor(() => {
const element = document.querySelector<HTMLElement>("diffs-container");
expect(element?.shadowRoot).not.toBeNull();
return element!;
});
}
describe("annotatable Pierre file diff", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.getState().setReviewComments(threadRef, []);
});
it("creates a local annotation from the gutter and attaches it to the composer", async () => {
let screen = await render(<TestDiff />);
try {
const diff = await getRenderedDiff();
const addedLineNumber = await vi.waitFor(() => {
const elements = Array.from(
diff.shadowRoot?.querySelectorAll<HTMLElement>('[data-column-number="2"]') ?? [],
);
const element = elements.at(-1) ?? null;
expect(element).not.toBeNull();
return element!;
});
dispatchPointer(addedLineNumber, "pointerdown", 1);
dispatchPointer(addedLineNumber, "pointerup", 1);
const textarea = page.getByRole("textbox", { name: "Comment on lines +2" });
await expect.element(textarea).toBeVisible();
await textarea.fill("Use the compatible value.");
await page.getByRole("button", { name: "Comment" }).click();
await vi.waitFor(() => {
expect(
useComposerDraftStore.getState().getComposerDraft(threadRef)?.reviewComments,
).toEqual([
expect.objectContaining({
sectionId: "turn:2",
filePath: "src/app.ts",
rangeLabel: "+2",
text: "Use the compatible value.",
diff: "@@ -0,0 +2,1 @@\n+TWO",
}),
]);
});
expect(document.querySelector("[data-file-comment-annotation]")?.textContent).toContain(
"Use the compatible value.",
);
await screen.unmount();
screen = await render(<TestDiff />);
await expect
.element(page.getByText("Use the compatible value.", { exact: true }))
.toBeVisible();
} finally {
await screen.unmount();
}
});
});
@@ -1,239 +0,0 @@
import type {
AnnotationSide,
DiffLineAnnotation,
FileDiffMetadata,
SelectedLineRange,
} from "@pierre/diffs";
import { FileDiff, type FileDiffProps } from "@pierre/diffs/react";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import {
buildDiffReviewComment,
restoreDiffReviewCommentRange,
type ReviewCommentContext,
} from "~/reviewCommentContext";
import { LocalCommentAnnotation } from "../files/LocalCommentAnnotation";
import { nextFileCommentId } from "../files/fileCommentAnnotations";
interface DiffCommentAnnotationEntry {
id: string;
kind: "draft" | "comment";
range: SelectedLineRange;
rangeLabel: string;
text: string;
}
interface DiffCommentAnnotationGroup {
entries: DiffCommentAnnotationEntry[];
}
type DiffCommentLineAnnotation = DiffLineAnnotation<DiffCommentAnnotationGroup>;
const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = [];
function annotationSide(range: SelectedLineRange): AnnotationSide {
return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions";
}
function appendAnnotationEntry(
annotations: ReadonlyArray<DiffCommentLineAnnotation>,
range: SelectedLineRange,
entry: DiffCommentAnnotationEntry,
): DiffCommentLineAnnotation[] {
const side = annotationSide(range);
const annotationIndex = annotations.findIndex(
(annotation) => annotation.side === side && annotation.lineNumber === range.end,
);
if (annotationIndex < 0) {
return [
...annotations,
{
side,
lineNumber: range.end,
metadata: { entries: [entry] },
},
];
}
return annotations.map((annotation, index) =>
index === annotationIndex
? {
...annotation,
metadata: { entries: [...annotation.metadata.entries, entry] },
}
: annotation,
);
}
interface AnnotatableFileDiffProps {
fileDiff: FileDiffMetadata;
filePath: string;
sectionId: string;
sectionTitle: string;
composerDraftTarget: ScopedThreadRef | DraftId;
options: FileDiffProps<DiffCommentAnnotationGroup>["options"];
renderHeaderPrefix: (fileDiff: FileDiffMetadata) => ReactNode;
}
export function AnnotatableFileDiff({
fileDiff,
filePath,
sectionId,
sectionTitle,
composerDraftTarget,
options,
renderHeaderPrefix,
}: AnnotatableFileDiffProps) {
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
const reviewComments = useComposerDraftStore(
(store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
);
const [selectedRange, setSelectedRange] = useState<SelectedLineRange | null>(null);
const [draftAnnotation, setDraftAnnotation] = useState<DiffCommentLineAnnotation | null>(null);
const persistedAnnotations = useMemo(
() =>
reviewComments
.filter(
(comment) =>
comment.sectionId === sectionId &&
comment.filePath === filePath &&
(comment.fenceLanguage ?? "diff") === "diff",
)
.reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
const range = restoreDiffReviewCommentRange(fileDiff, comment);
if (!range) return annotations;
return appendAnnotationEntry(annotations, range, {
id: comment.id,
kind: "comment",
range,
rangeLabel: comment.rangeLabel,
text: comment.text,
});
}, []),
[fileDiff, filePath, reviewComments, sectionId],
);
const lineAnnotations = useMemo(
() => (draftAnnotation ? [...persistedAnnotations, draftAnnotation] : persistedAnnotations),
[draftAnnotation, persistedAnnotations],
);
const removeAnnotationEntry = useCallback(
(entryId: string) => {
setSelectedRange(null);
if (
draftAnnotation?.metadata.entries.some(
(entry) => entry.id === entryId && entry.kind === "draft",
)
) {
setDraftAnnotation(null);
return;
}
removeReviewComment(composerDraftTarget, entryId);
},
[composerDraftTarget, draftAnnotation, removeReviewComment],
);
const submitAnnotationEntry = useCallback(
(entryId: string, text: string) => {
const entry = draftAnnotation?.metadata.entries.find((candidate) => candidate.id === entryId);
if (!entry) return;
const comment = buildDiffReviewComment({
id: entry.id,
sectionId,
sectionTitle,
filePath,
fileDiff,
range: entry.range,
text,
});
if (comment) {
addReviewComment(composerDraftTarget, comment);
}
setSelectedRange(null);
setDraftAnnotation(null);
},
[
addReviewComment,
composerDraftTarget,
fileDiff,
filePath,
draftAnnotation,
sectionId,
sectionTitle,
],
);
const beginComment = useCallback(
(range: SelectedLineRange) => {
const id = nextFileCommentId();
const comment = buildDiffReviewComment({
id,
sectionId,
sectionTitle,
filePath,
fileDiff,
range,
text: "",
});
if (!comment) return;
const draftEntry: DiffCommentAnnotationEntry = {
id,
kind: "draft",
range,
rangeLabel: comment.rangeLabel,
text: "",
};
setDraftAnnotation({
side: annotationSide(range),
lineNumber: range.end,
metadata: { entries: [draftEntry] },
});
},
[fileDiff, filePath, sectionId, sectionTitle],
);
const hasOpenCommentForm = draftAnnotation !== null;
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedRange(range);
if (range) beginComment(range);
},
[beginComment],
);
return (
<FileDiff<DiffCommentAnnotationGroup>
fileDiff={fileDiff}
renderHeaderPrefix={renderHeaderPrefix}
options={{
...options,
enableGutterUtility: !hasOpenCommentForm,
enableLineSelection: !hasOpenCommentForm,
onGutterUtilityClick: setSelectedRange,
onLineSelectionChange: setSelectedRange,
onLineSelectionEnd: handleLineSelectionEnd,
}}
selectedLines={selectedRange}
lineAnnotations={lineAnnotations}
renderAnnotation={(annotation) => (
<div className="py-1">
{annotation.metadata.entries.map((entry) => (
<LocalCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={entry.rangeLabel}
text={entry.text}
onCancel={() => removeAnnotationEntry(entry.id)}
onComment={(text) => submitAnnotationEntry(entry.id, text)}
onDelete={() => removeAnnotationEntry(entry.id)}
/>
))}
</div>
)}
/>
);
}
@@ -1,168 +0,0 @@
import "../../index.css";
import type { LineAnnotation, SelectedLineRange } from "@pierre/diffs";
import { Editor } from "@pierre/diffs/editor";
import { EditorProvider, File } from "@pierre/diffs/react";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
import { render } from "vitest-browser-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { installFileEditorDismissal } from "./fileEditorDismissal";
interface AnnotationMetadata {
label: string;
}
function dispatchPointer(target: EventTarget, type: string, pointerId: number): void {
target.dispatchEvent(
new PointerEvent(type, {
bubbles: true,
cancelable: true,
composed: true,
pointerId,
pointerType: "mouse",
}),
);
}
function EditableAnnotatedFile() {
const [selectedLines, setSelectedLines] = useState<SelectedLineRange | null>(null);
const [lineAnnotations, setLineAnnotations] = useState<LineAnnotation<AnnotationMetadata>[]>([]);
const rootRef = useRef<HTMLDivElement>(null);
const editor = useMemo(() => new Editor<AnnotationMetadata>(), []);
useEffect(() => () => editor.cleanUp(), [editor]);
useEffect(() => {
const root = rootRef.current;
if (!root) return;
return installFileEditorDismissal({
root,
editor,
isBlocked: () => false,
onDismiss: () => setSelectedLines(null),
});
}, [editor]);
return (
<>
<div ref={rootRef}>
<EditorProvider editor={editor}>
<File<AnnotationMetadata>
file={{ name: "example.ts", contents: "one\ntwo\nthree\n" }}
options={{
disableFileHeader: true,
enableGutterUtility: true,
enableLineSelection: true,
onGutterUtilityClick: setSelectedLines,
onLineSelectionChange: setSelectedLines,
onLineSelectionEnd: (range) => {
setSelectedLines(range);
if (range) {
setLineAnnotations([
{
lineNumber: Math.max(range.start, range.end),
metadata: { label: `${range.start}:${range.end}` },
},
]);
}
},
}}
selectedLines={selectedLines}
lineAnnotations={lineAnnotations}
renderAnnotation={(annotation) => (
<div data-test-file-annotation contentEditable={false}>
{annotation.metadata.label}
</div>
)}
disableWorkerPool
contentEditable
/>
</EditorProvider>
</div>
<button type="button">Outside file</button>
</>
);
}
async function getEditableFile() {
const file = await vi.waitFor(() => {
const element = document.querySelector<HTMLElement>("diffs-container");
expect(element?.shadowRoot).not.toBeNull();
return element!;
});
const content = await vi.waitFor(() => {
const element = file?.shadowRoot?.querySelector<HTMLElement>("[data-content]") ?? null;
expect(element).not.toBeNull();
return element!;
});
return { file, content };
}
describe("editable Pierre file annotations", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("keeps gutter selection and annotations enabled while the file is editable", async () => {
const screen = await render(<EditableAnnotatedFile />);
try {
const { file, content } = await getEditableFile();
const secondLineNumber = await vi.waitFor(() => {
const element =
file?.shadowRoot?.querySelector<HTMLElement>('[data-column-number="2"]') ?? null;
expect(element).not.toBeNull();
return element;
});
await vi.waitFor(() => {
expect(
file?.shadowRoot?.querySelector("pre")?.hasAttribute("data-interactive-line-numbers"),
).toBe(true);
});
dispatchPointer(secondLineNumber!, "pointerdown", 1);
dispatchPointer(secondLineNumber!, "pointerup", 1);
await vi.waitFor(() => {
expect(document.querySelector("[data-test-file-annotation]")?.textContent).toBe("2:2");
});
expect(content.contentEditable).toBe("true");
expect(content.getAttribute("role")).toBe("textbox");
} finally {
await screen.unmount();
}
});
it("dismisses editor focus and selection with outside click or Escape", async () => {
const screen = await render(<EditableAnnotatedFile />);
try {
const { file, content } = await getEditableFile();
content.focus();
expect(file?.shadowRoot?.activeElement).toBe(content);
await page.getByRole("button", { name: "Outside file" }).click();
await vi.waitFor(() => {
expect(file?.shadowRoot?.activeElement).not.toBe(content);
});
content.focus();
expect(file?.shadowRoot?.activeElement).toBe(content);
content.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Escape",
bubbles: true,
cancelable: true,
composed: true,
}),
);
await vi.waitFor(() => {
expect(file?.shadowRoot?.activeElement).not.toBe(content);
});
} finally {
await screen.unmount();
}
});
});
@@ -1,82 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
formatFileCommentRange,
normalizeFileCommentRange,
remapFileCommentAnnotations,
} from "./fileCommentAnnotations";
import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";
describe("file comment annotations", () => {
it("normalizes and formats selected line ranges", () => {
expect(normalizeFileCommentRange({ start: 16, end: 7 })).toEqual({
startLine: 7,
endLine: 16,
});
expect(formatFileCommentRange(7, 7)).toBe("L7");
expect(formatFileCommentRange(7, 16)).toBe("L7 to L16");
});
it("keeps an annotation range attached when Pierre remaps its anchor line", () => {
expect(
remapFileCommentAnnotations([
{
lineNumber: 20,
metadata: {
entries: [
{
id: "comment-1",
kind: "comment",
startLine: 7,
endLine: 16,
text: "Keep this guarded.",
},
],
},
},
]),
).toEqual([
{
lineNumber: 20,
metadata: {
entries: [
{
id: "comment-1",
kind: "comment",
startLine: 11,
endLine: 20,
text: "Keep this guarded.",
},
],
},
},
]);
});
});
describe("isMarkdownPreviewFile", () => {
it("recognizes markdown and MDX files case-insensitively", () => {
expect(isMarkdownPreviewFile("README.md")).toBe(true);
expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
});
it("does not treat other text files as markdown", () => {
expect(isMarkdownPreviewFile("docs/guide.txt")).toBe(false);
expect(isMarkdownPreviewFile("docs/markdown.ts")).toBe(false);
});
});
describe("setMarkdownTaskChecked", () => {
const markdown = "- [ ] First\n- [x] Second\n";
it("checks and unchecks the task marker at the supplied offset", () => {
expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");
expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");
expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");
});
it("leaves the document unchanged for a stale or invalid marker offset", () => {
expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);
expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);
});
});
@@ -1,51 +1,23 @@
import type {
EditorId,
EnvironmentId,
ResolvedKeybindingsConfig,
ScopedThreadRef,
} from "@t3tools/contracts";
import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
import type { EnvironmentId } from "@t3tools/contracts";
import { Editor } from "@pierre/diffs/editor";
import { EditorProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
import { ChevronRight, Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { EditorProvider, File, Virtualizer } from "@pierre/diffs/react";
import { ChevronRight, FolderTree, LoaderCircle } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import ChatMarkdown from "~/components/ChatMarkdown";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { ensureEnvironmentApi } from "~/environmentApi";
import { usePrimaryEnvironmentId } from "~/environments/primary/context";
import { useTheme } from "~/hooks/useTheme";
import { resolveDiffThemeName } from "~/lib/diffRendering";
import { cn } from "~/lib/utils";
import { isPreviewSupportedInRuntime } from "~/previewStateStore";
import { resolvePathLinkTarget } from "~/terminal-links";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Toggle } from "~/components/ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { buildFileReviewComment } from "~/reviewCommentContext";
import FileBrowserPanel from "./FileBrowserPanel";
import {
type FileCommentAnnotationEntry,
type FileCommentAnnotationGroup,
type FileCommentLineAnnotation,
formatFileCommentRange,
nextFileCommentId,
normalizeFileCommentRange,
remapFileCommentAnnotations,
} from "./fileCommentAnnotations";
import { installFileEditorDismissal } from "./fileEditorDismissal";
import { LocalCommentAnnotation } from "./LocalCommentAnnotation";
import { projectFileCacheKey } from "./fileContentRevision";
import { fileBreadcrumbs } from "./filePath";
import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";
import { FileSaveCoordinator } from "./fileSaveCoordinator";
import {
confirmProjectFileQueryData,
getOptimisticProjectFileQueryData,
setProjectFileQueryData,
useProjectFileQuery,
} from "./projectFilesQueryState";
@@ -55,208 +27,31 @@ interface FilePreviewPanelProps {
cwd: string;
projectName: string;
relativePath: string | null;
threadRef: ScopedThreadRef;
composerDraftTarget: ScopedThreadRef | DraftId;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
revealLine: number | null;
revealRequestId: number;
onOpenFile: (relativePath: string) => void;
onPendingChange: (relativePath: string, pending: boolean) => void;
}
const FILE_EXPLORER_STORAGE_KEY = "t3code.fileExplorerOpen";
const FILE_SAVE_DEBOUNCE_MS = 500;
const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal";
const FILE_LINK_REVEAL_UNSAFE_CSS = `
[${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] {
background-color: light-dark(
color-mix(
in lab,
var(--diffs-computed-diff-line-bg) 82%,
var(--diffs-bg-selection-override, var(--diffs-selection-base))
),
color-mix(
in lab,
var(--diffs-computed-diff-line-bg) 75%,
var(--diffs-bg-selection-override, var(--diffs-selection-base))
)
) !important;
}
[${FILE_LINK_REVEAL_ATTRIBUTE}][data-column-number] {
background-color: light-dark(
color-mix(
in lab,
var(--diffs-computed-diff-line-bg) 75%,
var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
),
color-mix(
in lab,
var(--diffs-computed-diff-line-bg) 60%,
var(--diffs-bg-selection-number-override, var(--diffs-selection-base))
)
) !important;
color: var(--diffs-selection-number-fg) !important;
}
`;
type FilePostRender = NonNullable<FileOptions<unknown>["onPostRender"]>;
function clampFileLine(contents: string, requestedLine: number): number {
let lineCount = 1;
for (let index = 0; index < contents.length; index += 1) {
const character = contents.charCodeAt(index);
if (character === 10) {
lineCount += 1;
} else if (character === 13) {
lineCount += 1;
if (contents.charCodeAt(index + 1) === 10) index += 1;
}
}
return Math.min(Math.max(1, requestedLine), lineCount);
}
function updateFileLinkReveal(fileContainer: HTMLElement, line: number | null): void {
const root = fileContainer.shadowRoot ?? fileContainer;
for (const element of root.querySelectorAll<HTMLElement>(`[${FILE_LINK_REVEAL_ATTRIBUTE}]`)) {
element.removeAttribute(FILE_LINK_REVEAL_ATTRIBUTE);
}
if (line === null) return;
root
.querySelector<HTMLElement>(`[data-line="${line}"]`)
?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
root
.querySelector<HTMLElement>(`[data-column-number="${line}"]`)
?.setAttribute(FILE_LINK_REVEAL_ATTRIBUTE, "");
}
function useFileLineReveal(
relativePath: string | null,
revealLine: number | null,
revealRequestId: number,
): FilePostRender {
const [handledRequestIdsByPath] = useState(() => new Map<string, number>());
const [latestRequestIdsByPath] = useState(() => new Map<string, number>());
const [pendingFramesByPath] = useState(() => new Map<string, number>());
return useCallback<FilePostRender>(
(fileContainer, instance, phase) => {
if (relativePath === null) return;
const cancelPendingReveal = () => {
const frameId = pendingFramesByPath.get(relativePath);
if (frameId !== undefined) {
cancelAnimationFrame(frameId);
pendingFramesByPath.delete(relativePath);
}
};
if (phase === "unmount") {
cancelPendingReveal();
return;
}
const targetLine =
revealLine === null ? null : clampFileLine(instance.file?.contents ?? "", revealLine);
updateFileLinkReveal(fileContainer, targetLine);
if (!(instance instanceof VirtualizedFile)) return;
if (latestRequestIdsByPath.get(relativePath) !== revealRequestId) {
cancelPendingReveal();
latestRequestIdsByPath.set(relativePath, revealRequestId);
}
if (targetLine === null) {
fileContainer.style.minHeight = "";
return;
}
const scrollContainer = fileContainer.closest<HTMLElement>(".file-preview-virtualizer");
if (!scrollContainer) return;
fileContainer.style.minHeight = `${Math.ceil(
Math.max(instance.height, scrollContainer.clientHeight),
)}px`;
if (
handledRequestIdsByPath.get(relativePath) === revealRequestId ||
pendingFramesByPath.has(relativePath)
) {
return;
}
const reveal = () => {
pendingFramesByPath.delete(relativePath);
if (
latestRequestIdsByPath.get(relativePath) !== revealRequestId ||
!fileContainer.isConnected
) {
return;
}
const linePosition = instance.getLinePosition(targetLine);
if (!linePosition) return;
const fileTop =
scrollContainer.scrollTop +
fileContainer.getBoundingClientRect().top -
scrollContainer.getBoundingClientRect().top;
const centeredTop = Math.max(
0,
fileTop +
linePosition.top -
Math.max(0, (scrollContainer.clientHeight - linePosition.height) / 2),
);
const maxScrollTop = Math.max(
0,
scrollContainer.scrollHeight - scrollContainer.clientHeight,
);
scrollContainer.scrollTop = Math.min(centeredTop, maxScrollTop);
handledRequestIdsByPath.set(relativePath, revealRequestId);
};
pendingFramesByPath.set(relativePath, requestAnimationFrame(reveal));
},
[
handledRequestIdsByPath,
latestRequestIdsByPath,
pendingFramesByPath,
relativePath,
revealLine,
revealRequestId,
],
);
}
interface EditableFileSurfaceProps {
environmentId: EnvironmentId;
cwd: string;
relativePath: string;
composerDraftTarget: ScopedThreadRef | DraftId;
contents: string;
resolvedTheme: "light" | "dark";
revealRequestId: number;
onPostRender: FilePostRender;
onPendingChange: (relativePath: string, pending: boolean) => void;
}
interface FileSelectionOverride {
revealRequestId: number;
range: SelectedLineRange | null;
}
function useFileSaveCoordinator({
function EditableFileSurface({
environmentId,
cwd,
relativePath,
contents,
resolvedTheme,
onPendingChange,
}: Pick<
EditableFileSurfaceProps,
"environmentId" | "cwd" | "relativePath" | "onPendingChange"
>): FileSaveCoordinator {
const coordinator = useMemo(
}: EditableFileSurfaceProps) {
const saveCoordinator = useMemo(
() =>
new FileSaveCoordinator({
debounceMs: FILE_SAVE_DEBOUNCE_MS,
@@ -274,309 +69,51 @@ function useFileSaveCoordinator({
}),
[cwd, environmentId, onPendingChange, relativePath],
);
useEffect(() => () => coordinator.dispose(), [coordinator]);
return coordinator;
}
function EditableFileSurface({
environmentId,
cwd,
relativePath,
composerDraftTarget,
contents,
resolvedTheme,
revealRequestId,
onPostRender,
onPendingChange,
}: EditableFileSurfaceProps) {
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
const [lineAnnotations, setLineAnnotations] = useState<FileCommentLineAnnotation[]>([]);
const [selectionOverride, setSelectionOverride] = useState<FileSelectionOverride | null>(null);
const selectedRange =
selectionOverride?.revealRequestId === revealRequestId ? selectionOverride.range : null;
const setSelectedRange = useCallback(
(range: SelectedLineRange | null) => {
setSelectionOverride({ revealRequestId, range });
},
[revealRequestId],
);
const surfaceRef = useRef<HTMLDivElement>(null);
const selectionFrameRef = useRef<number | null>(null);
const saveCoordinator = useFileSaveCoordinator({
environmentId,
cwd,
relativePath,
onPendingChange,
});
const editor = useMemo(
() =>
new Editor<FileCommentAnnotationGroup>({
onChange: (file, nextLineAnnotations) => {
new Editor({
onChange: (file) => {
setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
saveCoordinator.change(file.contents);
if (nextLineAnnotations) {
const remapped = remapFileCommentAnnotations(
nextLineAnnotations as FileCommentLineAnnotation[],
);
setLineAnnotations(remapped);
for (const annotation of remapped) {
for (const entry of annotation.metadata.entries) {
if (entry.kind !== "comment") continue;
addReviewComment(
composerDraftTarget,
buildFileReviewComment({
id: entry.id,
filePath: relativePath,
startLine: entry.startLine,
endLine: entry.endLine,
text: entry.text,
contents: file.contents,
}),
);
}
}
}
},
}),
[addReviewComment, composerDraftTarget, cwd, environmentId, relativePath, saveCoordinator],
[cwd, environmentId, relativePath, saveCoordinator],
);
useEffect(
() => () => {
editor.cleanUp();
saveCoordinator.dispose();
},
[editor],
);
const removeAnnotationEntry = useCallback(
(entryId: string) => {
setSelectedRange(null);
removeReviewComment(composerDraftTarget, entryId);
setLineAnnotations((current) => {
return current.flatMap((annotation) => {
const entries = annotation.metadata.entries.filter((entry) => entry.id !== entryId);
return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
});
});
},
[composerDraftTarget, removeReviewComment, setSelectedRange],
);
const submitAnnotationEntry = useCallback(
(entryId: string, text: string) => {
setSelectedRange(null);
const entry = lineAnnotations
.flatMap((annotation) => annotation.metadata.entries)
.find((candidate) => candidate.id === entryId);
if (entry) {
addReviewComment(
composerDraftTarget,
buildFileReviewComment({
id: entry.id,
filePath: relativePath,
startLine: entry.startLine,
endLine: entry.endLine,
text,
contents,
}),
);
}
setLineAnnotations((current) =>
current.map((annotation) => ({
...annotation,
metadata: {
entries: annotation.metadata.entries.map((annotationEntry) =>
annotationEntry.id === entryId
? { ...annotationEntry, kind: "comment", text }
: annotationEntry,
),
},
})),
);
},
[
addReviewComment,
composerDraftTarget,
contents,
lineAnnotations,
relativePath,
setSelectedRange,
],
);
const beginComment = useCallback((range: SelectedLineRange) => {
const { startLine, endLine } = normalizeFileCommentRange(range);
const draftEntry: FileCommentAnnotationEntry = {
id: nextFileCommentId(),
kind: "draft",
startLine,
endLine,
text: "",
};
setLineAnnotations((current) => {
const withoutDraft = current.flatMap((annotation) => {
const entries = annotation.metadata.entries.filter((entry) => entry.kind !== "draft");
return entries.length > 0 ? [{ ...annotation, metadata: { entries } }] : [];
});
const existingIndex = withoutDraft.findIndex(
(annotation) => annotation.lineNumber === endLine,
);
if (existingIndex < 0) {
return [
...withoutDraft,
{
lineNumber: endLine,
metadata: { entries: [draftEntry] },
},
];
}
return withoutDraft.map((annotation, index) =>
index === existingIndex
? {
...annotation,
metadata: { entries: [...annotation.metadata.entries, draftEntry] },
}
: annotation,
);
});
}, []);
const hasOpenCommentForm = lineAnnotations.some((annotation) =>
annotation.metadata.entries.some((entry) => entry.kind === "draft"),
);
useEffect(() => {
const root = surfaceRef.current;
if (!root) return;
return installFileEditorDismissal({
root,
editor,
isBlocked: () => hasOpenCommentForm,
onDismiss: () => setSelectedRange(null),
});
}, [editor, hasOpenCommentForm, setSelectedRange]);
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedRange(range);
if (range) {
beginComment(range);
}
},
[beginComment, setSelectedRange],
);
const handlePostRender = useCallback<FilePostRender>(
(fileContainer, instance, phase) => {
onPostRender(fileContainer, instance, phase);
if (selectionFrameRef.current !== null) {
cancelAnimationFrame(selectionFrameRef.current);
selectionFrameRef.current = null;
}
if (phase === "unmount") return;
selectionFrameRef.current = requestAnimationFrame(() => {
selectionFrameRef.current = null;
if (!fileContainer.isConnected) return;
instance.setSelectedLines(selectedRange, { notify: false });
});
},
[onPostRender, selectedRange],
[editor, saveCoordinator],
);
return (
<EditorProvider editor={editor}>
<div ref={surfaceRef} className="flex min-h-0 flex-1">
<Virtualizer
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
}}
>
<File<FileCommentAnnotationGroup>
file={{
name: relativePath,
contents,
cacheKey: projectFileCacheKey(cwd, relativePath, contents),
}}
options={{
disableFileHeader: true,
enableGutterUtility: !hasOpenCommentForm,
enableLineSelection: !hasOpenCommentForm,
onGutterUtilityClick: setSelectedRange,
onLineSelectionChange: setSelectedRange,
onLineSelectionEnd: handleLineSelectionEnd,
overflow: "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
onPostRender: handlePostRender,
}}
selectedLines={selectedRange}
lineAnnotations={lineAnnotations}
renderAnnotation={(annotation) => (
<div className="py-1">
{annotation.metadata.entries.map((entry) => (
<LocalCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
text={entry.text}
onCancel={() => removeAnnotationEntry(entry.id)}
onComment={(text) => submitAnnotationEntry(entry.id, text)}
onDelete={() => removeAnnotationEntry(entry.id)}
/>
))}
</div>
)}
className="min-h-full"
contentEditable
/>
</Virtualizer>
</div>
</EditorProvider>
);
}
function RenderedMarkdownSurface({
environmentId,
cwd,
relativePath,
contents,
threadRef,
onPendingChange,
}: Omit<
EditableFileSurfaceProps,
"resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender"
> & {
threadRef: ScopedThreadRef;
}) {
const saveCoordinator = useFileSaveCoordinator({
environmentId,
cwd,
relativePath,
onPendingChange,
});
return (
<ScrollArea className="min-h-0 flex-1">
<ChatMarkdown
text={contents}
cwd={cwd}
threadRef={threadRef}
className="mx-auto max-w-4xl px-6 py-5"
onTaskListChange={({ markerOffset, checked }) => {
const currentContents =
getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
contents;
const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
if (nextContents === currentContents) return;
setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
saveCoordinator.change(nextContents);
<Virtualizer
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
}}
/>
</ScrollArea>
>
<File
file={{
name: relativePath,
contents,
cacheKey: projectFileCacheKey(cwd, relativePath, contents),
}}
options={{
disableFileHeader: true,
overflow: "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
}}
className="min-h-full"
contentEditable
/>
</Virtualizer>
</EditorProvider>
);
}
@@ -593,37 +130,17 @@ export default function FilePreviewPanel({
cwd,
projectName,
relativePath,
threadRef,
composerDraftTarget,
keybindings,
availableEditors,
revealLine,
revealRequestId,
onOpenFile,
onPendingChange,
}: FilePreviewPanelProps) {
const { resolvedTheme } = useTheme();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const file = useProjectFileQuery(environmentId, cwd, relativePath);
const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);
const [markdownView, setMarkdownView] = useState<{
path: string | null;
revealRequestId: number | null;
}>({ path: null, revealRequestId: null });
const breadcrumbRef = useRef<HTMLDivElement>(null);
const isMarkdown = relativePath ? isMarkdownPreviewFile(relativePath) : false;
const renderMarkdown =
isMarkdown &&
markdownView.path === relativePath &&
(revealLine === null || markdownView.revealRequestId === revealRequestId);
const canOpenInBrowser =
relativePath !== null && isPreviewSupportedInRuntime() && isBrowserPreviewFile(relativePath);
const absolutePath = relativePath ? resolvePathLinkTarget(relativePath, cwd) : null;
const breadcrumbs = useMemo(
() => (relativePath ? fileBreadcrumbs(projectName, relativePath) : []),
[projectName, relativePath],
);
const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);
useEffect(() => {
const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(
@@ -642,19 +159,6 @@ export default function FilePreviewPanel({
});
};
const handleOpenInBrowser = () => {
if (!absolutePath) return;
void openFileInPreview(threadRef, absolutePath).catch((error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to open file in browser",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
});
};
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
{relativePath ? (
@@ -691,60 +195,6 @@ export default function FilePreviewPanel({
))}
</div>
</ScrollArea>
{absolutePath && environmentId === primaryEnvironmentId ? (
<OpenInPicker
keybindings={keybindings}
availableEditors={availableEditors}
openInCwd={absolutePath}
compact
enableShortcut={false}
/>
) : null}
{isMarkdown ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={renderMarkdown}
onPressedChange={(pressed) => {
setMarkdownView({
path: pressed ? relativePath : null,
revealRequestId: pressed ? revealRequestId : null,
});
}}
aria-label={renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
variant="ghost"
size="sm"
>
{renderMarkdown ? <Code2 className="size-3.5" /> : <Eye className="size-3.5" />}
</Toggle>
}
/>
<TooltipPopup>
{renderMarkdown ? "Show markdown source" : "Show rendered markdown"}
</TooltipPopup>
</Tooltip>
) : null}
{canOpenInBrowser ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={false}
onPressedChange={handleOpenInBrowser}
aria-label="Open file in preview browser"
variant="ghost"
size="sm"
>
<Globe2 className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup>Open file in preview browser</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -787,16 +237,7 @@ export default function FilePreviewPanel({
<LoaderCircle className="size-5 animate-spin" />
</div>
) : relativePath && file.data ? (
isMarkdown && renderMarkdown ? (
<RenderedMarkdownSurface
environmentId={environmentId}
cwd={cwd}
relativePath={relativePath}
threadRef={threadRef}
contents={file.data.contents}
onPendingChange={onPendingChange}
/>
) : file.data.truncated ? (
file.data.truncated ? (
<Virtualizer
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
@@ -816,8 +257,6 @@ export default function FilePreviewPanel({
overflow: "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
onPostRender: onFilePostRender,
}}
className="min-h-full"
/>
@@ -828,11 +267,8 @@ export default function FilePreviewPanel({
environmentId={environmentId}
cwd={cwd}
relativePath={relativePath}
composerDraftTarget={composerDraftTarget}
contents={file.data.contents}
resolvedTheme={resolvedTheme}
revealRequestId={revealRequestId}
onPostRender={onFilePostRender}
onPendingChange={onPendingChange}
/>
)
@@ -1,90 +0,0 @@
import { MessageCircle, Trash2 } from "lucide-react";
import { useState } from "react";
import { Button } from "~/components/ui/button";
import { Textarea } from "~/components/ui/textarea";
interface LocalCommentAnnotationProps {
kind: "draft" | "comment";
rangeLabel: string;
text: string;
onCancel: () => void;
onComment: (text: string) => void;
onDelete: () => void;
}
export function LocalCommentAnnotation({
kind,
rangeLabel,
text: savedText,
onCancel,
onComment,
onDelete,
}: LocalCommentAnnotationProps) {
const [text, setText] = useState("");
if (kind === "comment") {
return (
<div
data-file-comment-annotation
className="mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 shadow-sm"
contentEditable={false}
onPointerDown={(event) => event.stopPropagation()}
>
<div className="flex items-center gap-2">
<MessageCircle className="size-4 text-muted-foreground" />
<span className="text-xs font-medium">Local comment</span>
<span className="ml-auto text-[11px] text-muted-foreground">{rangeLabel}</span>
<Button variant="ghost" size="icon-xs" aria-label="Delete comment" onClick={onDelete}>
<Trash2 className="size-3.5" />
</Button>
</div>
<p className="mt-2 whitespace-pre-wrap text-sm leading-relaxed text-foreground">
{savedText}
</p>
</div>
);
}
return (
<div
data-file-comment-annotation
className="mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 shadow-lg"
contentEditable={false}
onPointerDown={(event) => event.stopPropagation()}
>
<div className="flex items-center gap-2">
<MessageCircle className="size-4 text-muted-foreground" />
<span className="text-sm font-medium">Local comment</span>
</div>
<div className="mt-1 text-xs text-muted-foreground">Comment on lines {rangeLabel}</div>
<Textarea
autoFocus
className="mt-3"
size="sm"
value={text}
placeholder="Request change"
aria-label={`Comment on lines ${rangeLabel}`}
onChange={(event) => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
onCancel();
}
if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && text.trim()) {
event.preventDefault();
onComment(text.trim());
}
}}
/>
<div className="mt-3 flex justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onCancel}>
Cancel
</Button>
<Button size="sm" disabled={!text.trim()} onClick={() => onComment(text.trim())}>
Comment
</Button>
</div>
</div>
);
}
@@ -1,54 +0,0 @@
import type { LineAnnotation, SelectedLineRange } from "@pierre/diffs";
export interface FileCommentAnnotationEntry {
id: string;
kind: "draft" | "comment";
startLine: number;
endLine: number;
text: string;
}
export interface FileCommentAnnotationGroup {
entries: FileCommentAnnotationEntry[];
}
export type FileCommentLineAnnotation = LineAnnotation<FileCommentAnnotationGroup>;
let fileCommentSequence = 0;
export function nextFileCommentId(): string {
fileCommentSequence += 1;
return `file-comment-${Date.now()}-${fileCommentSequence}`;
}
export function normalizeFileCommentRange(range: SelectedLineRange): {
startLine: number;
endLine: number;
} {
return {
startLine: Math.min(range.start, range.end),
endLine: Math.max(range.start, range.end),
};
}
export function formatFileCommentRange(startLine: number, endLine: number): string {
return startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`;
}
export function remapFileCommentAnnotations(
annotations: ReadonlyArray<FileCommentLineAnnotation>,
): FileCommentLineAnnotation[] {
return annotations.map((annotation) => ({
...annotation,
metadata: {
entries: annotation.metadata.entries.map((entry) => {
const lineCount = entry.endLine - entry.startLine;
return {
...entry,
endLine: annotation.lineNumber,
startLine: Math.max(1, annotation.lineNumber - lineCount),
};
}),
},
}));
}
@@ -1,53 +0,0 @@
interface FileEditorDismissalOptions {
root: HTMLElement;
editor: {
setSelections: (selections: []) => void;
};
isBlocked: () => boolean;
onDismiss: () => void;
}
function dismissFileEditorInteraction({
root,
editor,
onDismiss,
}: Pick<FileEditorDismissalOptions, "root" | "editor" | "onDismiss">): void {
onDismiss();
editor.setSelections([]);
const file = root.querySelector<HTMLElement>("diffs-container");
const activeElement = file?.shadowRoot?.activeElement;
if (activeElement instanceof HTMLElement) {
activeElement.blur();
}
}
function isFileEditorFocused(root: HTMLElement): boolean {
const file = root.querySelector<HTMLElement>("diffs-container");
return file?.shadowRoot?.activeElement?.hasAttribute("data-content") === true;
}
export function installFileEditorDismissal({
root,
editor,
isBlocked,
onDismiss,
}: FileEditorDismissalOptions): () => void {
const handlePointerDown = (event: PointerEvent) => {
if (isBlocked() || event.composedPath().includes(root)) return;
dismissFileEditorInteraction({ root, editor, onDismiss });
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || isBlocked() || !isFileEditorFocused(root)) return;
event.preventDefault();
event.stopImmediatePropagation();
dismissFileEditorInteraction({ root, editor, onDismiss });
};
document.addEventListener("pointerdown", handlePointerDown, true);
document.addEventListener("keydown", handleKeyDown, true);
return () => {
document.removeEventListener("pointerdown", handlePointerDown, true);
document.removeEventListener("keydown", handleKeyDown, true);
};
}
@@ -1,18 +0,0 @@
export const isMarkdownPreviewFile = (path: string): boolean => /\.(?:md|mdx)$/i.test(path);
export function setMarkdownTaskChecked(
markdown: string,
markerOffset: number,
checked: boolean,
): string {
if (
markerOffset < 0 ||
markdown[markerOffset] !== "[" ||
!/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||
markdown[markerOffset + 2] !== "]"
) {
return markdown;
}
return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;
}
@@ -19,7 +19,6 @@ import {
confirmProjectFileQueryData,
getProjectEntriesQueryAtom,
getProjectFileQueryAtom,
getOptimisticProjectFileQueryData,
resolveProjectFileQueryData,
setProjectFileQueryData,
} from "./projectFilesQueryState";
@@ -105,10 +104,6 @@ describe("project files queries", () => {
setProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"220"}');
setProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"22"}');
expect(getOptimisticProjectFileQueryData(environmentId, "/repo", "convex.json")?.contents).toBe(
'{"nodeVersion":"22"}',
);
expect(
confirmProjectFileQueryData(environmentId, "/repo", "convex.json", '{"nodeVersion":"220"}'),
).toBe(false);
@@ -121,14 +121,6 @@ export function setProjectFileQueryData(
});
}
export function getOptimisticProjectFileQueryData(
environmentId: EnvironmentId,
cwd: string,
relativePath: string,
): ProjectReadFileResult | null {
return optimisticProjectFiles.get(fileKey(environmentId, cwd, relativePath))?.data ?? null;
}
export function confirmProjectFileQueryData(
environmentId: EnvironmentId,
cwd: string,
@@ -19,6 +19,7 @@ import {
type SourceControlDiscoveryResult,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Option from "effect/Option";
import { page } from "vite-plus/test/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -789,6 +790,41 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
it("shows advanced background activity controls when background intervals are customized", async () => {
setServerConfigSnapshot({
...createBaseServerConfig(),
settings: {
...DEFAULT_SERVER_SETTINGS,
backgroundActivity: {
schemaVersion: 1,
profile: "custom",
baseProfile: "balanced",
overrides: {
automaticGitFetchInterval: Duration.seconds(15),
},
},
},
});
mounted = await renderWithTestRouter(
<AppAtomRegistryProvider>
<GeneralSettingsPanel />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("Advanced", { exact: true })).toBeInTheDocument();
await page.getByRole("button", { name: "Configure advanced background activity" }).click();
const dialog = page.getByRole("dialog", { name: "Background Activity" });
await expect.element(dialog).toBeInTheDocument();
await expect.element(dialog.getByText("Shared policy")).toBeInTheDocument();
await expect.element(dialog.getByText("Git fetch interval")).toBeInTheDocument();
await expect.element(dialog.getByText("Provider health interval")).toBeInTheDocument();
await expect.element(dialog.getByText("Host power monitor")).toBeInTheDocument();
await expect.element(dialog.getByText("Idle host monitor")).toBeInTheDocument();
});
it("creates and shows a pairing link when network access is enabled", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
@@ -1,9 +1,19 @@
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
import {
ArchiveIcon,
ArchiveX,
InfoIcon,
LoaderIcon,
PlusIcon,
RefreshCwIcon,
SettingsIcon,
} from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { useCallback, useMemo, useRef, useState } from "react";
import {
defaultInstanceIdForDriver,
type BackgroundActivityProfile,
type BackgroundActivitySettings,
type DesktopUpdateChannel,
PROVIDER_DISPLAY_NAMES,
ProviderDriverKind,
@@ -13,6 +23,11 @@ import {
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import {
getBackgroundActivityBaseProfile,
getBackgroundActivityPresetSettings,
resolveServerBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
import { createModelSelection } from "@t3tools/shared/model";
import * as Arr from "effect/Array";
import * as Duration from "effect/Duration";
@@ -51,7 +66,23 @@ import { selectProjectsAcrossEnvironments, useStore } from "../../store";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { DraftInput } from "../ui/draft-input";
import {
NumberField,
NumberFieldDecrement,
NumberFieldGroup,
NumberFieldIncrement,
NumberFieldInput,
} from "../ui/number-field";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
@@ -101,7 +132,128 @@ const TIMESTAMP_FORMAT_LABELS = {
"24-hour": "24-hour",
} as const;
const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, string> = {
balanced: "Balanced",
performance: "Performance",
"battery-saver": "Battery saver",
};
type BackgroundActivityProfileOption = BackgroundActivityProfile | "advanced";
type BackgroundActivityOverridePatch = Partial<{
[K in keyof BackgroundActivitySettings["overrides"]]:
| BackgroundActivitySettings["overrides"][K]
| undefined;
}>;
const BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS: Record<BackgroundActivityProfileOption, string> = {
...BACKGROUND_ACTIVITY_PROFILE_LABELS,
advanced: "Advanced",
};
const BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS: Record<BackgroundActivityProfile, string> = {
balanced:
"Pauses background probes when clients are idle, the host is locked, or low power mode is active.",
performance: "Allows scoped background probes while any subscribed client remains connected.",
"battery-saver": "Also pauses background probes when the host or client is on battery.",
};
const ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION =
"Uses custom background intervals with the selected shared power policy.";
const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
const BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES: ReadonlyArray<{
readonly key:
| "pauseWhenHostLocked"
| "pauseWhenHostLowPower"
| "pauseWhenClientLowPower"
| "pauseWhenOnBattery";
readonly label: string;
}> = [
{ key: "pauseWhenHostLocked", label: "Pause when host is locked" },
{ key: "pauseWhenHostLowPower", label: "Pause on host low power" },
{ key: "pauseWhenClientLowPower", label: "Pause on client low power" },
{ key: "pauseWhenOnBattery", label: "Pause on battery" },
];
function durationToSeconds(duration: Duration.Duration): number {
return Math.round(Duration.toMillis(duration) / 1_000);
}
function normalizeIntervalSeconds(value: number | null): number {
if (value === null || !Number.isFinite(value)) {
return 0;
}
return Math.max(0, Math.round(value));
}
function resolveBackgroundActivityProfileOption(settings: {
readonly backgroundActivity: BackgroundActivitySettings;
}): BackgroundActivityProfileOption {
return settings.backgroundActivity.profile === "custom"
? "advanced"
: settings.backgroundActivity.profile;
}
function resetBackgroundActivitySettings() {
return {
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
};
}
function backgroundActivityProfileSettings(profile: BackgroundActivityProfile) {
return {
backgroundActivity: {
schemaVersion: 1 as const,
profile,
overrides: {},
},
};
}
function backgroundActivityOverrideSettings(
current: BackgroundActivitySettings,
overrides: BackgroundActivityOverridePatch,
) {
const nextOverrides: BackgroundActivityOverridePatch = {
...current.overrides,
...overrides,
};
for (const [key, value] of Object.entries(nextOverrides)) {
if (value === undefined) {
delete nextOverrides[key as keyof typeof nextOverrides];
}
}
return {
backgroundActivity: {
schemaVersion: 1 as const,
profile: "custom" as const,
baseProfile: getBackgroundActivityBaseProfile(current),
overrides: nextOverrides as BackgroundActivitySettings["overrides"],
},
};
}
function PolicyTooltip({ children }: { readonly children: string }) {
return (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
aria-label="Background policy details"
>
<InfoIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="top" className="max-w-72">
{children}
</TooltipPopup>
</Tooltip>
);
}
function withoutProviderInstanceKey<V>(
record: Readonly<Record<ProviderInstanceId, V>> | undefined,
@@ -410,9 +562,8 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
? ["Assistant output"]
: []),
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
? ["Automatic Git fetch interval"]
...(!Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity)
? ["Background activity"]
: []),
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
@@ -437,7 +588,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.defaultThreadEnvMode,
settings.diffIgnoreWhitespace,
settings.diffWordWrap,
settings.automaticGitFetchInterval,
settings.backgroundActivity,
settings.enableAssistantStreaming,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -463,7 +614,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
@@ -479,10 +630,262 @@ export function useSettingsRestore(onRestored?: () => void) {
};
}
function BackgroundActivityAdvancedDialog({
open,
onOpenChange,
}: {
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
}) {
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const activeProfile = getBackgroundActivityBaseProfile(settings.backgroundActivity);
const automaticGitFetchIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.automaticGitFetchInterval,
);
const providerHealthRefreshIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.providerHealthRefreshInterval,
);
const hostPowerMonitorActiveIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.hostPowerMonitorActiveInterval,
);
const hostPowerMonitorIdleIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.hostPowerMonitorIdleInterval,
);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>Background Activity</DialogTitle>
<DialogDescription>
Tune the shared power policy and the background intervals that feed it.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-0 px-6 pb-5">
<div className="overflow-hidden rounded-xl border bg-card text-card-foreground">
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="text-sm font-medium">Shared policy</div>
<p className="text-xs leading-relaxed text-muted-foreground">
Controls whether background work may run after a subscribed interval fires.
</p>
</div>
<Select
value={activeProfile}
onValueChange={(value) => {
if (
value === "balanced" ||
value === "performance" ||
value === "battery-saver"
) {
updateSettings({
backgroundActivity: {
schemaVersion: 1 as const,
profile: "custom" as const,
baseProfile: value,
overrides: settings.backgroundActivity.overrides,
},
});
}
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Shared background policy">
<SelectValue>{BACKGROUND_ACTIVITY_PROFILE_LABELS[activeProfile]}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="balanced">
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
</SelectItem>
<SelectItem hideIndicator value="performance">
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
</SelectItem>
<SelectItem hideIndicator value="battery-saver">
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
</SelectItem>
</SelectPopup>
</Select>
</div>
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="text-sm font-medium">Git fetch interval</div>
<p className="text-xs leading-relaxed text-muted-foreground">
Refresh remote branch status in the background.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={automaticGitFetchIntervalSeconds}
min={0}
step={5}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
automaticGitFetchInterval: Duration.seconds(
normalizeIntervalSeconds(value),
),
}),
)
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease Git fetch interval" />
<NumberFieldInput aria-label="Git fetch interval in seconds" />
<NumberFieldIncrement aria-label="Increase Git fetch interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
<div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="text-sm font-medium">Provider health interval</div>
<p className="text-xs leading-relaxed text-muted-foreground">
Refresh provider availability, versions, auth state, and model metadata.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={providerHealthRefreshIntervalSeconds}
min={0}
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
providerHealthRefreshInterval: Duration.seconds(
normalizeIntervalSeconds(value),
),
}),
)
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease provider health interval" />
<NumberFieldInput aria-label="Provider health interval in seconds" />
<NumberFieldIncrement aria-label="Increase provider health interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="text-sm font-medium">Host power monitor</div>
<p className="text-xs leading-relaxed text-muted-foreground">
Poll host power state while clients are active.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={hostPowerMonitorActiveIntervalSeconds}
min={5}
step={5}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
hostPowerMonitorActiveInterval: Duration.seconds(
normalizeIntervalSeconds(value),
),
}),
)
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease active host power interval" />
<NumberFieldInput aria-label="Active host power interval in seconds" />
<NumberFieldIncrement aria-label="Increase active host power interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 space-y-1">
<div className="text-sm font-medium">Idle host monitor</div>
<p className="text-xs leading-relaxed text-muted-foreground">
Poll host power state when no foreground client is active.
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={hostPowerMonitorIdleIntervalSeconds}
min={5}
step={30}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
hostPowerMonitorIdleInterval: Duration.seconds(
normalizeIntervalSeconds(value),
),
}),
)
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease idle host power interval" />
<NumberFieldInput aria-label="Idle host power interval in seconds" />
<NumberFieldIncrement aria-label="Increase idle host power interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
</div>
<div className="grid gap-0 border-t sm:grid-cols-2">
{BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES.map(({ key, label }) => (
<label
key={key}
className="flex items-center justify-between gap-3 border-b px-4 py-3 last:border-b-0 sm:border-r sm:even:border-r-0"
>
<span className="text-sm font-medium">{label}</span>
<Switch
checked={resolvedBackgroundActivity[key]}
onCheckedChange={(checked) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
[key]: Boolean(checked),
}),
)
}
aria-label={label}
/>
</label>
))}
</div>
</div>
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
onClick={() => updateSettings(resetBackgroundActivitySettings())}
>
Reset all
</Button>
<Button onClick={() => onOpenChange(false)}>Done</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
const observability = useServerObservability();
const serverProviders = useServerProviders();
const diagnosticsDescription = formatDiagnosticsDescription({
@@ -515,6 +918,21 @@ export function GeneralSettingsPanel() {
settings.textGenerationModelSelection ?? null,
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
);
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const activeBackgroundActivityProfile = getBackgroundActivityBaseProfile(
settings.backgroundActivity,
);
const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
const backgroundActivityDescription =
backgroundActivityProfileOption === "advanced"
? `${ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION} Current shared policy: ${
BACKGROUND_ACTIVITY_PROFILE_LABELS[activeBackgroundActivityProfile]
}.`
: BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS[resolvedBackgroundActivity.profile];
const canResetBackgroundActivity = !Equal.equals(
settings.backgroundActivity,
DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
);
return (
<SettingsPageContainer>
@@ -671,6 +1089,88 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title={
<span className="inline-flex items-center gap-1.5">
Background activity
<PolicyTooltip>
This shared policy gates background work such as Git refreshes and provider health
probes after their individual intervals elapse.
</PolicyTooltip>
</span>
}
description={backgroundActivityDescription}
resetAction={
canResetBackgroundActivity ? (
<SettingResetButton
label="background activity"
onClick={() => updateSettings(resetBackgroundActivitySettings())}
/>
) : null
}
control={
<>
<Select
value={backgroundActivityProfileOption}
onValueChange={(value) => {
if (value === "advanced") {
setBackgroundActivityDialogOpen(true);
return;
}
if (
value === "balanced" ||
value === "performance" ||
value === "battery-saver"
) {
updateSettings(backgroundActivityProfileSettings(value));
}
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Background activity profile">
<SelectValue>
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[backgroundActivityProfileOption]}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="balanced">
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
</SelectItem>
<SelectItem hideIndicator value="performance">
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
</SelectItem>
<SelectItem hideIndicator value="battery-saver">
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
</SelectItem>
<SelectItem hideIndicator value="advanced">
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced}
</SelectItem>
</SelectPopup>
</Select>
{backgroundActivityProfileOption === "advanced" ? (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-sm"
variant="outline"
aria-label="Configure advanced background activity"
onClick={() => setBackgroundActivityDialogOpen(true)}
>
<SettingsIcon className="size-4" />
</Button>
}
/>
<TooltipPopup side="top">Configure background activity</TooltipPopup>
</Tooltip>
) : null}
<BackgroundActivityAdvancedDialog
open={backgroundActivityDialogOpen}
onOpenChange={setBackgroundActivityDialogOpen}
/>
</>
}
/>
<SettingsRow
title="Auto-open task panel"
description="Open the right-side plan and task panel automatically when steps appear."
@@ -946,6 +1446,14 @@ export function ProviderSettingsPanel() {
);
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
const textGenInstanceId = textGenerationModelSelection.instanceId;
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const providerHealthPreset = getBackgroundActivityPresetSettings(
getBackgroundActivityBaseProfile(settings.backgroundActivity),
).providerHealthRefreshInterval;
const providerHealthRefreshIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.providerHealthRefreshInterval,
);
const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
const lastCheckedAt =
serverProviders.length > 0
? serverProviders.reduce(
@@ -1230,6 +1738,61 @@ export function ProviderSettingsPanel() {
</div>
}
>
<SettingsRow
title={
<span className="inline-flex items-center gap-1.5">
Health check interval
<PolicyTooltip>
This interval is configured here, then the shared Background activity policy decides
whether provider probes may run when the timer fires. Custom intervals appear as
Advanced in General settings.
</PolicyTooltip>
</span>
}
description="Refresh provider availability, versions, auth state, and model metadata in the background. Set this to 0 seconds to rely on manual refreshes."
resetAction={
providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
<SettingResetButton
label="provider health check interval"
onClick={() =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
providerHealthRefreshInterval: undefined,
}),
)
}
/>
) : null
}
control={
<div className="flex shrink-0 items-center gap-2">
<NumberField
value={providerHealthRefreshIntervalSeconds}
min={0}
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
providerHealthRefreshInterval: Duration.seconds(
normalizeIntervalSeconds(value),
),
}),
)
}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label="Decrease provider health check interval" />
<NumberFieldInput aria-label="Provider health check interval in seconds" />
<NumberFieldIncrement aria-label="Increase provider health check interval" />
</NumberFieldGroup>
</NumberField>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
}
/>
{rows.map((row) => {
const driverOption = getDriverOption(row.driver);
const liveProvider = serverProviders.find(
@@ -1,8 +1,9 @@
import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import { ChevronDownIcon, GitPullRequestIcon, InfoIcon, RefreshCwIcon } from "lucide-react";
import * as Duration from "effect/Duration";
import * as Option from "effect/Option";
import { useState, type ReactNode } from "react";
import type {
BackgroundActivitySettings,
SourceControlProviderKind,
SourceControlDiscoveryResult,
SourceControlProviderAuth,
@@ -10,7 +11,11 @@ import type {
VcsDriverKind,
VcsDiscoveryItem,
} from "@t3tools/contracts";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
import {
getBackgroundActivityBaseProfile,
getBackgroundActivityPresetSettings,
resolveServerBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
@@ -70,6 +75,11 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
type BackgroundActivityOverridePatch = Partial<{
[K in keyof BackgroundActivitySettings["overrides"]]:
| BackgroundActivitySettings["overrides"][K]
| undefined;
}>;
function durationToSeconds(duration: Duration.Duration): number {
return Math.round(Duration.toMillis(duration) / 1_000);
@@ -82,6 +92,27 @@ function normalizeFetchIntervalSeconds(value: number | null): number {
return Math.max(0, Math.round(value));
}
function BackgroundPolicyTooltip({ children }: { readonly children: string }) {
return (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
aria-label="Background policy details"
>
<InfoIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="top" className="max-w-72">
{children}
</TooltipPopup>
</Tooltip>
);
}
function optionLabel(value: Option.Option<string>): string | null {
return Option.getOrNull(value);
}
@@ -292,14 +323,41 @@ function DiscoveryItemRow({
}
function GitFetchIntervalSettings() {
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
const automaticGitFetchIntervalSeconds = durationToSeconds(
resolvedBackgroundActivity.automaticGitFetchInterval,
);
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
getBackgroundActivityPresetSettings(
getBackgroundActivityBaseProfile(settings.backgroundActivity),
).automaticGitFetchInterval,
);
const canResetFetchInterval =
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
const backgroundActivityOverrideSettings = (
current: BackgroundActivitySettings,
overrides: BackgroundActivityOverridePatch,
) => {
const nextOverrides: BackgroundActivityOverridePatch = {
...current.overrides,
...overrides,
};
for (const [key, value] of Object.entries(nextOverrides)) {
if (value === undefined) {
delete nextOverrides[key as keyof typeof nextOverrides];
}
}
return {
backgroundActivity: {
schemaVersion: 1 as const,
profile: "custom" as const,
baseProfile: getBackgroundActivityBaseProfile(current),
overrides: nextOverrides as BackgroundActivitySettings["overrides"],
},
};
};
return (
<div className="grid gap-3">
@@ -307,6 +365,11 @@ function GitFetchIntervalSettings() {
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 items-center gap-1">
<span className="text-xs font-medium text-foreground">Fetch interval</span>
<BackgroundPolicyTooltip>
This interval is configured for Git only. The shared Background activity policy still
decides whether Git refreshes may run when the timer fires. Custom intervals appear as
Advanced in General settings.
</BackgroundPolicyTooltip>
<span
className={cn(
"inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
@@ -318,9 +381,11 @@ function GitFetchIntervalSettings() {
<SettingResetButton
label="fetch interval"
onClick={() =>
updateSettings({
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
})
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
automaticGitFetchInterval: undefined,
}),
)
}
/>
) : null}
@@ -339,9 +404,11 @@ function GitFetchIntervalSettings() {
size="sm"
className="w-32"
onValueChange={(value) =>
updateSettings({
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
})
updateSettings(
backgroundActivityOverrideSettings(settings.backgroundActivity, {
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
}),
)
}
>
<NumberFieldGroup>
-63
View File
@@ -615,69 +615,6 @@ describe("composerDraftStore element contexts", () => {
});
});
describe("composerDraftStore review comments", () => {
const threadId = ThreadId.make("thread-review-comment");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
const comment = {
id: "comment-1",
sectionId: "file:src/app.ts",
sectionTitle: "File comment",
filePath: "src/app.ts",
startIndex: 1,
endIndex: 2,
rangeLabel: "L2 to L3",
text: "Keep this configurable.",
diff: "@@ -2,2 +2,2 @@\n two\n three",
} as const;
beforeEach(() => {
resetComposerDraftStore();
});
it("upserts and removes review comments by id", () => {
const store = useComposerDraftStore.getState();
store.addReviewComment(threadRef, comment);
store.addReviewComment(threadRef, { ...comment, text: "Updated comment." });
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.reviewComments).toEqual([
{ ...comment, text: "Updated comment." },
]);
store.removeReviewComment(threadRef, comment.id);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
});
it("persists review comments and clears them with composer content", () => {
const store = useComposerDraftStore.getState();
store.addReviewComment(threadRef, comment);
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
};
};
const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey?: Record<string, { reviewComments?: Array<Record<string, unknown>> }>;
};
expect(
persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]
?.reviewComments?.[0],
).toMatchObject(comment);
store.clearComposerContent(threadRef);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
});
it("stores review comments against a new-thread draft id", () => {
const draftId = DraftId.make("draft-review-comment");
useComposerDraftStore.getState().addReviewComment(draftId, comment);
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.reviewComments).toEqual([
comment,
]);
});
});
describe("composerDraftStore project draft thread mapping", () => {
const projectId = ProjectId.make("project-a");
const otherProjectId = ProjectId.make("project-b");
+1 -78
View File
@@ -50,13 +50,11 @@ import { useShallow } from "zustand/react/shallow";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
const isRuntimeMode = Schema.is(RuntimeMode);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
const isReviewCommentContext = Schema.is(ReviewCommentContextSchema);
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
const COMPOSER_DRAFT_STORAGE_VERSION = 8;
const COMPOSER_DRAFT_STORAGE_VERSION = 7;
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
@@ -130,7 +128,6 @@ const PersistedComposerThreadDraftState = Schema.Struct({
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
elementContexts: Schema.optionalKey(Schema.Array(PersistedElementContextDraft)),
previewAnnotations: Schema.optionalKey(Schema.Array(PreviewAnnotationPayloadSchema)),
reviewComments: Schema.optionalKey(Schema.Array(ReviewCommentContextSchema)),
// Keyed by `ProviderInstanceId` (open branded slug) so custom provider
// instances (e.g. `codex_personal`) round-trip alongside the built-in
// `codex` / `claudeAgent` / ... entries. Every prior `ProviderDriverKind`
@@ -259,7 +256,6 @@ export interface ComposerThreadDraftState {
*/
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
reviewComments: ReviewCommentContext[];
/**
* Per-instance model selection. Keyed by `ProviderInstanceId` (open
* branded slug) so a default `codex` instance and a user-authored
@@ -468,12 +464,6 @@ interface ComposerDraftStoreState {
annotations: ReadonlyArray<PreviewAnnotationPayload>,
) => void;
removePreviewAnnotation: (threadRef: ComposerThreadTarget, annotationId: string) => void;
addReviewComment: (threadRef: ComposerThreadTarget, comment: ReviewCommentContext) => void;
setReviewComments: (
threadRef: ComposerThreadTarget,
comments: ReadonlyArray<ReviewCommentContext>,
) => void;
removeReviewComment: (threadRef: ComposerThreadTarget, commentId: string) => void;
clearPersistedAttachments: (threadRef: ComposerThreadTarget) => void;
syncPersistedAttachments: (
threadRef: ComposerThreadTarget,
@@ -551,13 +541,11 @@ const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
const EMPTY_ELEMENT_CONTEXTS: ElementContextDraft[] = [];
const EMPTY_PREVIEW_ANNOTATIONS: PreviewAnnotationPayload[] = [];
const EMPTY_REVIEW_COMMENTS: ReviewCommentContext[] = [];
Object.freeze(EMPTY_IMAGES);
Object.freeze(EMPTY_IDS);
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
Object.freeze(EMPTY_ELEMENT_CONTEXTS);
Object.freeze(EMPTY_PREVIEW_ANNOTATIONS);
Object.freeze(EMPTY_REVIEW_COMMENTS);
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderDriverKind, ModelSelection>> =
Object.freeze({});
const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({
@@ -573,7 +561,6 @@ const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
elementContexts: EMPTY_ELEMENT_CONTEXTS,
previewAnnotations: EMPTY_PREVIEW_ANNOTATIONS,
reviewComments: EMPTY_REVIEW_COMMENTS,
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
activeProvider: null,
runtimeMode: null,
@@ -595,7 +582,6 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
terminalContexts: [],
elementContexts: [],
previewAnnotations: [],
reviewComments: [],
modelSelectionByProvider: {},
activeProvider: null,
runtimeMode: null,
@@ -668,7 +654,6 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
draft.previewAnnotations.length === 0 &&
draft.reviewComments.length === 0 &&
Object.keys(draft.modelSelectionByProvider).length === 0 &&
draft.activeProvider === null &&
draft.runtimeMode === null &&
@@ -1639,9 +1624,6 @@ function normalizePersistedDraftsByThreadId(
return normalized ? [normalized] : [];
})
: [];
const reviewComments = Array.isArray(draftCandidate.reviewComments)
? draftCandidate.reviewComments.filter(isReviewCommentContext)
: [];
const runtimeMode = isRuntimeMode(draftCandidate.runtimeMode)
? draftCandidate.runtimeMode
: null;
@@ -1706,7 +1688,6 @@ function normalizePersistedDraftsByThreadId(
attachments.length === 0 &&
terminalContexts.length === 0 &&
elementContexts.length === 0 &&
reviewComments.length === 0 &&
!hasModelData &&
!runtimeMode &&
!interactionMode
@@ -1730,7 +1711,6 @@ function normalizePersistedDraftsByThreadId(
attachments,
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
...(elementContexts.length > 0 ? { elementContexts } : {}),
...(reviewComments.length > 0 ? { reviewComments } : {}),
...(hasModelData
? {
modelSelectionByProvider: compactModelSelectionByProvider(modelSelectionByProvider),
@@ -1815,7 +1795,6 @@ function partializeComposerDraftStoreState(
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
draft.previewAnnotations.length === 0 &&
draft.reviewComments.length === 0 &&
!hasModelData &&
draft.runtimeMode === null &&
draft.interactionMode === null
@@ -1862,11 +1841,6 @@ function partializeComposerDraftStoreState(
),
}
: {}),
...(draft.reviewComments.length > 0
? {
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
}
: {}),
...(hasModelData
? {
modelSelectionByProvider: compactModelSelectionByProvider(
@@ -2109,7 +2083,6 @@ function toHydratedThreadDraft(
})) ?? [],
previewAnnotations:
persistedDraft.previewAnnotations?.map((annotation) => ({ ...annotation })) ?? [],
reviewComments: persistedDraft.reviewComments?.map((comment) => ({ ...comment })) ?? [],
modelSelectionByProvider,
activeProvider,
runtimeMode: persistedDraft.runtimeMode ?? null,
@@ -3175,55 +3148,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
addReviewComment: (threadRef, comment) => {
const threadKey = resolveComposerDraftKey(get(), threadRef);
if (!threadKey || !isReviewCommentContext(comment)) return;
set((state) => {
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
const reviewComments = existing.reviewComments.filter(
(entry) => entry.id !== comment.id,
);
return {
draftsByThreadKey: {
...state.draftsByThreadKey,
[threadKey]: {
...existing,
reviewComments: [...reviewComments, { ...comment }],
},
},
};
});
},
setReviewComments: (threadRef, comments) => {
const threadKey = resolveComposerDraftKey(get(), threadRef);
if (!threadKey) return;
const reviewComments = comments
.filter(isReviewCommentContext)
.map((comment) => ({ ...comment }));
set((state) => {
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
const nextDraft = { ...existing, reviewComments };
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
else nextDraftsByThreadKey[threadKey] = nextDraft;
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
removeReviewComment: (threadRef, commentId) => {
const threadKey = resolveComposerDraftKey(get(), threadRef);
if (!threadKey || !commentId) return;
set((state) => {
const current = state.draftsByThreadKey[threadKey];
if (!current) return state;
const reviewComments = current.reviewComments.filter((entry) => entry.id !== commentId);
if (reviewComments.length === current.reviewComments.length) return state;
const nextDraft = { ...current, reviewComments };
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
else nextDraftsByThreadKey[threadKey] = nextDraft;
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
clearPersistedAttachments: (threadRef) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0) {
@@ -3298,7 +3222,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
terminalContexts: [],
elementContexts: [],
previewAnnotations: [],
reviewComments: [],
};
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextDraft)) {
@@ -173,6 +173,10 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
getProcessDiagnostics: vi.fn(),
getProcessResourceHistory: vi.fn(),
signalProcess: vi.fn(),
reportClientActivity: vi.fn(),
reportHostPowerState: vi.fn(),
getBackgroundPolicy: vi.fn(),
subscribeBackgroundPolicy: vi.fn(() => () => undefined),
},
};
return {
@@ -92,6 +92,7 @@ import {
const decodeIssuedBearerScopes = Schema.decodeUnknownSync(Schema.Array(AuthEnvironmentScope));
import { getClientSettings } from "~/hooks/useSettings";
import { startBackgroundActivityReporter } from "~/lib/backgroundActivityReporter";
import { subscribeTerminalMetadata, terminalSessionManager } from "../../terminalSessionState";
import { subscribePortDiscovery, usePortDiscoveryStore } from "../../portDiscoveryState";
import { resetWsReconnectBackoff } from "~/rpc/wsConnectionState";
@@ -2054,6 +2055,10 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
.catch(() => undefined);
const unsubscribeBrowserResumeReconnects = subscribeBrowserResumeReconnects();
const stopBackgroundActivityReporter = startBackgroundActivityReporter({
getConnections: listEnvironmentConnections,
subscribeConnections: subscribeEnvironmentConnections,
});
activeService = {
queryClient,
@@ -2062,6 +2067,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
stop: () => {
unsubscribeSavedEnvironments();
unsubscribeBrowserResumeReconnects();
stopBackgroundActivityReporter();
queryInvalidationThrottler.cancel();
},
};
@@ -0,0 +1,39 @@
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import { describe, expect, it, vi } from "vite-plus/test";
import { createServerSettingsWriteQueue } from "./serverSettingsWriteQueue";
describe("serverSettingsWriteQueue", () => {
it("serializes server settings writes so later calls cannot be overtaken", async () => {
const applied: Array<number> = [];
const updateSettings = vi
.fn()
.mockImplementationOnce(async () => ({
...DEFAULT_SERVER_SETTINGS,
automaticGitFetchInterval: Duration.seconds(10),
}))
.mockImplementationOnce(async () => ({
...DEFAULT_SERVER_SETTINGS,
automaticGitFetchInterval: Duration.seconds(25),
}));
const queue = createServerSettingsWriteQueue({
updateSettings,
applySettings: (settings) => {
applied.push(Duration.toMillis(settings.automaticGitFetchInterval));
},
onError: vi.fn(),
});
queue.enqueue({ automaticGitFetchInterval: Duration.seconds(10) });
queue.enqueue({ automaticGitFetchInterval: Duration.seconds(25) });
await queue.drain();
expect(updateSettings).toHaveBeenNthCalledWith(1, {
automaticGitFetchInterval: Duration.seconds(10),
});
expect(updateSettings).toHaveBeenNthCalledWith(2, {
automaticGitFetchInterval: Duration.seconds(25),
});
expect(applied).toEqual([10_000, 25_000]);
});
});
@@ -0,0 +1,31 @@
import type { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
export interface ServerSettingsWriteQueue {
readonly enqueue: (patch: ServerSettingsPatch) => void;
readonly reset: () => void;
readonly drain: () => Promise<void>;
}
export function createServerSettingsWriteQueue(input: {
readonly updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
readonly applySettings: (settings: ServerSettings) => void;
readonly onError: (error: unknown) => void;
}): ServerSettingsWriteQueue {
let queue: Promise<void> = Promise.resolve();
return {
enqueue: (patch) => {
queue = queue
.catch(() => undefined)
.then(async () => {
const settings = await input.updateSettings(patch);
input.applySettings(settings);
})
.catch(input.onError);
},
reset: () => {
queue = Promise.resolve();
},
drain: () => queue,
};
}
+14 -2
View File
@@ -22,6 +22,7 @@ import { ensureLocalApi } from "~/localApi";
import * as Struct from "effect/Struct";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
import { createServerSettingsWriteQueue } from "./serverSettingsWriteQueue";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -30,6 +31,13 @@ const clientSettingsHydrationListeners = new Set<() => void>();
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
let clientSettingsHydrated = false;
let clientSettingsHydrationPromise: Promise<void> | null = null;
const serverSettingsWriteQueue = createServerSettingsWriteQueue({
updateSettings: (patch) => ensureLocalApi().server.updateSettings(patch),
applySettings: applySettingsUpdated,
onError: (error) => {
console.error("[SERVER_SETTINGS] update failed", error);
},
});
function emitClientSettingsChange() {
for (const listener of clientSettingsListeners) {
@@ -143,6 +151,10 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
};
}
function enqueueServerSettingsUpdate(serverPatch: ServerSettingsPatch): void {
serverSettingsWriteQueue.enqueue(serverPatch);
}
// ── Hooks ────────────────────────────────────────────────────────────
/**
@@ -201,8 +213,7 @@ export function useUpdateSettings() {
if (currentServerConfig) {
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
enqueueServerSettingsUpdate(serverPatch);
}
if (Object.keys(clientPatch).length > 0) {
@@ -227,6 +238,7 @@ export function __resetClientSettingsPersistenceForTests(): void {
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
clientSettingsHydrated = false;
clientSettingsHydrationPromise = null;
serverSettingsWriteQueue.reset();
clientSettingsListeners.clear();
clientSettingsHydrationListeners.clear();
}
@@ -0,0 +1,160 @@
import type { BackgroundScope, ClientActivityReportInput } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import type { EnvironmentConnection } from "../environments/runtime/connection";
import { randomUUID } from "./utils";
const CLIENT_ID_STORAGE_KEY = "t3.backgroundActivity.clientId";
const REPORT_INTERVAL_MS = 25_000;
const LEASE_TTL_MS = 45_000;
const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
interface RetainedScope {
readonly scope: BackgroundScope;
refCount: number;
}
interface BackgroundActivityReporterOptions {
readonly getConnections: () => ReadonlyArray<EnvironmentConnection>;
readonly subscribeConnections: (listener: () => void) => () => void;
}
const retainedScopes = new Map<string, RetainedScope>();
const retainedScopeListeners = new Set<() => void>();
function notifyRetainedScopesChanged(): void {
for (const listener of retainedScopeListeners) {
listener();
}
}
function stableScopeKey(scope: BackgroundScope): string {
switch (scope.type) {
case "server-config":
case "diagnostics":
return scope.type;
case "provider-status":
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
case "vcs-status":
case "git-refs":
return `${scope.type}:${scope.cwd}`;
case "thread":
return `${scope.type}:${scope.threadId}`;
}
}
function getClientId(): string {
try {
const existing = window.localStorage.getItem(CLIENT_ID_STORAGE_KEY);
if (existing) return existing;
const next = randomUUID();
window.localStorage.setItem(CLIENT_ID_STORAGE_KEY, next);
return next;
} catch {
return "ephemeral-browser-client";
}
}
function resolveClientKind(): ClientActivityReportInput["clientKind"] {
return window.desktopBridge ? "desktop-renderer" : "web";
}
function createActivityReport(): ClientActivityReportInput {
return {
clientId: getClientId(),
clientKind: resolveClientKind(),
visible: document.visibilityState === "visible",
focused: document.hasFocus(),
recentlyInteracted: document.hasFocus(),
appState: document.visibilityState === "visible" ? "active" : "background",
scopes: [...BASELINE_SCOPES, ...[...retainedScopes.values()].map((entry) => entry.scope)],
ttlMs: LEASE_TTL_MS,
observedAt: DateTime.makeUnsafe(new Date().toISOString()),
};
}
async function reportToConnections(
connections: ReadonlyArray<EnvironmentConnection>,
): Promise<void> {
if (connections.length === 0) return;
const report = createActivityReport();
await Promise.allSettled(
connections.map((connection) => connection.client.server.reportClientActivity(report)),
);
}
export function startBackgroundActivityReporter(
options: BackgroundActivityReporterOptions,
): () => void {
if (
typeof window === "undefined" ||
typeof document === "undefined" ||
typeof window.setInterval !== "function"
) {
return () => {};
}
let disposed = false;
let reportTimer: number | null = null;
const report = () => {
if (disposed) return;
void reportToConnections(options.getConnections());
};
const scheduleReport = () => {
if (disposed) return;
if (reportTimer !== null) {
window.clearTimeout(reportTimer);
}
reportTimer = window.setTimeout(() => {
reportTimer = null;
report();
}, 250);
};
const interval = window.setInterval(report, REPORT_INTERVAL_MS);
const unsubscribeConnections = options.subscribeConnections(scheduleReport);
retainedScopeListeners.add(scheduleReport);
document.addEventListener("visibilitychange", scheduleReport);
window.addEventListener("focus", scheduleReport);
window.addEventListener("blur", scheduleReport);
window.addEventListener("online", scheduleReport);
scheduleReport();
return () => {
disposed = true;
if (reportTimer !== null) {
window.clearTimeout(reportTimer);
}
window.clearInterval(interval);
unsubscribeConnections();
retainedScopeListeners.delete(scheduleReport);
document.removeEventListener("visibilitychange", scheduleReport);
window.removeEventListener("focus", scheduleReport);
window.removeEventListener("blur", scheduleReport);
window.removeEventListener("online", scheduleReport);
};
}
export function retainBackgroundScope(scope: BackgroundScope): () => void {
const key = stableScopeKey(scope);
const existing = retainedScopes.get(key);
if (existing) {
existing.refCount += 1;
} else {
retainedScopes.set(key, { scope, refCount: 1 });
notifyRetainedScopesChanged();
}
return () => {
const current = retainedScopes.get(key);
if (!current) return;
current.refCount -= 1;
if (current.refCount <= 0) {
retainedScopes.delete(key);
notifyRetainedScopesChanged();
}
};
}
+11 -2
View File
@@ -18,6 +18,7 @@ import {
subscribeEnvironmentConnections,
} from "../environments/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { retainBackgroundScope } from "./backgroundActivityReporter";
export type { VcsStatusState, VcsStatusTarget };
export { getVcsStatusDataForTarget };
@@ -40,7 +41,15 @@ export function getVcsStatusSnapshot(target: VcsStatusTarget): VcsStatusState {
}
export function watchVcsStatus(target: VcsStatusTarget, client?: VcsStatusClient): () => void {
return manager.watch(target, client);
if (target.cwd === null) {
return manager.watch(target, client);
}
const releaseScope = retainBackgroundScope({ type: "vcs-status", cwd: target.cwd });
const unwatch = manager.watch(target, client);
return () => {
unwatch();
releaseScope();
};
}
export function refreshVcsStatus(target: VcsStatusTarget, client?: VcsStatusClient) {
@@ -54,7 +63,7 @@ export function resetVcsStatusStateForTests(): void {
export function useVcsStatus(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
useEffect(
() => manager.watch({ environmentId: target.environmentId, cwd: target.cwd }),
() => watchVcsStatus({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
-198
View File
@@ -1,15 +1,8 @@
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import { describe, expect, it } from "vite-plus/test";
import {
appendReviewCommentsToPrompt,
buildDiffReviewComment,
buildFileReviewComment,
buildReviewCommentRenderablePatch,
formatReviewCommentContext,
inferReviewCommentFenceLanguage,
parseReviewCommentMessageSegments,
restoreDiffReviewCommentRange,
} from "./reviewCommentContext";
describe("review comment context parsing", () => {
@@ -81,195 +74,4 @@ describe("review comment context parsing", () => {
].join("\n"),
);
});
it("formats editable file comments with the mobile review-comment contract", () => {
const comment = buildFileReviewComment({
id: "comment-1",
filePath: "src/app.ts",
startLine: 2,
endLine: 3,
text: "Keep this configurable.",
contents: ["one", "two", "three", "four"].join("\n"),
});
const prompt = appendReviewCommentsToPrompt("Please update this.", [comment]);
const segments = parseReviewCommentMessageSegments(prompt);
expect(segments).toHaveLength(2);
expect(segments[1]).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({
filePath: "src/app.ts",
startIndex: 1,
endIndex: 2,
rangeLabel: "L2 to L3",
text: "Keep this configurable.",
diff: "two\nthree",
fenceLanguage: "ts",
}),
}),
);
expect(prompt).toContain("```ts\ntwo\nthree\n```");
});
it("formats mixed diff-side selections with the mobile review-comment contract", () => {
const [fileDiff] = parsePatchFiles(
[
"diff --git a/src/app.ts b/src/app.ts",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,4 +1,4 @@",
" one",
"-two",
"+TWO",
" three",
" four",
].join("\n"),
"review-comment-test",
)[0]!.files;
const comment = buildDiffReviewComment({
id: "comment-2",
sectionId: "turn:2",
sectionTitle: "Turn 2",
filePath: "src/app.ts",
fileDiff: fileDiff!,
range: {
start: 2,
side: "deletions",
end: 2,
endSide: "additions",
},
text: "Keep this compatible.",
});
expect(comment).toEqual(
expect.objectContaining({
sectionId: "turn:2",
sectionTitle: "Turn 2",
filePath: "src/app.ts",
startIndex: 1,
endIndex: 2,
rangeLabel: "2",
text: "Keep this compatible.",
diff: "@@ -2,1 +2,1 @@\n-two\n+TWO",
fenceLanguage: "diff",
}),
);
});
it("uses file extensions for source comments and preserves nested markdown fences", () => {
expect(inferReviewCommentFenceLanguage("docs/plan.md")).toBe("md");
expect(inferReviewCommentFenceLanguage("src/view.tsx")).toBe("tsx");
const serialized = formatReviewCommentContext({
id: "comment-3",
sectionId: "file:docs/plan.md",
sectionTitle: "File comment",
filePath: "docs/plan.md",
startIndex: 0,
endIndex: 2,
rangeLabel: "L1 to L3",
text: "Update this example.",
diff: ["# Example", "```ts", "const value = 1;", "```"].join("\n"),
fenceLanguage: "md",
});
const [segment] = parseReviewCommentMessageSegments(serialized);
expect(serialized).toContain("````md");
expect(segment).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({
fenceLanguage: "md",
diff: ["# Example", "```ts", "const value = 1;", "```"].join("\n"),
}),
}),
);
});
it("round-trips greater-than signs in attributes", () => {
const serialized = formatReviewCommentContext({
id: "comment-4",
sectionId: "turn:4",
sectionTitle: "Changes > 5",
filePath: "src/app.ts",
startIndex: 0,
endIndex: 0,
rangeLabel: "+1",
text: "Check this.",
diff: "@@ -0,0 +1,1 @@\n+one",
fenceLanguage: "diff",
});
const [segment] = parseReviewCommentMessageSegments(serialized);
expect(serialized).toContain('sectionTitle="Changes &gt; 5"');
expect(segment).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({ sectionTitle: "Changes > 5" }),
}),
);
});
it("keeps fenced examples in comment text separate from the final context fence", () => {
const text = ["Try this:", "```ts", "const value = 1;", "```", "Then retry."].join("\n");
const serialized = formatReviewCommentContext({
id: "comment-5",
sectionId: "turn:5",
sectionTitle: "Turn 5",
filePath: "src/app.ts",
startIndex: 0,
endIndex: 0,
rangeLabel: "+1",
text,
diff: "@@ -0,0 +1,1 @@\n+one",
fenceLanguage: "diff",
});
const [segment] = parseReviewCommentMessageSegments(serialized);
expect(segment).toEqual(
expect.objectContaining({
kind: "review-comment",
comment: expect.objectContaining({
text,
diff: "@@ -0,0 +1,1 @@\n+one",
fenceLanguage: "diff",
}),
}),
);
});
it("restores Pierre line selections from persisted diff comment row indexes", () => {
const fileDiff = parsePatchFiles(
[
"diff --git a/src/app.ts b/src/app.ts",
"--- a/src/app.ts",
"+++ b/src/app.ts",
"@@ -1,3 +1,3 @@",
" one",
"-two",
"+TWO",
" three",
].join("\n"),
"restore-review-comment-range",
)[0]!.files[0]!;
const comment = buildDiffReviewComment({
id: "comment-6",
sectionId: "turn:6",
sectionTitle: "Turn 6",
filePath: "src/app.ts",
fileDiff,
range: { start: 2, side: "deletions", end: 2, endSide: "additions" },
text: "Keep both sides.",
});
expect(comment).not.toBeNull();
expect(restoreDiffReviewCommentRange(fileDiff, comment!)).toEqual({
start: 2,
side: "deletions",
end: 2,
endSide: "additions",
});
});
});
+11 -316
View File
@@ -1,19 +1,3 @@
import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";
import * as Schema from "effect/Schema";
export const ReviewCommentContextSchema = Schema.Struct({
id: Schema.String,
sectionId: Schema.String,
sectionTitle: Schema.String,
filePath: Schema.String,
startIndex: Schema.Number,
endIndex: Schema.Number,
rangeLabel: Schema.String,
text: Schema.String,
diff: Schema.String,
fenceLanguage: Schema.optional(Schema.String),
});
export interface ReviewCommentContext {
readonly id: string;
readonly sectionId: string;
@@ -24,14 +8,6 @@ export interface ReviewCommentContext {
readonly rangeLabel: string;
readonly text: string;
readonly diff: string;
readonly fenceLanguage?: string | undefined;
}
interface DiffReviewLine {
readonly change: "context" | "add" | "delete";
readonly oldLineNumber: number | null;
readonly newLineNumber: number | null;
readonly content: string;
}
export type ReviewCommentMessageSegment =
@@ -47,20 +23,11 @@ export type ReviewCommentMessageSegment =
const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
function escapeReviewCommentAttribute(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
const REVIEW_COMMENT_DIFF_FENCE_PATTERN = /```diff\s*\n([\s\S]*?)\n```/;
function unescapeReviewCommentAttribute(value: string): string {
return value
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&");
}
@@ -80,19 +47,14 @@ function readNonNegativeInteger(value: string | undefined): number | null {
return Number(value);
}
function extractReviewCommentBody(rawBody: string): {
text: string;
language: string;
contents: string;
} {
const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
const match = matches.at(-1);
const fenceIndex = match?.index;
return {
text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
language: match?.[2]?.trim() || "diff",
contents: match?.[3] ?? "",
};
function extractReviewCommentText(rawBody: string): string {
const fenceIndex = rawBody.indexOf("```diff");
const commentBody = fenceIndex >= 0 ? rawBody.slice(0, fenceIndex) : rawBody;
return commentBody.trim();
}
function extractReviewCommentDiff(rawBody: string): string {
return rawBody.match(REVIEW_COMMENT_DIFF_FENCE_PATTERN)?.[1]?.trim() ?? "";
}
function parseReviewCommentContext(
@@ -108,7 +70,6 @@ function parseReviewCommentContext(
if (!filePath || !sectionId || startIndex === null || endIndex === null) {
return null;
}
const body = extractReviewCommentBody(rawBody);
return {
id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
@@ -118,9 +79,8 @@ function parseReviewCommentContext(
startIndex: Math.min(startIndex, endIndex),
endIndex: Math.max(startIndex, endIndex),
rangeLabel: attributes.rangeLabel?.trim() || "line",
text: body.text,
diff: body.contents,
fenceLanguage: body.language,
text: extractReviewCommentText(rawBody),
diff: extractReviewCommentDiff(rawBody),
};
}
@@ -175,272 +135,7 @@ export function hasReviewCommentMessageSegments(value: string): boolean {
);
}
export function formatReviewCommentFence(language: string, contents: string): string {
const longestBacktickRun = Math.max(
0,
...Array.from(contents.matchAll(/`+/g), (match) => match[0].length),
);
const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
return [`${fence}${language}`, contents.trimEnd(), fence].join("\n");
}
export function formatReviewCommentContext(comment: ReviewCommentContext): string {
return [
[
"<review_comment",
` sectionId="${escapeReviewCommentAttribute(comment.sectionId)}"`,
` sectionTitle="${escapeReviewCommentAttribute(comment.sectionTitle)}"`,
` filePath="${escapeReviewCommentAttribute(comment.filePath)}"`,
` startIndex="${comment.startIndex}"`,
` endIndex="${comment.endIndex}"`,
` rangeLabel="${escapeReviewCommentAttribute(comment.rangeLabel)}"`,
">",
].join(""),
comment.text.trim(),
formatReviewCommentFence(comment.fenceLanguage ?? "diff", comment.diff),
"</review_comment>",
].join("\n");
}
export function appendReviewCommentsToPrompt(
prompt: string,
comments: ReadonlyArray<ReviewCommentContext>,
): string {
const blocks = comments.map(formatReviewCommentContext);
if (blocks.length === 0) return prompt;
const trimmedPrompt = prompt.trim();
return trimmedPrompt.length > 0
? `${trimmedPrompt}\n\n${blocks.join("\n\n")}`
: blocks.join("\n\n");
}
export function buildFileReviewComment(input: {
id: string;
filePath: string;
startLine: number;
endLine: number;
text: string;
contents: string;
}): ReviewCommentContext {
const startLine = Math.max(1, Math.min(input.startLine, input.endLine));
const endLine = Math.max(startLine, Math.max(input.startLine, input.endLine));
const selectedLines = input.contents.split("\n").slice(startLine - 1, endLine);
return {
id: input.id,
sectionId: `file:${input.filePath}`,
sectionTitle: "File comment",
filePath: input.filePath,
startIndex: startLine - 1,
endIndex: endLine - 1,
rangeLabel: startLine === endLine ? `L${startLine}` : `L${startLine} to L${endLine}`,
text: input.text.trim(),
diff: selectedLines.join("\n"),
fenceLanguage: inferReviewCommentFenceLanguage(input.filePath),
};
}
export function inferReviewCommentFenceLanguage(filePath: string): string {
const normalizedPath = filePath.replaceAll("\\", "/");
const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1).toLowerCase();
const extensionIndex = fileName.lastIndexOf(".");
if (extensionIndex > 0 && extensionIndex < fileName.length - 1) {
return fileName.slice(extensionIndex + 1);
}
if (fileName.startsWith(".") && fileName.length > 1) {
return fileName.slice(1);
}
return "text";
}
function stripTrailingNewline(value: string): string {
return value.endsWith("\n") ? value.slice(0, -1) : value;
}
function buildDiffReviewLines(fileDiff: FileDiffMetadata): ReadonlyArray<DiffReviewLine> {
const rows: DiffReviewLine[] = [];
for (const hunk of fileDiff.hunks) {
let oldLineNumber = hunk.deletionStart;
let newLineNumber = hunk.additionStart;
let deletionLineIndex = hunk.deletionLineIndex;
let additionLineIndex = hunk.additionLineIndex;
for (const segment of hunk.hunkContent) {
if (segment.type === "context") {
for (let index = 0; index < segment.lines; index += 1) {
rows.push({
change: "context",
oldLineNumber,
newLineNumber,
content: stripTrailingNewline(
fileDiff.additionLines[additionLineIndex] ??
fileDiff.deletionLines[deletionLineIndex] ??
"",
),
});
oldLineNumber += 1;
newLineNumber += 1;
deletionLineIndex += 1;
additionLineIndex += 1;
}
continue;
}
for (let index = 0; index < segment.deletions; index += 1) {
rows.push({
change: "delete",
oldLineNumber,
newLineNumber: null,
content: stripTrailingNewline(fileDiff.deletionLines[deletionLineIndex] ?? ""),
});
oldLineNumber += 1;
deletionLineIndex += 1;
}
for (let index = 0; index < segment.additions; index += 1) {
rows.push({
change: "add",
oldLineNumber: null,
newLineNumber,
content: stripTrailingNewline(fileDiff.additionLines[additionLineIndex] ?? ""),
});
newLineNumber += 1;
additionLineIndex += 1;
}
}
}
return rows;
}
function getDiffReviewSelectionPoint(
line: DiffReviewLine,
): { lineNumber: number; side: SelectionSide } | null {
if (line.change === "delete" && line.oldLineNumber !== null) {
return { lineNumber: line.oldLineNumber, side: "deletions" };
}
if (line.newLineNumber !== null) {
return { lineNumber: line.newLineNumber, side: "additions" };
}
if (line.oldLineNumber !== null) {
return { lineNumber: line.oldLineNumber, side: "deletions" };
}
return null;
}
export function restoreDiffReviewCommentRange(
fileDiff: FileDiffMetadata,
comment: ReviewCommentContext,
): SelectedLineRange | null {
const lines = buildDiffReviewLines(fileDiff);
const startLine = lines[comment.startIndex];
const endLine = lines[comment.endIndex];
if (!startLine || !endLine) return null;
const start = getDiffReviewSelectionPoint(startLine);
const end = getDiffReviewSelectionPoint(endLine);
if (!start || !end) return null;
return {
start: start.lineNumber,
side: start.side,
end: end.lineNumber,
endSide: end.side,
};
}
function findDiffReviewLineIndex(
lines: ReadonlyArray<DiffReviewLine>,
lineNumber: number,
side: SelectionSide | undefined,
): number {
const preferredKey = side === "deletions" ? "oldLineNumber" : "newLineNumber";
const preferredIndex = lines.findIndex((line) => line[preferredKey] === lineNumber);
if (preferredIndex >= 0) return preferredIndex;
const fallbackKey = preferredKey === "oldLineNumber" ? "newLineNumber" : "oldLineNumber";
return lines.findIndex((line) => line[fallbackKey] === lineNumber);
}
function getDiffRange(
lines: ReadonlyArray<DiffReviewLine>,
key: "oldLineNumber" | "newLineNumber",
): { start: number; count: number } {
const numberedLines = lines.filter((line) => line[key] !== null);
return {
start: numberedLines[0]?.[key] ?? 0,
count: numberedLines.length,
};
}
function getDiffChangeMarker(change: DiffReviewLine["change"]): string {
if (change === "add") return "+";
if (change === "delete") return "-";
return " ";
}
function formatDiffReviewRangeLabel(lines: ReadonlyArray<DiffReviewLine>): string {
const firstLine = lines[0];
const lastLine = lines.at(-1);
if (!firstLine || !lastLine) return "line";
const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
if (firstNumber === null || lastNumber === null) {
return lines.length === 1 ? "line" : `${lines.length} lines`;
}
const firstMarker = getDiffChangeMarker(firstLine.change).trim();
const marker =
firstMarker.length > 0 && lines.every((line) => line.change === firstLine.change)
? firstMarker
: "";
return firstNumber === lastNumber
? `${marker}${firstNumber}`
: `${marker}${firstNumber} to ${marker}${lastNumber}`;
}
export function buildDiffReviewComment(input: {
id: string;
sectionId: string;
sectionTitle: string;
filePath: string;
fileDiff: FileDiffMetadata;
range: SelectedLineRange;
text: string;
}): ReviewCommentContext | null {
const lines = buildDiffReviewLines(input.fileDiff);
const startIndex = findDiffReviewLineIndex(lines, input.range.start, input.range.side);
const endIndex = findDiffReviewLineIndex(
lines,
input.range.end,
input.range.endSide ?? input.range.side,
);
if (startIndex < 0 || endIndex < 0) return null;
const normalizedStartIndex = Math.min(startIndex, endIndex);
const normalizedEndIndex = Math.max(startIndex, endIndex);
const selectedLines = lines.slice(normalizedStartIndex, normalizedEndIndex + 1);
const oldRange = getDiffRange(selectedLines, "oldLineNumber");
const newRange = getDiffRange(selectedLines, "newLineNumber");
return {
id: input.id,
sectionId: input.sectionId,
sectionTitle: input.sectionTitle,
filePath: input.filePath,
startIndex: normalizedStartIndex,
endIndex: normalizedEndIndex,
rangeLabel: formatDiffReviewRangeLabel(selectedLines),
text: input.text.trim(),
diff: [
`@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
...selectedLines.map((line) => `${getDiffChangeMarker(line.change)}${line.content}`),
].join("\n"),
fenceLanguage: "diff",
};
}
export function buildReviewCommentRenderablePatch(comment: ReviewCommentContext): string {
if ((comment.fenceLanguage ?? "diff") !== "diff") {
return "";
}
const diff = comment.diff.trim();
if (diff.length === 0) {
return "";
+2 -128
View File
@@ -73,36 +73,6 @@ describe("rightPanelStore", () => {
});
});
it("upgrades saved file surfaces with neutral reveal state", () => {
expect(
migratePersistedRightPanelState({
byThreadKey: {
"env-1:thread-A": {
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" }],
},
},
}),
).toEqual({
byThreadKey: {
"env-1:thread-A": {
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 0,
},
],
},
},
});
});
it("open sets the active panel for a thread", () => {
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
@@ -138,55 +108,8 @@ describe("rightPanelStore", () => {
isOpen: true,
activeSurfaceId: "file:README.md",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 2,
},
{
id: "file:README.md",
kind: "file",
relativePath: "README.md",
revealLine: null,
revealRequestId: 1,
},
],
});
});
it("updates line reveal requests when reopening a file surface", () => {
useRightPanelStore.getState().openFile(refA, "src/index.ts", 42);
useRightPanelStore.getState().openFile(refA, "src/index.ts", 87);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: 87,
revealRequestId: 2,
},
],
});
useRightPanelStore.getState().openFile(refA, "src/index.ts");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 3,
},
{ id: "file:src/index.ts", kind: "file", relativePath: "src/index.ts" },
{ id: "file:README.md", kind: "file", relativePath: "README.md" },
],
});
});
@@ -381,55 +304,6 @@ describe("rightPanelStore", () => {
});
});
it("closing other surfaces keeps the selected surface active", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeOtherSurfaces(refA, "file:src/index.ts");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 1,
},
],
});
});
it("closing surfaces to the right activates the selected surface when active was removed", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurfacesToRight(refA, "browser:tab-a");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "browser:tab-a",
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
});
});
it("closing all surfaces leaves the panel open and empty", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().closeAllSurfaces(refA);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
});
it("reconciles browser surfaces without deleting other surface kinds", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openBrowser(refA, "tab-a");
+8 -94
View File
@@ -30,17 +30,11 @@ export type RightPanelSurface =
}
| { id: "diff"; kind: "diff" }
| { id: "files"; kind: "files" }
| {
id: `file:${string}`;
kind: "file";
relativePath: string;
revealLine: number | null;
revealRequestId: number;
}
| { id: `file:${string}`; kind: "file"; relativePath: string }
| { id: "plan"; kind: "plan" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
const RIGHT_PANEL_STORAGE_VERSION = 7;
const RIGHT_PANEL_STORAGE_VERSION = 6;
export interface ThreadRightPanelState {
isOpen: boolean;
@@ -52,7 +46,7 @@ interface RightPanelStoreState {
byThreadKey: Record<string, ThreadRightPanelState>;
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
openFile: (ref: ScopedThreadRef, relativePath: string) => void;
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
splitTerminal: (
ref: ScopedThreadRef,
@@ -64,9 +58,6 @@ interface RightPanelStoreState {
closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
closeAllSurfaces: (ref: ScopedThreadRef) => void;
reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
show: (ref: ScopedThreadRef) => void;
@@ -100,16 +91,10 @@ const browserSurface = (tabId: string | null): RightPanelSurface =>
? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
: { id: "browser:new", kind: "preview", resourceId: null };
const fileSurface = (
relativePath: string,
revealLine: number | null,
revealRequestId: number,
): RightPanelSurface => ({
const fileSurface = (relativePath: string): RightPanelSurface => ({
id: `file:${relativePath}`,
kind: "file",
relativePath,
revealLine,
revealRequestId,
});
const terminalSurface = (terminalId: string): RightPanelSurface => ({
@@ -148,11 +133,6 @@ const updateThread = (
return { ...byThreadKey, [threadKey]: next };
};
function normalizeRevealLine(line: number | undefined): number | null {
if (line === undefined || !Number.isFinite(line)) return null;
return Math.max(1, Math.trunc(line));
}
export function migratePersistedRightPanelState(persistedState: unknown): {
byThreadKey: Record<string, ThreadRightPanelState>;
} {
@@ -170,20 +150,6 @@ export function migratePersistedRightPanelState(persistedState: unknown): {
threadState && typeof threadState === "object" ? threadState : null;
const surfaces = Array.isArray(validThreadState?.surfaces)
? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
if (surface.kind === "file") {
const revealLine =
typeof surface.revealLine === "number" &&
Number.isFinite(surface.revealLine)
? Math.max(1, Math.trunc(surface.revealLine))
: null;
const revealRequestId =
typeof surface.revealRequestId === "number" &&
Number.isSafeInteger(surface.revealRequestId) &&
surface.revealRequestId >= 0
? surface.revealRequestId
: 0;
return [{ ...surface, revealLine, revealRequestId }];
}
if (surface.kind !== "terminal") return [surface];
if (
!("resourceId" in surface) ||
@@ -259,31 +225,16 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
}),
})),
openFile: (ref, relativePath, line) =>
openFile: (ref, relativePath) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
const withoutStandaloneExplorer = current.surfaces.filter(
(surface) => surface.kind !== "files",
);
const surfaceId = `file:${relativePath}` as const;
const existing = withoutStandaloneExplorer.find(
(surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
surface.id === surfaceId && surface.kind === "file",
return upsertSurface(
{ ...current, surfaces: withoutStandaloneExplorer },
fileSurface(relativePath),
);
const surface = fileSurface(
relativePath,
normalizeRevealLine(line),
(existing?.revealRequestId ?? 0) + 1,
);
return {
isOpen: true,
activeSurfaceId: surface.id,
surfaces: existing
? withoutStandaloneExplorer.map((entry) =>
entry.id === surface.id ? surface : entry,
)
: [...withoutStandaloneExplorer, surface],
};
}),
})),
openTerminal: (ref, terminalId) =>
@@ -383,43 +334,6 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
return { ...current, surfaces, activeSurfaceId: fallback?.id ?? null };
}),
})),
closeOtherSurfaces: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
const surface = current.surfaces.find((entry) => entry.id === surfaceId);
if (!surface || current.surfaces.length === 1) return current;
return {
...current,
isOpen: true,
surfaces: [surface],
activeSurfaceId: surface.id,
};
}),
})),
closeSurfacesToRight: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
if (index < 0 || index === current.surfaces.length - 1) return current;
const surfaces = current.surfaces.slice(0, index + 1);
const activeStillExists = surfaces.some(
(surface) => surface.id === current.activeSurfaceId,
);
return {
...current,
surfaces,
activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
};
}),
})),
closeAllSurfaces: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
current.surfaces.length === 0
? current
: { ...current, isOpen: true, surfaces: [], activeSurfaceId: null },
),
})),
reconcileBrowserSurfaces: (ref, tabIds) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
@@ -172,6 +172,12 @@ export interface WsRpcClient {
typeof WS_METHODS.serverGetProcessResourceHistory
>;
readonly signalProcess: RpcUnaryMethod<typeof WS_METHODS.serverSignalProcess>;
readonly reportClientActivity: RpcUnaryMethod<typeof WS_METHODS.serverReportClientActivity>;
readonly reportHostPowerState: RpcUnaryMethod<typeof WS_METHODS.serverReportHostPowerState>;
readonly getBackgroundPolicy: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetBackgroundPolicy>;
readonly subscribeBackgroundPolicy: RpcStreamMethod<
typeof WS_METHODS.subscribeBackgroundPolicy
>;
};
readonly cloud: {
readonly getRelayClientStatus: RpcUnaryNoArgMethod<typeof WS_METHODS.cloudGetRelayClientStatus>;
@@ -391,6 +397,18 @@ export function createWsRpcClient(
transport.request((client) => client[WS_METHODS.serverGetProcessResourceHistory](input)),
signalProcess: (input) =>
transport.request((client) => client[WS_METHODS.serverSignalProcess](input)),
reportClientActivity: (input) =>
transport.request((client) => client[WS_METHODS.serverReportClientActivity](input)),
reportHostPowerState: (input) =>
transport.request((client) => client[WS_METHODS.serverReportHostPowerState](input)),
getBackgroundPolicy: () =>
transport.request((client) => client[WS_METHODS.serverGetBackgroundPolicy]({})),
subscribeBackgroundPolicy: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeBackgroundPolicy]({}),
listener,
subscriptionOptions(options, WS_METHODS.subscribeBackgroundPolicy),
),
},
cloud: {
getRelayClientStatus: () =>
+101
View File
@@ -0,0 +1,101 @@
import * as Schema from "effect/Schema";
import { AuthSessionId, EnvironmentId, RpcClientId, ThreadId } from "./baseSchemas.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
export const BackgroundBooleanState = Schema.Literals(["true", "false", "unknown"]);
export type BackgroundBooleanState = typeof BackgroundBooleanState.Type;
export const HostPowerThermalState = Schema.Literals([
"unknown",
"nominal",
"fair",
"serious",
"critical",
]);
export type HostPowerThermalState = typeof HostPowerThermalState.Type;
export const HostPowerSource = Schema.Literals([
"unknown",
"node-macos-shell",
"node-macos-native",
"node-linux",
"node-windows",
"electron-main",
]);
export type HostPowerSource = typeof HostPowerSource.Type;
export const HostPowerSnapshot = Schema.Struct({
source: HostPowerSource,
idle: BackgroundBooleanState,
idleSeconds: Schema.NullOr(Schema.Number),
locked: BackgroundBooleanState,
suspended: Schema.Boolean,
onBattery: BackgroundBooleanState,
lowPowerMode: BackgroundBooleanState,
thermalState: HostPowerThermalState,
stale: Schema.Boolean,
updatedAt: Schema.DateTimeUtc,
});
export type HostPowerSnapshot = typeof HostPowerSnapshot.Type;
export const BackgroundScope = Schema.Union([
Schema.Struct({ type: Schema.Literal("server-config") }),
Schema.Struct({
type: Schema.Literal("provider-status"),
instanceId: Schema.optionalKey(ProviderInstanceId),
}),
Schema.Struct({ type: Schema.Literal("vcs-status"), cwd: Schema.String }),
Schema.Struct({ type: Schema.Literal("git-refs"), cwd: Schema.String }),
Schema.Struct({ type: Schema.Literal("diagnostics") }),
Schema.Struct({ type: Schema.Literal("thread"), threadId: ThreadId }),
]);
export type BackgroundScope = typeof BackgroundScope.Type;
export const ClientKind = Schema.Literals(["web", "desktop-renderer", "mobile", "unknown"]);
export type ClientKind = typeof ClientKind.Type;
export const ClientActivityReportInput = Schema.Struct({
environmentId: Schema.optionalKey(EnvironmentId),
clientId: Schema.String,
clientKind: ClientKind,
visible: Schema.Boolean,
focused: Schema.Boolean,
recentlyInteracted: Schema.Boolean,
appState: Schema.optionalKey(Schema.Literals(["active", "inactive", "background", "unknown"])),
lowPowerMode: Schema.optionalKey(BackgroundBooleanState),
batteryState: Schema.optionalKey(Schema.Literals(["unknown", "unplugged", "charging", "full"])),
networkType: Schema.optionalKey(Schema.String),
scopes: Schema.Array(BackgroundScope),
ttlMs: Schema.optionalKey(Schema.Number),
observedAt: Schema.DateTimeUtc,
});
export type ClientActivityReportInput = typeof ClientActivityReportInput.Type;
export const ClientActivityLease = Schema.Struct({
sessionId: AuthSessionId,
rpcClientId: RpcClientId,
clientId: Schema.String,
clientKind: ClientKind,
visible: Schema.Boolean,
focused: Schema.Boolean,
recentlyInteracted: Schema.Boolean,
appState: Schema.optionalKey(Schema.Literals(["active", "inactive", "background", "unknown"])),
lowPowerMode: Schema.optionalKey(BackgroundBooleanState),
batteryState: Schema.optionalKey(Schema.Literals(["unknown", "unplugged", "charging", "full"])),
networkType: Schema.optionalKey(Schema.String),
scopes: Schema.Array(BackgroundScope),
updatedAt: Schema.DateTimeUtc,
expiresAt: Schema.DateTimeUtc,
});
export type ClientActivityLease = typeof ClientActivityLease.Type;
export const BackgroundPolicySnapshot = Schema.Struct({
hostPower: HostPowerSnapshot,
leases: Schema.Array(ClientActivityLease),
activeForegroundLeaseCount: Schema.Number,
activeScopeKeys: Schema.Array(Schema.String),
shouldRunOpportunisticWork: Schema.Boolean,
updatedAt: Schema.DateTimeUtc,
});
export type BackgroundPolicySnapshot = typeof BackgroundPolicySnapshot.Type;
+2
View File
@@ -43,6 +43,8 @@ export const TurnId = makeEntityId("TurnId");
export type TurnId = typeof TurnId.Type;
export const AuthSessionId = makeEntityId("AuthSessionId");
export type AuthSessionId = typeof AuthSessionId.Type;
export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
export type RpcClientId = typeof RpcClientId.Type;
export const ProviderItemId = makeEntityId("ProviderItemId");
export type ProviderItemId = typeof ProviderItemId.Type;
+1
View File
@@ -1,4 +1,5 @@
export * from "./baseSchemas.ts";
export * from "./background.ts";
export * from "./auth.ts";
export * from "./environment.ts";
export * from "./environmentHttp.ts";
+36
View File
@@ -8,6 +8,11 @@ import {
AuthAccessStreamEvent,
EnvironmentAuthorizationError,
} from "./auth.ts";
import {
BackgroundPolicySnapshot,
ClientActivityReportInput,
HostPowerSnapshot,
} from "./background.ts";
import {
FilesystemBrowseInput,
FilesystemBrowseResult,
@@ -211,6 +216,9 @@ export const WS_METHODS = {
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
serverSignalProcess: "server.signalProcess",
serverReportClientActivity: "server.reportClientActivity",
serverReportHostPowerState: "server.reportHostPowerState",
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
// Cloud environment methods
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
@@ -230,6 +238,7 @@ export const WS_METHODS = {
subscribeServerConfig: "subscribeServerConfig",
subscribeServerLifecycle: "subscribeServerLifecycle",
subscribeAuthAccess: "subscribeAuthAccess",
subscribeBackgroundPolicy: "subscribeBackgroundPolicy",
} as const;
export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {
@@ -328,6 +337,22 @@ export const WsCloudInstallRelayClientRpc = Rpc.make(WS_METHODS.cloudInstallRela
stream: true,
});
export const WsServerReportClientActivityRpc = Rpc.make(WS_METHODS.serverReportClientActivity, {
payload: ClientActivityReportInput,
error: EnvironmentAuthorizationError,
});
export const WsServerReportHostPowerStateRpc = Rpc.make(WS_METHODS.serverReportHostPowerState, {
payload: HostPowerSnapshot,
error: EnvironmentAuthorizationError,
});
export const WsServerGetBackgroundPolicyRpc = Rpc.make(WS_METHODS.serverGetBackgroundPolicy, {
payload: Schema.Struct({}),
success: BackgroundPolicySnapshot,
error: EnvironmentAuthorizationError,
});
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
WS_METHODS.sourceControlLookupRepository,
{
@@ -678,6 +703,13 @@ export const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess,
stream: true,
});
export const WsSubscribeBackgroundPolicyRpc = Rpc.make(WS_METHODS.subscribeBackgroundPolicy, {
payload: Schema.Struct({}),
success: BackgroundPolicySnapshot,
error: EnvironmentAuthorizationError,
stream: true,
});
export const WsRpcGroup = RpcGroup.make(
WsServerGetConfigRpc,
WsServerRefreshProvidersRpc,
@@ -691,6 +723,9 @@ export const WsRpcGroup = RpcGroup.make(
WsServerGetProcessDiagnosticsRpc,
WsServerGetProcessResourceHistoryRpc,
WsServerSignalProcessRpc,
WsServerReportClientActivityRpc,
WsServerReportHostPowerStateRpc,
WsServerGetBackgroundPolicyRpc,
WsCloudGetRelayClientStatusRpc,
WsCloudInstallRelayClientRpc,
WsSourceControlLookupRepositoryRpc,
@@ -740,6 +775,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeServerConfigRpc,
WsSubscribeServerLifecycleRpc,
WsSubscribeAuthAccessRpc,
WsSubscribeBackgroundPolicyRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetFullThreadDiffRpc,
+62 -1
View File
@@ -40,7 +40,7 @@ export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
export const ClientSettingsSchema = Schema.Struct({
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
@@ -362,14 +362,65 @@ export const ObservabilitySettings = Schema.Struct({
export type ObservabilitySettings = typeof ObservabilitySettings.Type;
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
export const BackgroundActivityProfile = Schema.Literals([
"balanced",
"performance",
"battery-saver",
]);
export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
export const BackgroundActivityProfileSelection = Schema.Literals([
"balanced",
"performance",
"battery-saver",
"custom",
]);
export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
export const BackgroundActivityOverrides = Schema.Struct({
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
});
export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
export const BackgroundActivitySettings = Schema.Struct({
schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
profile: BackgroundActivityProfileSelection.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
),
baseProfile: Schema.optionalKey(BackgroundActivityProfile),
overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
backgroundActivity: BackgroundActivitySettings,
// Legacy flat fields retained for old settings files and old clients. New
// consumers should resolve `backgroundActivity` instead.
automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
Schema.withDecodingDefault(
Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
),
),
providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
Schema.withDecodingDefault(
Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
),
),
backgroundActivityProfile: BackgroundActivityProfile.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
@@ -479,7 +530,17 @@ const OpenCodeSettingsPatch = Schema.Struct({
export const ServerSettingsPatch = Schema.Struct({
// Server settings
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey(
Schema.Struct({
schemaVersion: Schema.optionalKey(Schema.Literal(1)),
profile: Schema.optionalKey(BackgroundActivityProfileSelection),
baseProfile: Schema.optionalKey(BackgroundActivityProfile),
overrides: Schema.optionalKey(BackgroundActivityOverrides),
}),
),
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
+4
View File
@@ -75,6 +75,10 @@
"types": "./src/serverSettings.ts",
"import": "./src/serverSettings.ts"
},
"./backgroundActivitySettings": {
"types": "./src/backgroundActivitySettings.ts",
"import": "./src/backgroundActivitySettings.ts"
},
"./String": {
"types": "./src/String.ts",
"import": "./src/String.ts"
@@ -0,0 +1,248 @@
import {
type BackgroundActivityProfile,
type BackgroundActivitySettings,
DEFAULT_BACKGROUND_ACTIVITY_PROFILE,
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
type ServerSettings,
} from "@t3tools/contracts";
import * as Duration from "effect/Duration";
export interface ResolvedBackgroundActivitySettings {
readonly profile: BackgroundActivityProfile;
readonly automaticGitFetchInterval: Duration.Duration;
readonly providerHealthRefreshInterval: Duration.Duration;
readonly hostPowerMonitorActiveInterval: Duration.Duration;
readonly hostPowerMonitorIdleInterval: Duration.Duration;
readonly idleClientTtl: Duration.Duration;
readonly pauseWhenHostLocked: boolean;
readonly pauseWhenHostLowPower: boolean;
readonly pauseWhenClientLowPower: boolean;
readonly pauseWhenOnBattery: boolean;
}
const PRESET_SETTINGS: Record<BackgroundActivityProfile, ResolvedBackgroundActivitySettings> = {
performance: {
profile: "performance",
automaticGitFetchInterval: Duration.seconds(15),
providerHealthRefreshInterval: Duration.minutes(1),
hostPowerMonitorActiveInterval: Duration.seconds(30),
hostPowerMonitorIdleInterval: Duration.minutes(2),
idleClientTtl: Duration.seconds(45),
pauseWhenHostLocked: true,
pauseWhenHostLowPower: false,
pauseWhenClientLowPower: false,
pauseWhenOnBattery: false,
},
balanced: {
profile: "balanced",
automaticGitFetchInterval: DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
providerHealthRefreshInterval: DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
hostPowerMonitorActiveInterval: Duration.seconds(30),
hostPowerMonitorIdleInterval: Duration.minutes(5),
idleClientTtl: Duration.seconds(45),
pauseWhenHostLocked: true,
pauseWhenHostLowPower: true,
pauseWhenClientLowPower: true,
pauseWhenOnBattery: false,
},
"battery-saver": {
profile: "battery-saver",
automaticGitFetchInterval: Duration.seconds(0),
providerHealthRefreshInterval: Duration.minutes(15),
hostPowerMonitorActiveInterval: Duration.minutes(1),
hostPowerMonitorIdleInterval: Duration.minutes(10),
idleClientTtl: Duration.seconds(45),
pauseWhenHostLocked: true,
pauseWhenHostLowPower: true,
pauseWhenClientLowPower: true,
pauseWhenOnBattery: true,
},
};
export function getBackgroundActivityPresetSettings(
profile: BackgroundActivityProfile,
): ResolvedBackgroundActivitySettings {
return PRESET_SETTINGS[profile];
}
export function getBackgroundActivityBaseProfile(
backgroundActivity: BackgroundActivitySettings,
): BackgroundActivityProfile {
if (backgroundActivity.profile === "custom") {
return backgroundActivity.baseProfile ?? DEFAULT_BACKGROUND_ACTIVITY_PROFILE;
}
return backgroundActivity.profile;
}
export function resolveBackgroundActivitySettings(
backgroundActivity: BackgroundActivitySettings,
): ResolvedBackgroundActivitySettings {
const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);
const preset = PRESET_SETTINGS[baseProfile];
const { overrides } = backgroundActivity;
return {
profile: baseProfile,
automaticGitFetchInterval:
overrides.automaticGitFetchInterval ?? preset.automaticGitFetchInterval,
providerHealthRefreshInterval:
overrides.providerHealthRefreshInterval ?? preset.providerHealthRefreshInterval,
hostPowerMonitorActiveInterval:
overrides.hostPowerMonitorActiveInterval ?? preset.hostPowerMonitorActiveInterval,
hostPowerMonitorIdleInterval:
overrides.hostPowerMonitorIdleInterval ?? preset.hostPowerMonitorIdleInterval,
idleClientTtl: overrides.idleClientTtl ?? preset.idleClientTtl,
pauseWhenHostLocked: overrides.pauseWhenHostLocked ?? preset.pauseWhenHostLocked,
pauseWhenHostLowPower: overrides.pauseWhenHostLowPower ?? preset.pauseWhenHostLowPower,
pauseWhenClientLowPower: overrides.pauseWhenClientLowPower ?? preset.pauseWhenClientLowPower,
pauseWhenOnBattery: overrides.pauseWhenOnBattery ?? preset.pauseWhenOnBattery,
};
}
function durationsEqual(a: Duration.Duration, b: Duration.Duration): boolean {
return Duration.toMillis(a) === Duration.toMillis(b);
}
function resolvedSettingsEqual(
a: ResolvedBackgroundActivitySettings,
b: ResolvedBackgroundActivitySettings,
): boolean {
return (
durationsEqual(a.automaticGitFetchInterval, b.automaticGitFetchInterval) &&
durationsEqual(a.providerHealthRefreshInterval, b.providerHealthRefreshInterval) &&
durationsEqual(a.hostPowerMonitorActiveInterval, b.hostPowerMonitorActiveInterval) &&
durationsEqual(a.hostPowerMonitorIdleInterval, b.hostPowerMonitorIdleInterval) &&
durationsEqual(a.idleClientTtl, b.idleClientTtl) &&
a.pauseWhenHostLocked === b.pauseWhenHostLocked &&
a.pauseWhenHostLowPower === b.pauseWhenHostLowPower &&
a.pauseWhenClientLowPower === b.pauseWhenClientLowPower &&
a.pauseWhenOnBattery === b.pauseWhenOnBattery
);
}
export function normalizeBackgroundActivitySettings(
backgroundActivity: BackgroundActivitySettings,
): BackgroundActivitySettings {
if (backgroundActivity.profile !== "custom") {
return {
schemaVersion: 1,
profile: backgroundActivity.profile,
overrides: {},
};
}
const resolved = resolveBackgroundActivitySettings(backgroundActivity);
const profiles: ReadonlyArray<BackgroundActivityProfile> = [
getBackgroundActivityBaseProfile(backgroundActivity),
"balanced",
"performance",
"battery-saver",
];
for (const profile of profiles) {
if (resolvedSettingsEqual(resolved, PRESET_SETTINGS[profile])) {
return {
schemaVersion: 1,
profile,
overrides: {},
};
}
}
const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);
const preset = PRESET_SETTINGS[baseProfile];
const overrides: BackgroundActivitySettings["overrides"] = {
...(!durationsEqual(resolved.automaticGitFetchInterval, preset.automaticGitFetchInterval)
? { automaticGitFetchInterval: resolved.automaticGitFetchInterval }
: {}),
...(!durationsEqual(
resolved.providerHealthRefreshInterval,
preset.providerHealthRefreshInterval,
)
? { providerHealthRefreshInterval: resolved.providerHealthRefreshInterval }
: {}),
...(!durationsEqual(
resolved.hostPowerMonitorActiveInterval,
preset.hostPowerMonitorActiveInterval,
)
? { hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval }
: {}),
...(!durationsEqual(resolved.hostPowerMonitorIdleInterval, preset.hostPowerMonitorIdleInterval)
? { hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval }
: {}),
...(!durationsEqual(resolved.idleClientTtl, preset.idleClientTtl)
? { idleClientTtl: resolved.idleClientTtl }
: {}),
...(resolved.pauseWhenHostLocked !== preset.pauseWhenHostLocked
? { pauseWhenHostLocked: resolved.pauseWhenHostLocked }
: {}),
...(resolved.pauseWhenHostLowPower !== preset.pauseWhenHostLowPower
? { pauseWhenHostLowPower: resolved.pauseWhenHostLowPower }
: {}),
...(resolved.pauseWhenClientLowPower !== preset.pauseWhenClientLowPower
? { pauseWhenClientLowPower: resolved.pauseWhenClientLowPower }
: {}),
...(resolved.pauseWhenOnBattery !== preset.pauseWhenOnBattery
? { pauseWhenOnBattery: resolved.pauseWhenOnBattery }
: {}),
};
return {
schemaVersion: 1,
profile: "custom",
baseProfile,
overrides,
};
}
export function resolveServerBackgroundActivitySettings(
settings: ServerSettings,
): ResolvedBackgroundActivitySettings {
const defaultBackgroundActivity: BackgroundActivitySettings = {
schemaVersion: 1,
profile: DEFAULT_BACKGROUND_ACTIVITY_PROFILE,
overrides: {},
};
const backgroundActivityIsDefault =
settings.backgroundActivity.profile === defaultBackgroundActivity.profile &&
settings.backgroundActivity.baseProfile === undefined &&
Object.keys(settings.backgroundActivity.overrides).length === 0;
const legacyProfile = settings.backgroundActivityProfile;
const hasLegacyOverrides =
legacyProfile !== DEFAULT_BACKGROUND_ACTIVITY_PROFILE ||
Duration.toMillis(settings.automaticGitFetchInterval) !==
Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) ||
Duration.toMillis(settings.providerHealthRefreshInterval) !==
Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL);
if (backgroundActivityIsDefault && hasLegacyOverrides) {
return resolveBackgroundActivitySettings({
schemaVersion: 1,
profile:
Duration.toMillis(settings.automaticGitFetchInterval) ===
Duration.toMillis(
getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,
) &&
Duration.toMillis(settings.providerHealthRefreshInterval) ===
Duration.toMillis(
getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,
)
? legacyProfile
: "custom",
baseProfile: legacyProfile,
overrides: {
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
Duration.toMillis(
getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,
)
? { automaticGitFetchInterval: settings.automaticGitFetchInterval }
: {}),
...(Duration.toMillis(settings.providerHealthRefreshInterval) !==
Duration.toMillis(
getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,
)
? { providerHealthRefreshInterval: settings.providerHealthRefreshInterval }
: {}),
},
});
}
return resolveBackgroundActivitySettings(settings.backgroundActivity);
}
@@ -3,7 +3,9 @@ import {
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import { describe, expect, it } from "vite-plus/test";
import { resolveServerBackgroundActivitySettings } from "./backgroundActivitySettings.ts";
import { createModelSelection } from "./model.ts";
import {
applyServerSettingsPatch,
@@ -194,4 +196,80 @@ describe("serverSettings helpers", () => {
config: { homePath: "~/.codex" },
});
});
it("stores background activity profiles as a versioned object and syncs legacy aliases", () => {
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
backgroundActivity: {
schemaVersion: 1,
profile: "battery-saver",
overrides: {},
},
});
expect(next.backgroundActivity).toEqual({
schemaVersion: 1,
profile: "battery-saver",
overrides: {},
});
expect(next.backgroundActivityProfile).toBe("battery-saver");
expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(0);
expect(Duration.toMillis(next.providerHealthRefreshInterval)).toBe(
Duration.toMillis(Duration.minutes(15)),
);
});
it("turns legacy interval patches into custom background activity overrides", () => {
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
automaticGitFetchInterval: Duration.seconds(15),
});
expect(next.backgroundActivity).toEqual({
schemaVersion: 1,
profile: "custom",
baseProfile: "balanced",
overrides: {
automaticGitFetchInterval: Duration.seconds(15),
},
});
expect(resolveServerBackgroundActivitySettings(next).profile).toBe("balanced");
expect(
Duration.toMillis(resolveServerBackgroundActivitySettings(next).automaticGitFetchInterval),
).toBe(15_000);
});
it("reconciles custom background activity back to a preset when overrides match the preset", () => {
const custom = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
automaticGitFetchInterval: Duration.seconds(15),
});
const next = applyServerSettingsPatch(custom, {
automaticGitFetchInterval: Duration.seconds(30),
});
expect(next.backgroundActivity).toEqual({
schemaVersion: 1,
profile: "balanced",
overrides: {},
});
expect(next.backgroundActivityProfile).toBe("balanced");
expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(30_000);
});
it("drops custom overrides that duplicate the base profile", () => {
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
backgroundActivity: {
schemaVersion: 1,
profile: "custom",
baseProfile: "balanced",
overrides: {
automaticGitFetchInterval: Duration.seconds(30),
},
},
});
expect(next.backgroundActivity).toEqual({
schemaVersion: 1,
profile: "balanced",
overrides: {},
});
});
});
+54 -2
View File
@@ -4,6 +4,11 @@ import * as Schema from "effect/Schema";
import { deepMerge } from "./Struct.ts";
import { fromLenientJson } from "./schemaJson.ts";
import { createModelSelection } from "./model.ts";
import {
getBackgroundActivityBaseProfile,
normalizeBackgroundActivitySettings,
resolveBackgroundActivitySettings,
} from "./backgroundActivitySettings.ts";
const ServerSettingsJson = fromLenientJson(ServerSettings);
const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
@@ -76,14 +81,61 @@ export function applyServerSettingsPatch(
patch: ServerSettingsPatch,
): ServerSettings {
const selectionPatch = patch.textGenerationModelSelection;
const { automaticGitFetchInterval, ...patchForMerge } = patch;
const {
automaticGitFetchInterval,
providerHealthRefreshInterval,
backgroundActivityProfile,
backgroundActivity,
...patchForMerge
} = patch;
const backgroundActivityPatch =
backgroundActivityProfile !== undefined
? {
schemaVersion: 1 as const,
profile: backgroundActivityProfile,
overrides: {},
}
: automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
? {
schemaVersion: 1 as const,
profile: "custom" as const,
baseProfile: getBackgroundActivityBaseProfile(current.backgroundActivity),
overrides: {
...current.backgroundActivity.overrides,
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
...(providerHealthRefreshInterval !== undefined
? { providerHealthRefreshInterval }
: {}),
},
}
: undefined;
const next = deepMerge(current, patchForMerge);
const nextWithReplacements = {
const nextWithReplacementsBase = {
...next,
...(backgroundActivity !== undefined
? { backgroundActivity: deepMerge(current.backgroundActivity, backgroundActivity) }
: {}),
...(backgroundActivityPatch !== undefined
? { backgroundActivity: backgroundActivityPatch }
: {}),
...(patch.providerInstances !== undefined
? { providerInstances: patch.providerInstances }
: {}),
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
};
const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
nextWithReplacementsBase.backgroundActivity,
);
const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
normalizedBackgroundActivity,
);
const nextWithReplacements = {
...nextWithReplacementsBase,
backgroundActivity: normalizedBackgroundActivity,
automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
backgroundActivityProfile: resolvedBackgroundActivity.profile,
};
if (!selectionPatch) {
return nextWithReplacements;
+23
View File
@@ -0,0 +1,23 @@
diff --git a/package.json b/package.json
index b18c94f3f7b40bdb15084ab7cabcb19dd29c61f7..ab96ac589d368e806ef45480283d6e0fa199117f 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,18 @@
"./worker/worker-portable.js": {
"types": "./dist/worker/worker-portable.d.ts",
"import": "./dist/worker/worker-portable.js"
+ },
+ "./types": {
+ "types": "./dist/types.d.ts",
+ "import": "./dist/types.js"
+ },
+ "./utils/getFiletypeFromFileName": {
+ "types": "./dist/utils/getFiletypeFromFileName.d.ts",
+ "import": "./dist/utils/getFiletypeFromFileName.js"
+ },
+ "./utils/parsePatchFiles": {
+ "types": "./dist/utils/parsePatchFiles.d.ts",
+ "import": "./dist/utils/parsePatchFiles.js"
}
},
"publishConfig": {
-69
View File
@@ -1,69 +0,0 @@
diff --git a/dist/editor/editor.js b/dist/editor/editor.js
index e8013fc6eb6f243a6c912facf3fc0319ac66a8d0..80c82df4cdeb828bd331f5ec2f443d216bedc304 100644
--- a/dist/editor/editor.js
+++ b/dist/editor/editor.js
@@ -77,15 +77,12 @@ var Editor = class {
this.#options = options;
}
edit(component) {
- const { useTokenTransformer, enableGutterUtility, enableLineSelection, expandUnchanged, diffStyle, lineHoverHighlight,...rest } = component.options;
+ const { useTokenTransformer, expandUnchanged, diffStyle,...rest } = component.options;
const isDiff = component.type === "file-diff";
- if (useTokenTransformer !== true || enableGutterUtility === true || enableLineSelection === true || lineHoverHighlight !== "disabled" || expandUnchanged !== true && isDiff || diffStyle === "unified" && isDiff) {
+ if (useTokenTransformer !== true || expandUnchanged !== true && isDiff || diffStyle === "unified" && isDiff) {
component.setOptions({
...rest,
useTokenTransformer: true,
- enableGutterUtility: false,
- enableLineSelection: false,
- lineHoverHighlight: "disabled",
expandUnchanged: true,
diffStyle: "split"
});
@@ -511,6 +508,7 @@ var Editor = class {
return lineNumber - 1;
};
this.#editorEventDisposes.push(addEventListener(gutterEl, "pointerdown", (e) => {
+ if (this.#fileInstance?.options.enableLineSelection === true) return;
const textDocument = this.#textDocument;
const lineIndex = resolveEditableLine(resolveGutterTarget(e.composedPath()[0]));
if (lineIndex === void 0 || textDocument === void 0) return;
diff --git a/dist/react/utils/useFileInstance.js b/dist/react/utils/useFileInstance.js
index cb8e2026fb5d7a19f489c0a2402efbcb7dff3322..510fad6364d4a2214c7dd65fe2b114f1cce0c815 100644
--- a/dist/react/utils/useFileInstance.js
+++ b/dist/react/utils/useFileInstance.js
@@ -92,10 +92,7 @@ function mergeFileOptions({ options, controlledSelection, contentEditable, hasCu
};
if (needsEditorOptions) merged = {
...merged,
- useTokenTransformer: true,
- enableGutterUtility: false,
- enableLineSelection: false,
- lineHoverHighlight: "disabled"
+ useTokenTransformer: true
};
return merged;
}
diff --git a/package.json b/package.json
index d1558633de87044b7aa96cff09443db11f163cec..c0b16f0a0bec6fba2026f24f38b2c0a8fa06af7c 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,18 @@
"./worker/worker-portable.js": {
"types": "./dist/worker/worker-portable.d.ts",
"import": "./dist/worker/worker-portable.js"
+ },
+ "./types": {
+ "types": "./dist/types.d.ts",
+ "import": "./dist/types.js"
+ },
+ "./utils/getFiletypeFromFileName": {
+ "types": "./dist/utils/getFiletypeFromFileName.d.ts",
+ "import": "./dist/utils/getFiletypeFromFileName.js"
+ },
+ "./utils/parsePatchFiles": {
+ "types": "./dist/utils/parsePatchFiles.d.ts",
+ "import": "./dist/utils/parsePatchFiles.js"
}
},
"publishConfig": {
-31
View File
@@ -1,34 +1,3 @@
diff --git a/dist/unstable/ai/McpServer.js b/dist/unstable/ai/McpServer.js
index 4819ff0..f5e0f60 100644
--- a/dist/unstable/ai/McpServer.js
+++ b/dist/unstable/ai/McpServer.js
@@ -235,6 +235,26 @@ export const run = /*#__PURE__*/Effect.fnUntraced(function* (options) {
const server = yield* McpServer;
const isHttp = Option.isSome(yield* Effect.serviceOption(HttpRouter.HttpRouter));
const clientSessions = new Map();
+ if (isHttp && options.path !== undefined) {
+ const router = yield* HttpRouter.HttpRouter;
+ yield* router.add("DELETE", options.path, Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const sessionId = request.headers[mcpSessionIdHeader];
+ if (sessionId === undefined) {
+ return HttpServerResponse.empty({
+ status: 400
+ });
+ }
+ if (!clientSessions.delete(sessionId)) {
+ return HttpServerResponse.empty({
+ status: 404
+ });
+ }
+ return HttpServerResponse.empty({
+ status: 204
+ });
+ }));
+ }
const handlers = yield* Layer.build(layerHandlers(options, {
clientSessions
}));
diff --git a/dist/unstable/rpc/RpcClient.d.ts b/dist/unstable/rpc/RpcClient.d.ts
index b0f61df..ead663e 100644
--- a/dist/unstable/rpc/RpcClient.d.ts
+209 -229
View File
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -17,7 +17,7 @@ catalog:
"@effect/vitest": 4.0.0-beta.78
"@noble/curves": 1.9.1
"@noble/hashes": 1.8.0
"@pierre/diffs": 1.3.0-beta.5
"@pierre/diffs": 1.3.0-beta.4
"@types/node": 24.12.4
"@typescript/native-preview": 7.0.0-dev.20260604.1
"@vitest/runner": 4.1.8
@@ -56,7 +56,6 @@ overrides:
"@effect/vitest>@vitest/runner": "-"
"@effect/vitest>vitest": "-"
"@expo/metro-config": 56.0.13
"@pierre/diffs>@shikijs/transformers": ^4.2.0
"@types/node": "catalog:"
effect: "catalog:"
vite: "catalog:"
@@ -78,7 +77,7 @@ patchedDependencies:
"@effect/[email protected]": patches/@[email protected]
"@expo/[email protected]": patches/@expo%[email protected]
"@ff-labs/[email protected]": patches/@[email protected]
"@pierre/[email protected].5": patches/@pierre%[email protected].5.patch
"@pierre/[email protected].4": patches/@pierre%[email protected].4.patch
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]