Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23d7a3d1c8 | ||
|
|
ab23a82b1d | ||
|
|
069f271b1c | ||
|
|
e17a333d3f | ||
|
|
5dfc78e85e |
No files matched your search
@@ -0,0 +1,510 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>T3 Code — Sidebar v2 Beta Plan</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #000;
|
||||
--fg: #fff;
|
||||
--muted: #9ca3af;
|
||||
--dim: #6b7280;
|
||||
--surface: #0d0d0f;
|
||||
--surface2: #16161a;
|
||||
--border: #26262c;
|
||||
--amber: #f59e0b;
|
||||
--sky: #38bdf8;
|
||||
--indigo: #818cf8;
|
||||
--violet: #a78bfa;
|
||||
--emerald: #34d399;
|
||||
--red: #f87171;
|
||||
--teal: #2dd4bf;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 15px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.wrap { max-width: 960px; margin: 0 auto; padding: 56px 24px 120px; }
|
||||
h1 { font-size: 32px; line-height: 1.2; letter-spacing: -0.02em; }
|
||||
h2 { font-size: 21px; letter-spacing: -0.01em; margin: 72px 0 8px; }
|
||||
h2 .num { color: var(--dim); font-weight: 500; margin-right: 10px; }
|
||||
h3 { font-size: 15px; margin: 28px 0 8px; }
|
||||
p { color: var(--muted); margin: 10px 0; max-width: 72ch; }
|
||||
p strong, li strong { color: var(--fg); font-weight: 600; }
|
||||
a { color: var(--sky); text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
code {
|
||||
font-family: var(--mono); font-size: 12.5px;
|
||||
background: var(--surface2); border: 1px solid var(--border);
|
||||
padding: 1px 5px; border-radius: 4px; color: #d4d4d8;
|
||||
}
|
||||
pre {
|
||||
font-family: var(--mono); font-size: 12.5px; line-height: 1.7;
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 10px; padding: 16px 18px; overflow-x: auto;
|
||||
color: #d4d4d8; margin: 14px 0;
|
||||
}
|
||||
pre .c { color: var(--dim); }
|
||||
pre .k { color: var(--violet); }
|
||||
pre .s { color: var(--emerald); }
|
||||
ul, ol { margin: 10px 0 10px 22px; color: var(--muted); max-width: 72ch; }
|
||||
li { margin: 6px 0; }
|
||||
li::marker { color: var(--dim); }
|
||||
.lede { font-size: 17px; color: var(--muted); margin-top: 14px; }
|
||||
.meta { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 20px; }
|
||||
.chip {
|
||||
font-size: 12px; padding: 3px 10px; border-radius: 999px;
|
||||
border: 1px solid var(--border); color: var(--muted); background: var(--surface);
|
||||
}
|
||||
.chip.hot { border-color: rgba(52,211,153,.4); color: var(--emerald); }
|
||||
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 18px 0; }
|
||||
@media (max-width: 760px) { .cols { grid-template-columns: 1fr; } }
|
||||
.panel {
|
||||
background: var(--surface); border: 1px solid var(--border);
|
||||
border-radius: 12px; padding: 18px 20px;
|
||||
}
|
||||
.panel h4 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--dim); margin-bottom: 10px; }
|
||||
.panel ul { margin-left: 18px; font-size: 13.5px; }
|
||||
.kv { font-size: 13.5px; color: var(--muted); }
|
||||
.kv b { color: var(--fg); font-weight: 600; }
|
||||
.note {
|
||||
border-left: 3px solid var(--violet); background: rgba(167,139,250,.06);
|
||||
padding: 12px 16px; border-radius: 0 10px 10px 0; margin: 18px 0; color: var(--muted);
|
||||
font-size: 14px; max-width: 78ch;
|
||||
}
|
||||
.warn { border-left-color: var(--amber); background: rgba(245,158,11,.06); }
|
||||
|
||||
/* ————— sidebar mock ————— */
|
||||
.mockwrap { display: grid; grid-template-columns: 320px 1fr; gap: 28px; margin: 24px 0; align-items: start; }
|
||||
@media (max-width: 820px) { .mockwrap { grid-template-columns: 1fr; } }
|
||||
.sidebar {
|
||||
background: #0a0a0c; border: 1px solid var(--border); border-radius: 14px;
|
||||
overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,.6);
|
||||
font-size: 12px;
|
||||
}
|
||||
.sb-top {
|
||||
display: flex; gap: 8px; padding: 10px; border-bottom: 1px solid var(--border);
|
||||
align-items: center;
|
||||
}
|
||||
.sb-search {
|
||||
flex: 1; display: flex; align-items: center; gap: 6px;
|
||||
background: var(--surface2); border: 1px solid var(--border); border-radius: 7px;
|
||||
padding: 5px 9px; color: var(--dim); font-size: 11.5px;
|
||||
}
|
||||
.sb-search kbd {
|
||||
margin-left: auto; font-family: var(--mono); font-size: 10px;
|
||||
border: 1px solid var(--border); border-radius: 4px; padding: 0 4px; color: var(--dim);
|
||||
}
|
||||
.sb-new {
|
||||
width: 26px; height: 26px; border-radius: 7px; border: 1px solid var(--border);
|
||||
background: var(--surface2); color: var(--muted); display: grid; place-items: center;
|
||||
font-size: 15px; cursor: default;
|
||||
}
|
||||
.rows { padding: 6px; display: flex; flex-direction: column; gap: 3px; }
|
||||
|
||||
.row {
|
||||
position: relative; border-radius: 8px; cursor: default;
|
||||
transition: background .12s;
|
||||
overflow: hidden;
|
||||
}
|
||||
.row:hover { background: rgba(255,255,255,.045); }
|
||||
.row .rail {
|
||||
position: absolute; left: 0; top: 6px; bottom: 6px; width: 3px; border-radius: 2px;
|
||||
}
|
||||
.rail.amber { background: var(--amber); }
|
||||
.rail.sky { background: var(--sky); animation: pulse 1.6s ease-in-out infinite; }
|
||||
.rail.red { background: var(--red); }
|
||||
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
|
||||
|
||||
.card { padding: 8px 10px 8px 14px; }
|
||||
.card .l1 { display: flex; align-items: center; gap: 8px; }
|
||||
.card .title { color: #d4d4d8; font-weight: 500; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row.unread .card .title { color: var(--fg); font-weight: 650; }
|
||||
.fav {
|
||||
width: 15px; height: 15px; border-radius: 4px; flex: none;
|
||||
display: grid; place-items: center; font-size: 8px; font-weight: 700; letter-spacing: .02em;
|
||||
}
|
||||
.fav.t3 { background: rgba(167,139,250,.14); color: var(--violet); border: 1px solid rgba(167,139,250,.3); }
|
||||
.fav.fh { background: rgba(56,189,248,.12); color: #7dd3fc; border: 1px solid rgba(56,189,248,.3); }
|
||||
.slim .fav { width: 13px; height: 13px; font-size: 7px; }
|
||||
.card .diff { font-family: var(--mono); font-size: 10px; white-space: nowrap; }
|
||||
.diff .add { color: var(--emerald); } .diff .del { color: var(--red); }
|
||||
.card .time { margin-left: auto; color: var(--dim); font-size: 10px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.card .time.wait { color: var(--amber); }
|
||||
.card .meta {
|
||||
margin-top: 3px; display: flex; align-items: center; gap: 8px;
|
||||
color: var(--dim); font-size: 10px; padding-left: 23px;
|
||||
white-space: nowrap; overflow: hidden;
|
||||
}
|
||||
.meta .st { font-weight: 650; font-size: 9.5px; letter-spacing: .02em; }
|
||||
.st.amber { color: var(--amber); } .st.sky { color: var(--sky); } .st.red { color: var(--red); }
|
||||
.branch { font-family: var(--mono); font-size: 9.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.model { font-family: var(--mono); font-size: 9.5px; display: inline-flex; align-items: center; gap: 3px; }
|
||||
.hx.cl { color: rgba(217,119,87,.75); font-size: 9px; }
|
||||
.hx.cx { color: rgba(255,255,255,.45); font-size: 9px; }
|
||||
.mach { font-size: 9.5px; color: var(--dim); display: inline-flex; align-items: center; gap: 3px; }
|
||||
|
||||
.slim { display: flex; align-items: center; gap: 7px; padding: 5px 10px; height: 27px; }
|
||||
.slim .dot { width: 5px; height: 5px; border-radius: 50%; background: var(--dim); flex: none; }
|
||||
.slim .title { color: var(--muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.slim .pr { font-family: var(--mono); font-size: 9.5px; color: var(--violet); white-space: nowrap; }
|
||||
.slim .pr.open { color: var(--emerald); }
|
||||
.slim .time { margin-left: auto; color: var(--dim); font-size: 10px; flex: none; }
|
||||
|
||||
.settle-btn {
|
||||
position: absolute; right: 8px; top: 8px; opacity: 0;
|
||||
border: 1px solid var(--border); background: var(--surface2); color: var(--muted);
|
||||
border-radius: 6px; font-size: 10px; padding: 2px 8px; cursor: pointer;
|
||||
transition: opacity .12s; font-family: inherit;
|
||||
}
|
||||
.row:hover .settle-btn { opacity: 1; }
|
||||
.settle-btn:hover { color: var(--fg); border-color: var(--dim); }
|
||||
.row.settling { transition: opacity .35s, max-height .35s ease; max-height: 0 !important; opacity: 0; }
|
||||
|
||||
.mock-legend h4 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--dim); margin: 18px 0 8px; }
|
||||
.mock-legend .kv { display: block; margin: 7px 0; }
|
||||
.lg-dot { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 8px; vertical-align: baseline; }
|
||||
.toast {
|
||||
margin: 10px 6px 8px; border: 1px solid rgba(45,212,191,.35); background: rgba(45,212,191,.07);
|
||||
border-radius: 8px; padding: 8px 10px; font-size: 11px; color: var(--muted);
|
||||
display: none; align-items: center; gap: 8px;
|
||||
}
|
||||
.toast.show { display: flex; }
|
||||
.toast b { color: var(--teal); font-weight: 600; }
|
||||
.toast button {
|
||||
margin-left: auto; border: 1px solid rgba(45,212,191,.4); background: transparent;
|
||||
color: var(--teal); border-radius: 5px; font-size: 10px; padding: 2px 8px; cursor: pointer;
|
||||
}
|
||||
.reset { font-size: 12px; color: var(--dim); cursor: pointer; background: none; border: none; font-family: inherit; }
|
||||
.reset:hover { color: var(--muted); }
|
||||
|
||||
table { border-collapse: collapse; width: 100%; margin: 14px 0; font-size: 13.5px; }
|
||||
th { text-align: left; color: var(--dim); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; padding: 8px 12px; border-bottom: 1px solid var(--border); }
|
||||
td { padding: 9px 12px; border-bottom: 1px solid var(--border); color: var(--muted); vertical-align: top; }
|
||||
td:first-child { color: var(--fg); white-space: nowrap; }
|
||||
.phase { border: 1px solid var(--border); border-radius: 12px; margin: 16px 0; overflow: hidden; }
|
||||
.phase-h {
|
||||
display: flex; align-items: baseline; gap: 12px; padding: 14px 20px;
|
||||
background: var(--surface); border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.phase-h .n {
|
||||
font-family: var(--mono); font-size: 12px; color: var(--bg); background: var(--fg);
|
||||
border-radius: 6px; padding: 1px 8px; font-weight: 700;
|
||||
}
|
||||
.phase-h .t { font-weight: 600; font-size: 15px; }
|
||||
.phase-h .d { margin-left: auto; font-size: 12px; color: var(--dim); }
|
||||
.phase-b { padding: 6px 20px 16px; }
|
||||
.phase-b ul { font-size: 13.5px; }
|
||||
svg text { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
|
||||
svg .mono { font-family: var(--mono); }
|
||||
.foot { margin-top: 80px; padding-top: 20px; border-top: 1px solid var(--border); color: var(--dim); font-size: 12.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
|
||||
<h1>Sidebar v2 — beta plan</h1>
|
||||
<p class="lede">One flat, recency-sorted thread list where row size is earned by state — and “settled” becomes a real lifecycle stage users control. Familiar mechanics only: nothing here requires learning a new gesture.</p>
|
||||
<div class="meta">
|
||||
<span class="chip hot">beta · toggle in settings</span>
|
||||
<span class="chip">plan: <code style="border:none;background:none;padding:0">.plans/21-sidebar-v2-beta.md</code></span>
|
||||
<span class="chip"><a href="https://hsyscdqldmk5.postplan.dev/" target="_blank" rel="noopener noreferrer">original 5 concepts ↗</a></span>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">01</span>What we're building</h2>
|
||||
<p>The hybrid the concepts page predicted, filtered through “meet users where they are”: <strong>concept 4's adaptive density</strong> as the skeleton, <strong>concept 1's card layout</strong> (trimmed to two structured lines — no generated text) for active rows, and <strong>concept 3 reduced to a sort rule</strong> (approval-blocked threads pin above the recency flow — no tiers, no inline approve).</p>
|
||||
<div class="cols">
|
||||
<div class="panel">
|
||||
<h4>Changes</h4>
|
||||
<ul>
|
||||
<li><strong>Flat recency list</strong> — project group headers gone; project becomes a chip. This is how Claude Code, Codex, and Cursor already present sessions.</li>
|
||||
<li><strong>Settled lifecycle state</strong> — explicit, user- or rule-triggered. Settled rows collapse to slim one-liners (≈ today's density).</li>
|
||||
<li><strong>Four states, three colors</strong> — Needs approval (amber, pinned with wait time), Working (sky, pulsing), <strong>Ready</strong> (no color, no label — the normal resting state; bold title until visited), Failed (red).</li>
|
||||
<li><strong>Structured metadata only</strong> — the card's second line is status word · branch · harness + model · machine. No summaries or free text to generate; every field is data the shell already carries.</li>
|
||||
<li><strong>Project identity = favicon</strong> — the existing <code>ProjectFavicon</code> per-row, not a text chip. Harness (Claude Code / Codex / other) is a tinted glyph on the model; machine shows only when the thread lives on another computer.</li>
|
||||
<li><strong>Failed sessions visible</strong> — <code>session.lastError</code> finally gets a red state; today a dead session shows nothing.</li>
|
||||
<li><strong>Settle → worktree cleanup</strong> — settling an orphaned-worktree thread offers a one-click remove.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h4>Deliberately not</h4>
|
||||
<ul>
|
||||
<li>Inline approve/reject in the sidebar — needs a safety story first.</li>
|
||||
<li>Message snippets (concept 2) — streaming churn unsolved.</li>
|
||||
<li>Ops-grid density mode (concept 5).</li>
|
||||
<li>Auto-archive of long-settled threads (future: settled ≥ 30d).</li>
|
||||
<li>Removing v1 — it stays the default; v2 is opt-in.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">02</span>The mock</h2>
|
||||
<p><strong>Hover any card and hit “Settle”</strong> — it collapses into the slim tail. That height change is the whole design: it happens only at lifecycle transitions, never from streaming updates, which is what keeps the list calm.</p>
|
||||
|
||||
<div class="mockwrap">
|
||||
<div class="sidebar" id="mock">
|
||||
<div class="sb-top">
|
||||
<div class="sb-search">⌕ Search <kbd>⌘K</kbd></div>
|
||||
<div class="sb-new">+</div>
|
||||
</div>
|
||||
<div class="toast" id="toast"><span>Settled · worktree <b>fix-pr-titles</b> is orphaned</span><button id="toast-remove">Remove</button></div>
|
||||
<div class="rows" id="rows">
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="rail amber"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Normalize open PR titles</span><span class="time wait">waiting 2m</span></div>
|
||||
<div class="meta"><span class="st amber">APPROVAL</span><span class="branch">fix-pr-titles</span><span class="model"><span class="hx cl">✳</span>opus-4.8</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle data-toast>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row" data-card style="max-height:64px">
|
||||
<div class="rail sky"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Sidebar v2 UX Redesign</span><span class="time">14m 22s</span></div>
|
||||
<div class="meta"><span class="st sky">WORKING</span><span class="branch">sidebar-v2-beta</span><span class="model"><span class="hx cl">✳</span>fable-5</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav fh">FH</span><span class="title">Fix image upload stalls</span><span class="time">18m</span></div>
|
||||
<div class="meta"><span class="branch">main</span><span class="model"><span class="hx cl">✳</span>sonnet-5</span><span class="mach">⏻ mac-studio</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Review default experience plan</span><span class="time">9m</span></div>
|
||||
<div class="meta"><span class="branch">plan-ux-review</span><span class="model"><span class="hx cl">✳</span>opus-4.8</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">Disable pairing codes by default</span><span class="diff"><span class="add">+214</span> <span class="del">−38</span></span><span class="time">12m</span></div>
|
||||
<div class="meta"><span class="branch">disable-pairing-codes</span><span class="model"><span class="hx cx">◈</span>gpt-5.6-sol</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row unread" data-card style="max-height:64px">
|
||||
<div class="rail red"></div>
|
||||
<div class="card">
|
||||
<div class="l1"><span class="fav t3">T3</span><span class="title">iOS Simulator Remote Setup</span><span class="time">34m</span></div>
|
||||
<div class="meta"><span class="st red">FAILED</span><span class="branch">main</span><span class="model"><span class="hx cx">◈</span>gpt-5.6-sol</span><span class="mach">⏻ mbp-16</span></div>
|
||||
</div>
|
||||
<button class="settle-btn" data-settle>✓ Settle</button>
|
||||
</div>
|
||||
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Default new worktrees from origin main</span><span class="time">41m</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Fix performance bottlenecks</span><span class="pr">#3825 merged</span><span class="time">1d</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav t3">T3</span><span class="title">Stress test long thread rendering</span><span class="pr open">#3822 open</span><span class="time">2d</span></div></div>
|
||||
<div class="row"><div class="slim"><span class="fav fh">FH</span><span class="title">CLI File Hosting Options</span><span class="time">2d</span></div></div>
|
||||
</div>
|
||||
<div style="padding:4px 10px 10px; text-align:right"><button class="reset" id="reset-mock">↺ reset mock</button></div>
|
||||
</div>
|
||||
|
||||
<div class="mock-legend">
|
||||
<h4>Card anatomy (active threads, ~52px)</h4>
|
||||
<span class="kv"><b>Line 1</b> — project favicon · title (bold = unread) · diff stats when present · time</span>
|
||||
<span class="kv"><b>Line 2</b> — structured metadata only: status word (only when colored) · branch · harness glyph + model · machine (only when not this one). No generated text — everything on the card is data we already have.</span>
|
||||
<h4>Four states, three colors</h4>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--amber)"></span><b>APPROVAL</b> — blocked mid-run, pinned to top with “waiting Xm”</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--sky)"></span><b>WORKING</b> — pulsing rail, live elapsed timer</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--fg)"></span><b>Ready</b> — the default; needs no label. Stopped, waiting on you. Bold title until visited.</span>
|
||||
<span class="kv"><span class="lg-dot" style="background:var(--red)"></span><b>FAILED</b> — session error, invisible today</span>
|
||||
<h4>Harness · model · machine</h4>
|
||||
<span class="kv"><b>✳</b> Claude Code · <b>◈</b> Codex · a neutral glyph for “other” — one tinted glyph before the model name, deliberately quiet.</span>
|
||||
<span class="kv"><b>⏻ machine</b> appears only on threads running somewhere other than the current computer; local threads show nothing.</span>
|
||||
<h4>Slim row (settled, ~28px)</h4>
|
||||
<span class="kv">favicon · title · PR when notable · time. Visually ≈ today's v1 row, so density for history is preserved.</span>
|
||||
<h4>Sort</h4>
|
||||
<span class="kv">Approval first (by wait time) → then pure recency. No sections, no headers, no “show more” — the tail just scrolls, virtualized.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">03</span>The settled model</h2>
|
||||
<p>Concept 4 derived “settled” passively. This version makes it an <strong>acknowledgment with an act attached</strong> — Gmail's archive, GitHub notifications' “Done” — which is what makes row heights stable and the list trustworthy.</p>
|
||||
|
||||
<svg viewBox="0 0 900 210" style="width:100%; max-width:900px; margin:18px 0" role="img" aria-label="Settled state machine">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M0 0 L10 5 L0 10 z" fill="#6b7280"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect x="30" y="65" width="180" height="80" rx="14" fill="rgba(56,189,248,.08)" stroke="#38bdf8" stroke-width="1.5"/>
|
||||
<text x="120" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Active</text>
|
||||
<text x="120" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">rich card · in rollups</text>
|
||||
<rect x="370" y="65" width="180" height="80" rx="14" fill="rgba(107,114,128,.1)" stroke="#6b7280" stroke-width="1.5"/>
|
||||
<text x="460" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Settled</text>
|
||||
<text x="460" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">slim row · out of rollups</text>
|
||||
<rect x="700" y="65" width="170" height="80" rx="14" fill="rgba(248,113,113,.06)" stroke="#3f3f46" stroke-width="1.5" stroke-dasharray="5 4"/>
|
||||
<text x="785" y="100" text-anchor="middle" fill="#fff" font-size="17" font-weight="600">Archived</text>
|
||||
<text x="785" y="122" text-anchor="middle" fill="#9ca3af" font-size="11">existing flow, unchanged</text>
|
||||
<path d="M212 85 C 270 60, 310 60, 368 85" fill="none" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr)"/>
|
||||
<text x="290" y="52" text-anchor="middle" fill="#9ca3af" font-size="11.5">user settles · PR merged/closed · inactive ≥ 3d</text>
|
||||
<path d="M368 128 C 310 153, 270 153, 212 128" fill="none" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr)"/>
|
||||
<text x="290" y="172" text-anchor="middle" fill="#9ca3af" font-size="11.5">any real activity · user un-settles</text>
|
||||
<path d="M552 105 L 698 105" fill="none" stroke="#4b5563" stroke-width="1.5" stroke-dasharray="5 4" marker-end="url(#arr)"/>
|
||||
<text x="625" y="94" text-anchor="middle" fill="#6b7280" font-size="11.5">manual (future: 30d auto)</text>
|
||||
</svg>
|
||||
|
||||
<p><strong>Storage is one override, everything else is computed.</strong> No background jobs, no sweeper:</p>
|
||||
<pre><span class="k">effectiveSettled</span>(thread) =
|
||||
override === <span class="s">"settled"</span> → <span class="k">true</span> <span class="c">// manual settle</span>
|
||||
override === <span class="s">"active"</span> → <span class="k">false</span> <span class="c">// manual keep-active (beats auto rules)</span>
|
||||
pr.state ∈ {<span class="s">merged</span>, <span class="s">closed</span>} → <span class="k">true</span> <span class="c">// auto — strongest signal</span>
|
||||
lastActivityAt < now − inactivityThreshold → <span class="k">true</span> <span class="c">// auto — backstop, default 3d, configurable</span>
|
||||
otherwise → <span class="k">false</span></pre>
|
||||
<ul>
|
||||
<li>Stored: <code>settledOverride: "settled" | "active" | null</code> + <code>settledAt</code>, server-side next to <code>archivedAt</code> — it must sync across desktop/remote, and worktree cleanup needs the server to know. Mirrors the <code>thread.archived</code> event pattern exactly.</li>
|
||||
<li><strong>Activity clears the override</strong> (new user message, session start, approval request) — a settled thread that wakes up expands and floats back up. Settled is never a hole a thread disappears into.</li>
|
||||
<li><strong>Viewing ≠ settling.</strong> Visiting clears unread (existing <code>lastVisitedAt</code>); settling asserts “this work is concluded.” Conflating them would make auto-unsettle fight the user.</li>
|
||||
</ul>
|
||||
<div class="note warn"><strong>Inbox-zero hedge:</strong> manual settling must feel like optional satisfaction, not homework. The auto rules guarantee a user who never touches the affordance still gets a tidy list. Beta telemetry decides how prominent the affordance stays.</div>
|
||||
|
||||
<h2><span class="num">04</span>Swap boundary</h2>
|
||||
<p><strong>Whole-component swap, one seam.</strong> Today's <code>Sidebar.tsx</code> (~3,750 lines) takes zero props and mounts at exactly one place. Everything that must behave identically in both sidebars already lives <em>outside</em> the component in shared hooks and stores — and what lives inside (project grouping, drag-and-drop, show-more) is precisely what v2 deletes.</p>
|
||||
|
||||
<svg viewBox="0 0 900 330" style="width:100%; max-width:900px; margin:18px 0" role="img" aria-label="Component swap architecture">
|
||||
<defs>
|
||||
<marker id="arr2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M0 0 L10 5 L0 10 z" fill="#6b7280"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect x="280" y="14" width="340" height="52" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="450" y="36" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">AppSidebarLayout.tsx:93</text>
|
||||
<text x="450" y="54" text-anchor="middle" fill="#9ca3af" font-size="11" class="mono">{sidebarV2Enabled ? <ThreadSidebarV2/> : <ThreadSidebar/>}</text>
|
||||
<path d="M380 66 L 235 108" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<path d="M520 66 L 665 108" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<rect x="70" y="112" width="330" height="78" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="235" y="136" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">Sidebar.tsx (v1 — untouched, default)</text>
|
||||
<text x="235" y="156" text-anchor="middle" fill="#9ca3af" font-size="11">project groups · dnd · show-more · collapse</text>
|
||||
<text x="235" y="174" text-anchor="middle" fill="#6b7280" font-size="11">ignores new settled fields entirely</text>
|
||||
<rect x="500" y="112" width="330" height="78" rx="10" fill="rgba(52,211,153,.05)" stroke="#34d399"/>
|
||||
<text x="665" y="136" text-anchor="middle" fill="#fff" font-size="13" font-weight="600" class="mono">SidebarV2.tsx (new, beta)</text>
|
||||
<text x="665" y="156" text-anchor="middle" fill="#9ca3af" font-size="11">flat virtualized list · card/slim rows · settle</text>
|
||||
<text x="665" y="174" text-anchor="middle" fill="#6b7280" font-size="11">no imports from Sidebar.tsx, ever</text>
|
||||
<path d="M235 190 L 235 232" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<path d="M665 190 L 665 232" stroke="#6b7280" stroke-width="1.5" marker-end="url(#arr2)"/>
|
||||
<rect x="70" y="236" width="760" height="72" rx="10" fill="#0d0d0f" stroke="#26262c"/>
|
||||
<text x="450" y="260" text-anchor="middle" fill="#fff" font-size="13" font-weight="600">Shared — both components call the same modules</text>
|
||||
<text x="450" y="282" text-anchor="middle" fill="#9ca3af" font-size="11" class="mono">Sidebar.logic.ts · ThreadStatusIndicators · useThreadActions · threadSelectionStore · uiStateStore · threadSort.ts · keybindings</text>
|
||||
<text x="450" y="300" text-anchor="middle" fill="#6b7280" font-size="11">anything both need moves here first — never cross-imported</text>
|
||||
</svg>
|
||||
|
||||
<ul>
|
||||
<li>The settled <strong>data model ships dark and is flag-independent</strong> — v1 simply ignores the new fields. The toggle is a pure view swap: flipping it never migrates data, so switching back and forth is always safe.</li>
|
||||
<li>Toggle lives in a new <strong>“Beta features”</strong> settings panel: <code>sidebarV2Enabled</code> (default false) + <code>sidebarAutoSettleAfterDays</code> (default 3, nullable = never) in <code>ClientSettingsSchema</code>.</li>
|
||||
<li>Inherited for free via shared hooks: click-to-open, multi-select, context menu, inline rename, thread-jump ⌘1–9, archive, PR link, port/terminal/remote indicators.</li>
|
||||
</ul>
|
||||
|
||||
<h2><span class="num">05</span>Phases</h2>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P1</span><span class="t">Settled data model</span><span class="d">ships dark · no UI change</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li><code>contracts/settings.ts</code> — add <code>sidebarV2Enabled</code>, <code>sidebarAutoSettleAfterDays</code>.</li>
|
||||
<li><code>contracts/orchestration.ts</code> — <code>settledOverride</code> + <code>settledAt</code> on the thread (decoding defaults → old data decodes unchanged); <code>thread.settled</code> / <code>thread.unsettled</code> events; <code>thread.settle</code> / <code>thread.unsettle</code> commands.</li>
|
||||
<li><code>server/orchestration/decider.ts</code> — handle both commands (settle is idempotent for bulk); activity paths (user message, session start, approval request) emit <code>thread.unsettled</code> when an override is set.</li>
|
||||
<li><code>client-runtime/threadReducer.ts</code> — reduce both events (archive cases at :87–101 are the template).</li>
|
||||
<li>Pure <code>effectiveSettled(shell, {now, autoSettleAfterDays})</code> in client-runtime; unit-test the full truth table (override × PR state × inactivity).</li>
|
||||
</ul>
|
||||
<p class="kv"><b>Verify:</b> typecheck · reducer + predicate tests · zero visible change.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P2</span><span class="t">SidebarV2 component + beta toggle</span><span class="d">the visible feature</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>“Beta features” settings panel + route; swap seam in <code>AppSidebarLayout.tsx</code>.</li>
|
||||
<li><code>SidebarV2.tsx</code>: flat virtualized list, sort = needs-approval (by wait) → recency; single <code>SidebarV2Row</code> with <code>card</code> / <code>slim</code> variants from the same shell data. Rows lead with the existing <code>ProjectFavicon</code> component (environmentId + cwd are already on the shell).</li>
|
||||
<li>Consolidate status derivation in <code>Sidebar.logic.ts</code> to four visual states: <strong>Needs approval</strong>, <strong>Working</strong> (incl. connecting), <strong>Ready</strong> (merges today's Awaiting Input / Plan Ready / Completed-unseen — same user action, so one unlabeled state), and new <strong>Failed</strong> (<code>session.lastError</code>, non-running) — kept shared so v1 can adopt Failed later.</li>
|
||||
<li>Meta line: harness glyph + model from the shell's provider/model selection; machine label from the thread's environment vs. the current one (render only when they differ). Both are display-only lookups, no new data plumbing.</li>
|
||||
<li>Unread = bold-until-visited from existing <code>uiStateStore.threadLastVisitedAtById</code>.</li>
|
||||
<li>Height changes <strong>only</strong> on settle/unsettle transitions (auto-animate); streaming never resizes rows.</li>
|
||||
<li><code>useThreadActions</code>: <code>settleThread</code> / <code>unsettleThread</code> mirroring <code>archiveThread</code>, minus navigation — settling never navigates away. Affordances: row hover button, context menu, bulk multi-select. No keyboard shortcut yet.</li>
|
||||
</ul>
|
||||
<p class="kv"><b>Verify:</b> toggle on → v2; toggle off → v1 pixel-identical to before · settle round-trips across a desktop+remote pair · killed session → Failed card.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P3</span><span class="t">Worktree cleanup hook</span><span class="d">settle = reclaim disk</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>On <strong>manual settle</strong> where the worktree is orphaned (<code>getOrphanedWorktreePathForThread</code>): non-blocking “Worktree kept · Remove?” prompt → <code>vcsEnvironment.removeWorktree</code>. Never automatic, never blocks the settle.</li>
|
||||
<li>Skip the prompt when the worktree has uncommitted changes or unpushed commits (from vcs status the sidebar already has).</li>
|
||||
<li>Auto-settle never touches worktrees. Follow-up (tracked, out of scope): settings “Storage” view listing orphaned worktrees of settled threads with sizes + bulk remove.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="phase">
|
||||
<div class="phase-h"><span class="n">P4</span><span class="t">Telemetry & beta exit</span><span class="d">find the balance</span></div>
|
||||
<div class="phase-b">
|
||||
<ul>
|
||||
<li>Count settles by source: manual / auto-PR / auto-inactivity / bulk. Count un-settles: manual vs. activity-driven.</li>
|
||||
<li><strong>Activity-driven un-settles of manual settles</strong> = the model fighting users → retune threshold or triggers.</li>
|
||||
<li>Manual settling ≈ 0% → shrink the affordance, lean on auto rules. High → a habit worth building on (keyboard shortcut, etc.).</li>
|
||||
<li>Track toggle-off rate after trying v2.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><span class="num">06</span>Open questions</h2>
|
||||
<table>
|
||||
<tr><th>Question</th><th>Current thinking</th></tr>
|
||||
<tr><td>Server-side activity observation</td><td>If decider activity paths are too scattered for unsettle-on-activity, fall back to client-side: compute with activity timestamps, override only stores manual state (activity newer than <code>settledAt</code> wins). Decide in P1.</td></tr>
|
||||
<tr><td>Shell projection</td><td><code>settledOverride</code>/<code>settledAt</code> <strong>must</strong> be in the thread shell stream — the sidebar never loads details. Verify first thing in P1.</td></tr>
|
||||
<tr><td>Diff stats on cards</td><td>Requires checkpoint data in the shell; if absent, defer diff stats rather than loading details per row.</td></tr>
|
||||
<tr><td>Project grouping in v2</td><td>Not planned; v1 stays available for users who want groups. Revisit only if beta feedback demands it.</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="foot">T3 Code · Sidebar v2 beta · plan doc pair: <code>.plans/21-sidebar-v2-beta.md</code> (implementation detail) + this page (design + rationale). Mock data mirrors the original concepts page (from live state.sqlite, Jul 13).</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function settle(btn, showToast) {
|
||||
const row = btn.closest('.row');
|
||||
if (!row) return;
|
||||
row.classList.add('settling');
|
||||
setTimeout(() => {
|
||||
row.classList.remove('settling');
|
||||
row.removeAttribute('data-card');
|
||||
row.style.maxHeight = '';
|
||||
const title = row.querySelector('.title').textContent;
|
||||
const time = row.querySelector('.time').textContent.replace('waiting ', '');
|
||||
const fav = row.querySelector('.fav').outerHTML;
|
||||
row.classList.remove('unread');
|
||||
row.innerHTML = '<div class="slim">' + fav + '<span class="title">' + title +
|
||||
'</span><span class="time">' + time + '</span></div>';
|
||||
const rows = document.getElementById('rows');
|
||||
const firstSlim = Array.from(rows.children).find(r => !r.hasAttribute('data-card'));
|
||||
rows.insertBefore(row, firstSlim ?? null);
|
||||
row.style.opacity = '0';
|
||||
requestAnimationFrame(() => { row.style.transition = 'opacity .3s'; row.style.opacity = '1'; });
|
||||
if (showToast) document.getElementById('toast').classList.add('show');
|
||||
}, 360);
|
||||
}
|
||||
function hideToast() { document.getElementById('toast').classList.remove('show'); }
|
||||
document.querySelectorAll('[data-settle]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => settle(btn, btn.hasAttribute('data-toast')));
|
||||
});
|
||||
document.getElementById('toast-remove').addEventListener('click', hideToast);
|
||||
document.getElementById('reset-mock').addEventListener('click', () => location.reload());
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,285 @@
|
||||
# Sidebar v2 (beta): flat adaptive-density list with settled threads
|
||||
|
||||
Status: planned
|
||||
Mocks: https://hsyscdqldmk5.postplan.dev/ (concept 4 base + concept 1 card layout + concept 3 needs-you pinning)
|
||||
|
||||
## Summary
|
||||
|
||||
A new thread sidebar behind a client-settings beta toggle. Core changes vs. the
|
||||
current sidebar:
|
||||
|
||||
- **Flat recency list.** Project group headers are gone; project identity moves
|
||||
onto the row as the existing `ProjectFavicon` (environmentId + cwd). This
|
||||
matches the session lists users know from Claude Code, Codex, and Cursor.
|
||||
- **Adaptive density via a "settled" lifecycle state.** Active threads render
|
||||
as two-line cards: favicon + title + time, then a structured meta line
|
||||
(status word · branch · harness glyph + model · machine). Settled threads
|
||||
collapse to slim one-liners, roughly today's row height. No generated or
|
||||
free-text summaries anywhere — every field on a card is data the shell
|
||||
already carries.
|
||||
- **Settled is an explicit state**, not a derived one: users settle threads
|
||||
manually, or threads auto-settle (PR merged/closed, inactivity). Any real
|
||||
activity auto-unsettles. Settled is a lifecycle stage between active and
|
||||
archived — it stays in the list, just quiet.
|
||||
- **Four visual states, three colors.** Needs approval (amber, pinned above
|
||||
the recency flow with "waiting Xm"), Working (sky, pulsing, elapsed timer),
|
||||
**Ready** (uncolored and unlabeled — the normal resting state: the agent
|
||||
stopped and is waiting on you, whether it finished, asked a question, or
|
||||
proposed a plan; bold title until visited is the only signal), Failed (red,
|
||||
`session.lastError` — a dead session shows nothing today). Today's Awaiting
|
||||
Input / Plan Ready / Completed-unseen pills all collapse into Ready: they
|
||||
differ in detail, not in what the user should do (look at the thread).
|
||||
Color is reserved for "act now" (amber), "in motion" (sky), "broken" (red).
|
||||
- **Harness / model / machine as quiet metadata.** A tinted glyph before the
|
||||
model name distinguishes Claude Code / Codex / other; a machine label
|
||||
renders only when the thread lives on a different computer than the one
|
||||
you're looking at. Display-only lookups from shell data, no new plumbing.
|
||||
- **Settled feeds cleanup.** Settling a thread offers/permits worktree cleanup;
|
||||
long-settled threads are candidates for future auto-archive.
|
||||
|
||||
The v2 component is a sibling of the current sidebar, swapped at a single mount
|
||||
point. The current sidebar is untouched except for the swap seam.
|
||||
|
||||
## Rationale
|
||||
|
||||
Full design discussion lives in the session that produced the mocks; the short
|
||||
version:
|
||||
|
||||
- We aren't in a position to teach users a new interaction model. Every v2
|
||||
mechanic maps to an existing habit: flat recency list (Claude Code / Codex /
|
||||
Cursor), settle (Gmail archive / GitHub notifications "Done"), unread-bold
|
||||
(email). Zero new gestures.
|
||||
- "Settled" makes the adaptive-density row-height rule *stable*: height changes
|
||||
only at real lifecycle transitions, never from ambient re-rendering. This
|
||||
kills concept 4's "jumpy list" risk.
|
||||
- Viewing a thread does **not** settle it. Visiting clears unseen (existing
|
||||
`lastVisitedAt` mechanics); settling asserts "this work is concluded." If
|
||||
viewing settled, auto-unsettle would fight the user and the state would stop
|
||||
meaning anything.
|
||||
- Settling is optional by design. The auto rules are the hedge against
|
||||
inbox-zero fatigue: a user who never touches the affordance still gets a
|
||||
naturally tidy list. Beta telemetry question: what fraction of settles are
|
||||
manual vs. auto?
|
||||
|
||||
## The settled model
|
||||
|
||||
```
|
||||
Active ──(user settles | PR merged/closed | inactivity ≥ threshold)──▶ Settled
|
||||
Settled ──(new user message | session starts | approval requested |
|
||||
PR reopened | user un-settles)──▶ Active
|
||||
Settled ──(existing archive flow, or future auto-archive)──▶ Archived
|
||||
```
|
||||
|
||||
Settled is a **computed property with one stored override**:
|
||||
|
||||
```
|
||||
effectiveSettled(thread) =
|
||||
override === "settled" → true (manual settle)
|
||||
override === "active" → false (manual keep-active)
|
||||
pr.state ∈ {merged, closed} → true (auto)
|
||||
lastActivityAt < now − inactivityThreshold → true (auto)
|
||||
otherwise → false
|
||||
```
|
||||
|
||||
- The stored field is a tri-state: `settledOverride: "settled" | "active" | null`
|
||||
plus `settledAt: IsoDateTime | null` (set when override becomes "settled",
|
||||
used for display and future auto-archive aging).
|
||||
- The auto cases need no background job and no events — they fall out of data
|
||||
the sidebar already streams (`vcs.status` change request state,
|
||||
`latestUserMessageAt` / turn timestamps). Auto-unsettle for the time-based
|
||||
case is free: activity moves the timestamp, the predicate flips.
|
||||
- **Activity clears the override.** Any thread activity event (new user
|
||||
message, session start, approval request) resets `settledOverride` to null
|
||||
server-side, so a manually settled thread that wakes up becomes active again
|
||||
and later auto-rules apply fresh. Likewise, manually un-settling a merged-PR
|
||||
thread sets `settledOverride: "active"`, which beats the PR auto-rule.
|
||||
- Inactivity threshold: default 3 days, client setting, `null` = never
|
||||
auto-settle by time.
|
||||
|
||||
Server-side storage (next to `archivedAt` on the thread) rather than
|
||||
client-local: settled must sync across desktop/remote environments, and the
|
||||
worktree-cleanup hook needs the server to know. This mirrors the
|
||||
`archivedAt` / `thread.archived` / `thread.unarchived` pattern exactly.
|
||||
|
||||
Consequences of being settled:
|
||||
|
||||
- Row collapses to the slim one-liner.
|
||||
- Excluded from status rollups (any badge counts, aggregate status dots).
|
||||
- Eligible for worktree cleanup prompting (see below).
|
||||
- Future: settled ≥ 30 days → auto-archive candidate (not in this phase).
|
||||
|
||||
## Swap strategy: component swap at the mount point
|
||||
|
||||
Decision: **swap the whole sidebar component**, not internals.
|
||||
|
||||
The current `Sidebar.tsx` (~3750 lines) takes no props — it reads everything
|
||||
from hooks/atoms/stores — and `AppSidebarLayout.tsx:93` is its single mount
|
||||
point. The truly shared behavior (thread-jump keybindings, selection store,
|
||||
uiStateStore, `useThreadActions`, context-menu via `readLocalApi()`) already
|
||||
lives *outside* the component in hooks and stores, so a sibling component
|
||||
inherits all of it by calling the same hooks. What lives inside Sidebar.tsx
|
||||
(project grouping, drag-and-drop, show-more, per-project collapse) is exactly
|
||||
the stuff v2 deletes — threading a variant flag through it would mean touching
|
||||
hundreds of conditional branches for no benefit.
|
||||
|
||||
```tsx
|
||||
// AppSidebarLayout.tsx — the entire seam
|
||||
const sidebarV2 = useClientSettings((s) => s.sidebarV2Enabled);
|
||||
...
|
||||
{sidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
```
|
||||
|
||||
Rules for the seam:
|
||||
|
||||
- `SidebarV2.tsx` imports freely from `Sidebar.logic.ts`,
|
||||
`ThreadStatusIndicators.tsx`, `useThreadActions`, `threadSelectionStore`,
|
||||
`uiStateStore` — shared logic stays shared.
|
||||
- `SidebarV2.tsx` must not import from `Sidebar.tsx`, and vice versa. Anything
|
||||
both need moves into `Sidebar.logic.ts` (or a new shared module) first.
|
||||
- The settled *data model* (contracts, server, reducer) is flag-independent —
|
||||
it ships dark and is simply unused by the v1 component. Only the *UI* is
|
||||
gated. This keeps the toggle a pure view swap: flipping it never migrates
|
||||
data, so switching back and forth is always safe.
|
||||
- v1 remains the default. Deleting v1 is a separate future decision once beta
|
||||
feedback lands.
|
||||
|
||||
## Implementation phases
|
||||
|
||||
### Phase 1 — Settled data model (ships dark, no UI)
|
||||
|
||||
Mirror the archived pattern end-to-end:
|
||||
|
||||
1. `packages/contracts/src/settings.ts`: add to `ClientSettingsSchema`:
|
||||
- `sidebarV2Enabled: boolean` (default false)
|
||||
- `sidebarAutoSettleAfterDays: number | null` (default 3)
|
||||
2. `packages/contracts/src/orchestration.ts`:
|
||||
- Thread shell: `settledOverride: "settled" | "active" | null`,
|
||||
`settledAt: IsoDateTime | null` (both with decoding defaults of null —
|
||||
old persisted threads decode unchanged).
|
||||
- Events: `thread.settled` (threadId, settledAt, updatedAt),
|
||||
`thread.unsettled` (threadId, updatedAt). Payload schemas alongside
|
||||
`ThreadArchivedPayload` / `ThreadUnarchivedPayload`.
|
||||
- Commands: `thread.settle`, `thread.unsettle`.
|
||||
3. `apps/server/src/orchestration/decider.ts`: handle both commands, mirroring
|
||||
archive/unarchive. Invariants in `commandInvariants.ts`
|
||||
(`requireThreadNotArchived` applies; settle of an already-settled thread is
|
||||
a no-op rather than an error — idempotent for bulk operations).
|
||||
In the decider paths that record thread activity (user message appended,
|
||||
session started, approval requested): if `settledOverride !== null`, also
|
||||
emit `thread.unsettled` to clear it.
|
||||
4. `packages/client-runtime/src/state/threadReducer.ts`: reduce both events
|
||||
(`threadReducer.ts:87-101` is the archive template). Tests alongside the
|
||||
archive reducer tests.
|
||||
5. `packages/client-runtime` (new `threadSettled.ts` or in `threadSort.ts`):
|
||||
pure `effectiveSettled(shell, { now, autoSettleAfterDays })` implementing
|
||||
the predicate above, plus `lastActivityAt(shell)` (max of
|
||||
latestUserMessageAt, latest turn completion, session start). Unit-test the
|
||||
truth table: each override state × PR state × inactivity.
|
||||
|
||||
Verification: `bun run typecheck`, reducer + predicate unit tests. No visible
|
||||
change anywhere.
|
||||
|
||||
### Phase 2 — SidebarV2 component + beta toggle
|
||||
|
||||
1. Settings UI: "Beta features" section (new panel in
|
||||
`apps/web/src/components/settings/SettingsPanels.tsx` + route, matching the
|
||||
existing settings-page pattern) with the v2 toggle and, indented under it,
|
||||
the auto-settle threshold control.
|
||||
2. Swap seam in `AppSidebarLayout.tsx` as above.
|
||||
3. `apps/web/src/components/SidebarV2.tsx`, reusing shared modules. Structure:
|
||||
- **One flat virtualized list** of all non-archived threads across
|
||||
projects. Sort key: (needs-approval first, by wait time) → then recency
|
||||
(`latestUserMessageAt`, reusing `threadSort.ts`). No show-more, no
|
||||
project collapse, no dnd.
|
||||
- **Row variants** (single `SidebarV2Row` with a `variant` prop, both
|
||||
variants rendered from the same shell data):
|
||||
- `card` (~52px, threads where `effectiveSettled` is false): line 1
|
||||
`ProjectFavicon` + title (+ diff stats when present) + time ("waiting
|
||||
Xm" in amber when approval-blocked, live elapsed for working); line 2
|
||||
structured meta — status word (only for the colored states) · branch ·
|
||||
harness glyph + model · machine (only when the thread's environment is
|
||||
not the current machine). Left rail color only for approval (amber),
|
||||
working (sky, pulsing), failed (red) — Ready rows carry no color or
|
||||
label, just a bold title while unread. No free-text/generated content.
|
||||
- `slim` (~28px, settled): `ProjectFavicon` · title · PR badge when
|
||||
notable · time. Visually close to today's v1 row.
|
||||
- **Status derivation** consolidates `Sidebar.logic.ts`'s pill logic into
|
||||
four visual states: Needs Approval, Working (incl. connecting), Ready
|
||||
(today's Awaiting Input + Plan Ready + Completed-unseen — same user
|
||||
action, different payload), and new Failed (`session.lastError` on a
|
||||
non-running session). Keep it in `Sidebar.logic.ts` so v1 can adopt
|
||||
Failed later too.
|
||||
- **Unread**: bold title until visited, from existing
|
||||
`uiStateStore.threadLastVisitedAtById` — same mechanics as today's
|
||||
Completed-unseen pill.
|
||||
- **Row height changes only on lifecycle transitions** (settle/unsettle),
|
||||
animated with the existing auto-animate pattern. Streaming/status
|
||||
updates within a variant never change height.
|
||||
- Preserved v1 behaviors, via the shared hooks: click-to-open, multi-select
|
||||
(threadSelectionStore), context menu (add Settle/Un-settle entries),
|
||||
inline rename, thread-jump shortcut labels, archive affordance, PR icon
|
||||
link, port/terminal/remote indicators (moved into line 3 / slim row
|
||||
trailing icons).
|
||||
4. Settle affordances:
|
||||
- Hover action on the row (next to today's archive hover button) +
|
||||
context-menu entry + bulk via multi-select.
|
||||
- `useThreadActions`: add `settleThread` / `unsettleThread` mirroring
|
||||
`archiveThread` (`useThreadActions.ts:91-134`), minus the navigation
|
||||
dance — settling never navigates away.
|
||||
- No keyboard shortcut in the first cut; add via keybindings once the
|
||||
affordance proves out.
|
||||
|
||||
Verification: typecheck/lint; toggle on → v2 renders, toggle off → v1
|
||||
identical to before; settle/unsettle round-trips including across a
|
||||
desktop+remote pair; kill a session mid-run → Failed card appears.
|
||||
|
||||
### Phase 3 — Worktree cleanup hook
|
||||
|
||||
Settling is the natural moment to reclaim disk:
|
||||
|
||||
1. On **manual settle** of a thread whose worktree is orphaned
|
||||
(`getOrphanedWorktreePathForThread`, `worktreeCleanup.ts:11-33`): show a
|
||||
non-blocking inline prompt/toast — "Worktree kept · Remove?" — that calls
|
||||
`vcsEnvironment.removeWorktree`. Never remove without an explicit click;
|
||||
never block the settle on the answer. Skip the prompt entirely when the
|
||||
worktree has uncommitted changes or unpushed commits (check via the
|
||||
existing vcs status the sidebar already has).
|
||||
2. **Auto-settle does not touch worktrees** in this phase. A settings-page
|
||||
"Storage" affordance listing orphaned worktrees of settled threads (with
|
||||
sizes, bulk-remove) is the follow-up; tracked but not in scope.
|
||||
|
||||
### Phase 4 — Beta telemetry & exit criteria
|
||||
|
||||
Instrument (whatever the existing analytics path is — if none, a lightweight
|
||||
local counter surfaced in diagnostics is enough for the beta):
|
||||
|
||||
- settle events by source: manual / auto-PR / auto-inactivity / bulk
|
||||
- un-settle events: manual vs. activity-driven (activity-driven un-settles of
|
||||
*manual* settles = the model fighting users)
|
||||
- toggle-off rate after trying v2
|
||||
|
||||
Decision inputs for exiting beta: if manual settling is ~0%, shrink the
|
||||
affordance and lean on auto rules; if activity-unsettle-of-manual-settle is
|
||||
high, the inactivity threshold or unsettle triggers need retuning.
|
||||
|
||||
## Explicitly out of scope
|
||||
|
||||
- Inline approve/reject in the sidebar (concept 3) — needs a safety story.
|
||||
- Message snippets in rows (concept 2) — streaming churn unsolved.
|
||||
- Ops-grid density mode (concept 5).
|
||||
- Auto-archive of long-settled threads.
|
||||
- Removing v1 / making v2 the default.
|
||||
- Project grouping inside v2 (v1 remains available for users who want groups).
|
||||
|
||||
## Open questions
|
||||
|
||||
- Where thread "activity" is centrally observable server-side for the
|
||||
unsettle-on-activity rule — if the decider paths are too scattered, an
|
||||
acceptable fallback is client-side: compute `effectiveSettled` with the
|
||||
activity timestamps and only use the override for manual state (activity
|
||||
newer than `settledAt` wins). Decide during Phase 1 once in the decider.
|
||||
- Whether `settledAt` belongs in the thread *shell* stream (sidebar reads
|
||||
shells only) — it must, or v2 can't sort/collapse without detail loads.
|
||||
Verify shell projection includes it.
|
||||
- Diff stats on cards require checkpoint data in the shell; if absent, defer
|
||||
diff stats rather than loading details for every row.
|
||||
@@ -35,7 +35,6 @@ import {
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
setTheme,
|
||||
@@ -49,7 +48,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
|
||||
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
|
||||
import { getLocalEnvironmentBootstraps } from "./window.ts";
|
||||
|
||||
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "wsl.exe",
|
||||
@@ -130,19 +126,3 @@ describe("getLocalEnvironmentBootstraps", () => {
|
||||
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getWindowFullscreenState", () => {
|
||||
it.effect("reads the current native window state", () => {
|
||||
const window = { isFullScreen: () => true } as Electron.BrowserWindow;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
assert.isTrue(yield* getWindowFullscreenState.handler());
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(ElectronWindow.ElectronWindow)({
|
||||
currentMainOrFirst: Effect.succeed(Option.some(window)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -55,16 +55,6 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const window = yield* electronWindow.currentMainOrFirst;
|
||||
return Option.isSome(window) && window.value.isFullScreen();
|
||||
}),
|
||||
});
|
||||
|
||||
export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
|
||||
result: Schema.Array(DesktopEnvironmentBootstrapSchema),
|
||||
|
||||
@@ -116,19 +116,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => {
|
||||
if (typeof fullscreen !== "boolean") return;
|
||||
listener(fullscreen);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.WINDOW_FULLSCREEN_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(IpcChannels.UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) =>
|
||||
ipcRenderer.invoke(IpcChannels.UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
|
||||
@@ -20,6 +20,7 @@ const clientSettings: ClientSettings = {
|
||||
diffIgnoreWhitespace: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
@@ -27,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopWindow from "./DesktopWindow.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
@@ -46,7 +46,6 @@ const environmentInput = {
|
||||
} satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
function makeFakeBrowserWindow() {
|
||||
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
@@ -67,13 +66,10 @@ function makeFakeBrowserWindow() {
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isFullScreen: vi.fn(() => false),
|
||||
isMinimized: vi.fn(() => false),
|
||||
isVisible: vi.fn(() => true),
|
||||
loadURL: vi.fn(() => Promise.resolve()),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
windowListeners.set(eventName, listener);
|
||||
}),
|
||||
on: vi.fn(),
|
||||
once: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
@@ -92,7 +88,6 @@ function makeFakeBrowserWindow() {
|
||||
send: webContents.send,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
windowListeners,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -343,37 +338,6 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes native macOS fullscreen changes to the renderer", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen");
|
||||
const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen");
|
||||
if (!enterFullscreen || !leaveFullscreen) {
|
||||
return yield* Effect.die("fullscreen listeners were not registered");
|
||||
}
|
||||
|
||||
enterFullscreen();
|
||||
leaveFullscreen();
|
||||
assert.deepEqual(fakeWindow.send.mock.calls, [
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, true],
|
||||
[WINDOW_FULLSCREEN_STATE_CHANNEL, false],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -15,7 +15,7 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
@@ -365,15 +365,6 @@ export const make = Effect.gen(function* () {
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
window.on("enter-full-screen", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, true);
|
||||
});
|
||||
window.on("leave-full-screen", () => {
|
||||
window.webContents.send(WINDOW_FULLSCREEN_STATE_CHANNEL, false);
|
||||
});
|
||||
}
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
|
||||
@@ -1,414 +0,0 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
|
||||
interface Props {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly heading: string;
|
||||
readonly lede: string;
|
||||
readonly effectiveDate: string;
|
||||
readonly lastUpdated: string;
|
||||
readonly sections: ReadonlyArray<readonly [id: string, label: string]>;
|
||||
}
|
||||
|
||||
const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;
|
||||
---
|
||||
|
||||
<Layout title={title} description={description} pageClass="legal-document-page">
|
||||
<div class="legal-page">
|
||||
<a class="legal-index-link" href="/legal"><span aria-hidden="true">←</span> All legal documents</a>
|
||||
<header class="legal-hero">
|
||||
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
|
||||
<h1>{heading}</h1>
|
||||
<p class="legal-lede">{lede}</p>
|
||||
<dl class="legal-dates" aria-label="Document dates">
|
||||
<div>
|
||||
<dt>Effective Date</dt>
|
||||
<dd>{effectiveDate}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Last Updated</dt>
|
||||
<dd>{lastUpdated}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</header>
|
||||
|
||||
<div class="legal-rule" aria-hidden="true"></div>
|
||||
|
||||
<div class="legal-layout">
|
||||
<aside class="legal-nav" aria-label="On this page">
|
||||
<p class="legal-nav-label">On this page</p>
|
||||
<ol>
|
||||
{sections.map(([id, label], index) => (
|
||||
<li>
|
||||
<a href={`#${id}`} data-legal-nav-link={id}>
|
||||
<span>{String(index + 1).padStart(2, "0")}</span>
|
||||
{label}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</aside>
|
||||
|
||||
<article class="legal-copy">
|
||||
<slot />
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
const navLinks = Array.from(
|
||||
document.querySelectorAll<HTMLAnchorElement>("[data-legal-nav-link]"),
|
||||
);
|
||||
const sections = navLinks
|
||||
.map((link) => {
|
||||
const id = link.dataset.legalNavLink;
|
||||
const section = id ? document.getElementById(id) : null;
|
||||
return section ? { link, section } : null;
|
||||
})
|
||||
.filter((entry): entry is { link: HTMLAnchorElement; section: HTMLElement } => entry !== null);
|
||||
|
||||
let activeId = "";
|
||||
let frame = 0;
|
||||
|
||||
const updateActiveSection = () => {
|
||||
frame = 0;
|
||||
const marker = Math.min(180, window.innerHeight * 0.28);
|
||||
let active = sections[0];
|
||||
|
||||
for (const entry of sections) {
|
||||
if (entry.section.getBoundingClientRect().top > marker) break;
|
||||
active = entry;
|
||||
}
|
||||
|
||||
if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
|
||||
active = sections[sections.length - 1];
|
||||
}
|
||||
|
||||
if (!active || active.section.id === activeId) return;
|
||||
activeId = active.section.id;
|
||||
|
||||
for (const { link, section } of sections) {
|
||||
if (section.id === activeId) {
|
||||
link.setAttribute("aria-current", "location");
|
||||
} else {
|
||||
link.removeAttribute("aria-current");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleUpdate = () => {
|
||||
if (frame) return;
|
||||
frame = window.requestAnimationFrame(updateActiveSection);
|
||||
};
|
||||
|
||||
updateActiveSection();
|
||||
window.addEventListener("scroll", scheduleUpdate, { passive: true });
|
||||
window.addEventListener("resize", scheduleUpdate);
|
||||
</script>
|
||||
|
||||
<style is:global>
|
||||
.legal-page {
|
||||
width: min(1120px, calc(100% - 64px));
|
||||
margin: 0 auto;
|
||||
padding: clamp(72px, 10vw, 132px) 0 112px;
|
||||
}
|
||||
|
||||
.legal-index-link {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.legal-hero {
|
||||
max-width: 820px;
|
||||
animation: fade-in 0.8s ease-out both;
|
||||
}
|
||||
|
||||
.legal-hero h1 {
|
||||
margin-top: 18px;
|
||||
font-size: clamp(3.4rem, 8vw, 7.4rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 0.9;
|
||||
}
|
||||
|
||||
.legal-lede {
|
||||
max-width: 720px;
|
||||
margin-top: 34px;
|
||||
color: var(--fg-muted);
|
||||
font-size: clamp(1.05rem, 1.8vw, 1.3rem);
|
||||
line-height: 1.65;
|
||||
letter-spacing: -0.012em;
|
||||
}
|
||||
|
||||
.legal-dates {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 36px;
|
||||
margin-top: 38px;
|
||||
}
|
||||
|
||||
.legal-dates div {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.legal-dates dt,
|
||||
.legal-nav-label,
|
||||
.section-number {
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.legal-dates dd {
|
||||
color: var(--fg);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.legal-rule {
|
||||
height: 1px;
|
||||
margin: 72px 0;
|
||||
background: linear-gradient(90deg, var(--border-strong), var(--border) 65%, transparent);
|
||||
}
|
||||
|
||||
.legal-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 210px minmax(0, 720px);
|
||||
gap: clamp(64px, 10vw, 140px);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.legal-nav {
|
||||
position: sticky;
|
||||
top: 88px;
|
||||
max-height: calc(100vh - 112px);
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.legal-nav ol {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
margin-top: 16px;
|
||||
padding-bottom: 12px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.legal-nav a {
|
||||
display: grid;
|
||||
grid-template-columns: 24px 1fr;
|
||||
gap: 9px;
|
||||
margin-left: -10px;
|
||||
padding: 7px 8px 7px 10px;
|
||||
border-radius: 6px;
|
||||
color: var(--fg-dim);
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.35;
|
||||
transition:
|
||||
color 0.16s ease,
|
||||
background-color 0.16s ease,
|
||||
box-shadow 0.16s ease;
|
||||
}
|
||||
|
||||
.legal-nav a span {
|
||||
color: var(--fg-faint);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.64rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.legal-nav a:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.legal-nav a[aria-current="location"] {
|
||||
color: var(--fg);
|
||||
background: color-mix(in srgb, var(--accent) 8%, transparent);
|
||||
box-shadow: inset 2px 0 var(--accent);
|
||||
}
|
||||
|
||||
.legal-nav a[aria-current="location"] span {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.legal-copy section {
|
||||
scroll-margin-top: 104px;
|
||||
}
|
||||
|
||||
.legal-copy section + section {
|
||||
margin-top: 82px;
|
||||
padding-top: 82px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.section-number {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy h2 {
|
||||
margin: 8px 0 28px;
|
||||
color: var(--fg);
|
||||
font-size: clamp(1.75rem, 3vw, 2.45rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.legal-copy h3 {
|
||||
margin: 32px 0 10px;
|
||||
color: var(--fg);
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
|
||||
.legal-copy h4 {
|
||||
margin: 24px 0 8px;
|
||||
color: var(--fg);
|
||||
font-size: 0.94rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy p,
|
||||
.legal-copy li,
|
||||
.legal-copy address {
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.98rem;
|
||||
font-style: normal;
|
||||
line-height: 1.78;
|
||||
}
|
||||
|
||||
.legal-copy p + p {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.legal-copy strong {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy ul,
|
||||
.legal-copy ol {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin: 18px 0 20px;
|
||||
padding-left: 1.2rem;
|
||||
}
|
||||
|
||||
.legal-copy li {
|
||||
padding-left: 7px;
|
||||
}
|
||||
|
||||
.legal-copy li::marker {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-copy .provider-list {
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
.provider-list a,
|
||||
.legal-copy a {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.legal-copy a {
|
||||
color: var(--fg);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: color-mix(in srgb, var(--accent) 55%, transparent);
|
||||
text-underline-offset: 4px;
|
||||
transition: text-decoration-color 0.16s ease;
|
||||
}
|
||||
|
||||
.legal-copy a:hover {
|
||||
text-decoration-color: var(--accent);
|
||||
}
|
||||
|
||||
.legal-notice {
|
||||
color: var(--fg) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.legal-copy address {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.contact-link {
|
||||
display: inline-block;
|
||||
margin-top: 18px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
.legal-index-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 38px;
|
||||
color: var(--fg-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.legal-page {
|
||||
width: min(100% - 40px, 720px);
|
||||
padding-top: 56px;
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
|
||||
.legal-hero h1 {
|
||||
font-size: clamp(3.1rem, 16vw, 5rem);
|
||||
}
|
||||
|
||||
.legal-rule {
|
||||
margin: 52px 0;
|
||||
}
|
||||
|
||||
.legal-layout {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.legal-nav {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.legal-copy section + section {
|
||||
margin-top: 62px;
|
||||
padding-top: 62px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.legal-page {
|
||||
width: calc(100% - 32px);
|
||||
padding-top: 42px;
|
||||
}
|
||||
|
||||
.legal-lede {
|
||||
margin-top: 26px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.legal-dates {
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.legal-copy p,
|
||||
.legal-copy li,
|
||||
.legal-copy address {
|
||||
font-size: 0.94rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,13 +4,11 @@ import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
interface Props {
|
||||
title?: string;
|
||||
description?: string;
|
||||
pageClass?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
title = "T3 Code",
|
||||
description = "T3 Code — The open-source control plane for coding agents.",
|
||||
pageClass,
|
||||
} = Astro.props;
|
||||
---
|
||||
|
||||
@@ -32,7 +30,7 @@ const {
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class:list={["page", pageClass]}>
|
||||
<div class="page">
|
||||
<nav class="nav">
|
||||
<div class="nav-inner">
|
||||
<a href="/" class="nav-brand" aria-label="T3 Code home">
|
||||
@@ -69,9 +67,6 @@ const {
|
||||
<a href={GITHUB_REPOSITORY_URL} 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>
|
||||
<a href="/terms-of-service">Terms</a>
|
||||
<a href="/privacy-policy">Privacy</a>
|
||||
<a href="/security-policy">Security</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -284,7 +279,7 @@ const {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-x: clip;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.nav {
|
||||
@@ -407,8 +402,6 @@ const {
|
||||
|
||||
.footer-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
@@ -428,28 +421,6 @@ const {
|
||||
padding-left: 20px;
|
||||
padding-right: 20px;
|
||||
}
|
||||
|
||||
.legal-document-page .nav {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding-bottom: max(32px, env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.footer-inner {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
gap: 28px;
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
width: 100%;
|
||||
gap: 14px 20px;
|
||||
justify-content: initial;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
|
||||
const documents = [
|
||||
{
|
||||
number: "01",
|
||||
title: "Privacy Policy",
|
||||
description: "How T3 Code handles information, connected services, and your privacy choices.",
|
||||
href: "/privacy-policy",
|
||||
},
|
||||
{
|
||||
number: "02",
|
||||
title: "Terms of Service",
|
||||
description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",
|
||||
href: "/terms-of-service",
|
||||
},
|
||||
{
|
||||
number: "03",
|
||||
title: "Security Policy",
|
||||
description: "Our security practices, responsible disclosure process, and shared responsibilities.",
|
||||
href: "/security-policy",
|
||||
},
|
||||
] as const;
|
||||
---
|
||||
|
||||
<Layout
|
||||
title="Legal — T3 Code"
|
||||
description="Privacy, terms, and security documents for T3 Code."
|
||||
pageClass="legal-document-page"
|
||||
>
|
||||
<div class="legal-index">
|
||||
<header class="legal-index-hero">
|
||||
<p class="eyebrow">T3 Tools, Inc. / Legal</p>
|
||||
<h1>Legal</h1>
|
||||
<p>Policies and terms for T3 Code, collected in one place.</p>
|
||||
</header>
|
||||
|
||||
<nav class="document-list" aria-label="Legal documents">
|
||||
{documents.map((document) => (
|
||||
<a href={document.href} class="document-card">
|
||||
<span class="document-number">{document.number}</span>
|
||||
<span class="document-copy">
|
||||
<strong>{document.title}</strong>
|
||||
<span>{document.description}</span>
|
||||
</span>
|
||||
<span class="document-arrow" aria-hidden="true">↗</span>
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<style>
|
||||
.legal-index {
|
||||
width: min(960px, calc(100% - 64px));
|
||||
margin: 0 auto;
|
||||
padding: clamp(72px, 10vw, 132px) 0 112px;
|
||||
}
|
||||
|
||||
.legal-index-hero {
|
||||
max-width: 680px;
|
||||
animation: fade-in 0.7s ease-out both;
|
||||
}
|
||||
|
||||
.legal-index h1 {
|
||||
margin-top: 18px;
|
||||
font-size: clamp(4rem, 10vw, 7.4rem);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 0.9;
|
||||
}
|
||||
|
||||
.legal-index-hero > p:last-child {
|
||||
margin-top: 30px;
|
||||
color: var(--fg-muted);
|
||||
font-size: clamp(1.05rem, 2vw, 1.3rem);
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.document-list {
|
||||
display: grid;
|
||||
margin-top: clamp(64px, 9vw, 96px);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.document-card {
|
||||
display: grid;
|
||||
grid-template-columns: 42px minmax(0, 1fr) auto;
|
||||
gap: 24px;
|
||||
align-items: center;
|
||||
padding: 30px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
transition: background-color 0.18s ease, padding 0.18s ease;
|
||||
}
|
||||
|
||||
.document-number {
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.7rem;
|
||||
letter-spacing: 0.1em;
|
||||
}
|
||||
|
||||
.document-copy {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.document-copy strong {
|
||||
color: var(--fg);
|
||||
font-size: 1.2rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.document-copy > span {
|
||||
color: var(--fg-dim);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.document-arrow {
|
||||
color: var(--fg-dim);
|
||||
font-size: 1.25rem;
|
||||
transition: color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.document-card:hover {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
|
||||
.document-card:hover .document-arrow {
|
||||
color: var(--fg);
|
||||
transform: translate(2px, -2px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
.legal-index {
|
||||
width: min(100% - 40px, 720px);
|
||||
padding-top: 56px;
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
|
||||
.document-card {
|
||||
grid-template-columns: 30px minmax(0, 1fr) auto;
|
||||
gap: 14px;
|
||||
padding: 24px 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.legal-index {
|
||||
width: calc(100% - 32px);
|
||||
padding-top: 42px;
|
||||
}
|
||||
|
||||
.legal-index h1 {
|
||||
font-size: 4.4rem;
|
||||
}
|
||||
|
||||
.document-copy strong {
|
||||
font-size: 1.08rem;
|
||||
}
|
||||
|
||||
.document-copy > span {
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,445 +0,0 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["information", "Personal information we collect"],
|
||||
["uses", "How we use your personal information"],
|
||||
["sharing", "How we share your personal information"],
|
||||
["choices", "Your choices regarding your personal information"],
|
||||
["security", "Security of your personal information"],
|
||||
["international", "International users"],
|
||||
["children", "Children"],
|
||||
["do-not-track", "Do Not Track"],
|
||||
["updates", "Updates to this Privacy Policy"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Privacy Policy — T3 Code"
|
||||
description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."
|
||||
heading="T3 Code Privacy Policy"
|
||||
lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."
|
||||
effectiveDate="2026-07-14"
|
||||
lastUpdated="2026-07-14"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3
|
||||
Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3
|
||||
Code desktop and mobile applications, the hosted T3 Code web application located at
|
||||
{" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect
|
||||
service (together, the “Services”), or visit the T3 Code marketing website located at
|
||||
{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to
|
||||
personal information we collect through the Site and the Services, as well as personal
|
||||
information you provide to us directly.
|
||||
</p>
|
||||
<p>
|
||||
By using the Site or the Services, you acknowledge the practices described in this
|
||||
Policy. If you do not agree with this Policy, please do not use the Site or the Services.
|
||||
This Policy does not govern third-party coding agents, artificial-intelligence providers,
|
||||
identity providers, or environments that you choose to connect to T3 Code; those third
|
||||
parties process information under their own terms and privacy policies.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="information">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Personal Information We Collect</h2>
|
||||
|
||||
<p>
|
||||
We collect personal information about you in different ways depending on how you use
|
||||
T3 Code and which optional features you enable.
|
||||
</p>
|
||||
|
||||
<h3>Personal Information From Users of T3 Code</h3>
|
||||
|
||||
<p>
|
||||
When you use T3 Code, we may collect the following categories of personal information:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Account information.</strong> If you create or sign in to a T3 account, we
|
||||
receive general identifiers and profile information from our authentication provider
|
||||
and the identity provider you select. This may include your name, email address,
|
||||
profile image, user ID, sign-in method, and authentication credentials or tokens.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Environment and device information.</strong> If you enable T3 Connect, we
|
||||
process information needed to connect and secure your environments and devices,
|
||||
including identifiers, labels you assign, public keys, connection endpoints,
|
||||
credential hashes, connection status, app and operating-system versions, and
|
||||
notification preferences.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Agent activity and notifications.</strong> If you enable notifications or Live
|
||||
Activities, we process push tokens and limited activity information needed to provide
|
||||
those features, such as project and thread titles, model name, status, and activity
|
||||
headline.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Information you provide to us.</strong> We collect information that you choose
|
||||
to provide when you request support, send feedback, or otherwise communicate with us.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>Personal Information From Users of Our Site Generally</h3>
|
||||
<p>
|
||||
When you visit the Site or use online portions of the Services, we and our service
|
||||
providers may automatically log online identifiers and internet-activity information,
|
||||
including your Internet Protocol (IP) address, device and operating-system type, browser
|
||||
or app type and version, pages viewed, access times, request timestamps, connection
|
||||
events, latency, error details, and diagnostic traces. The amount of information we
|
||||
collect depends on the Services you use and your device and browser settings.
|
||||
</p>
|
||||
<p>
|
||||
We use operational and diagnostic information to provide, secure, maintain, and
|
||||
troubleshoot the Services, not for targeted advertising.
|
||||
</p>
|
||||
|
||||
<h3>Information We Get From Others</h3>
|
||||
<p>
|
||||
We may receive personal information from service providers that help us operate the
|
||||
Services, such as authentication and identity providers, app stores, device-platform
|
||||
providers, and coding-agent providers you choose to use. We may combine this information
|
||||
with information we collect through the Site and the Services.
|
||||
</p>
|
||||
|
||||
<h3>Cookies and Local Storage</h3>
|
||||
<p>
|
||||
The Site and online portions of the Services may use cookies or similar technologies to
|
||||
operate essential features, maintain sessions, remember preferences, and understand
|
||||
whether the Services are functioning correctly. T3 Code also stores connection settings,
|
||||
credentials, preferences, drafts, and cached thread, file, branch, and server metadata on
|
||||
your device. Credentials and session tokens use platform-provided protected storage where
|
||||
supported. Information stored only on your device is not collected by T3 Tools unless it
|
||||
is transmitted as part of a feature you use.
|
||||
</p>
|
||||
|
||||
<h3>Device Permissions</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames
|
||||
are processed on your device.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Photos and files.</strong> Items you select are accessed only to preview them or
|
||||
attach them to a request you initiate.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Notifications.</strong> Used only if you enable agent-status notifications or
|
||||
Live Activities.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Local network.</strong> Used to discover or connect to T3 Code environments
|
||||
accessible from your machine over the network.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section id="uses">
|
||||
<p class="section-number">03</p>
|
||||
<h2>How We Use Your Personal Information</h2>
|
||||
<p>
|
||||
Subject to this Policy and applicable terms governing third-party applications and
|
||||
services, we may use personal information for the following purposes:
|
||||
</p>
|
||||
<ul>
|
||||
<li>To establish and verify your identity and authenticate your account;</li>
|
||||
<li>To link and protect devices and environments and deliver optional notifications;</li>
|
||||
<li>To process and fulfill requests you make through the Services;</li>
|
||||
<li>To provide customer service and respond to support requests and feedback;</li>
|
||||
<li>To communicate with you about the Services and your relationship with us;</li>
|
||||
<li>To monitor reliability, prevent abuse, and investigate security incidents;</li>
|
||||
<li>To comply with applicable law and enforce the terms governing the Services; and</li>
|
||||
<li>
|
||||
To analyze and improve T3 Code using aggregated, de-identified, or other anonymous
|
||||
operational information.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h3>Training of AI Models</h3>
|
||||
<p>
|
||||
We do not use your personal information, source code, prompts, or agent responses to
|
||||
train artificial-intelligence models.
|
||||
</p>
|
||||
|
||||
<h3>Compliance and Protection</h3>
|
||||
<p>We may use personal information to:</p>
|
||||
<ul>
|
||||
<li>Comply with applicable laws, lawful requests, and legal process;</li>
|
||||
<li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>
|
||||
<li>Audit our internal processes for legal, contractual, and policy compliance;</li>
|
||||
<li>Enforce the terms and conditions that govern the Site and the Services; and</li>
|
||||
<li>
|
||||
Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,
|
||||
unethical, or illegal activity, including cyberattacks and identity theft.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
We may also use personal information for other purposes consistent with this Policy or
|
||||
explained to you when we collect the information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="sharing">
|
||||
<p class="section-number">04</p>
|
||||
<h2>How We Share Your Personal Information</h2>
|
||||
<p>
|
||||
We may disclose the categories of personal information described above to the following
|
||||
categories of third parties:
|
||||
</p>
|
||||
|
||||
<h3>Providers You Choose</h3>
|
||||
<p>
|
||||
At your direction, prompts, files, and related content are sent to coding agents and
|
||||
artificial-intelligence providers configured in your environment. Because you bring and
|
||||
configure your own coding-agent harness and provider, the applicable third parties vary.
|
||||
Those providers process information under their own terms and privacy policies.
|
||||
</p>
|
||||
|
||||
<h3>Third-Party Service Providers</h3>
|
||||
<p>
|
||||
We use third-party service providers to help provide the Services and operate our
|
||||
business. Depending on the features you use, these providers may include:
|
||||
</p>
|
||||
<ul class="provider-list">
|
||||
<li>
|
||||
<strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />
|
||||
We use Clerk to provide account authentication.<br />
|
||||
You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"
|
||||
>https://clerk.com/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />
|
||||
We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />
|
||||
You can view Cloudflare's privacy policy here:{" "}<a
|
||||
href="https://www.cloudflare.com/policies/privacy/"
|
||||
>https://www.cloudflare.com/policies/privacy/</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />
|
||||
We use PlanetScale to host the database that supports T3 Connect.<br />
|
||||
You can view PlanetScale's privacy policy here:{" "}<a
|
||||
href="https://planetscale.com/legal/privacy"
|
||||
>https://planetscale.com/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />
|
||||
We use Vercel to host and deploy the T3 Code Site.<br />
|
||||
You can view Vercel's privacy notice here:{" "}<a
|
||||
href="https://vercel.com/legal/privacy-notice"
|
||||
>https://vercel.com/legal/privacy-notice</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />
|
||||
We use Axiom for operational diagnostics that help us maintain and troubleshoot the
|
||||
Services.<br />
|
||||
You can view Axiom's privacy policy here:{" "}<a
|
||||
href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />
|
||||
We use Expo for application updates and related mobile-app services.<br />
|
||||
You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"
|
||||
>https://expo.dev/privacy</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Apple</strong> <em>(Apple Inc.)</em>.<br />
|
||||
We use Apple services for app distribution, optional authentication, and platform
|
||||
notifications.<br />
|
||||
You can view Apple's privacy policy here:{" "}<a
|
||||
href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a
|
||||
>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Google</strong> <em>(Google LLC)</em>.<br />
|
||||
We use Google services for app distribution and optional authentication.<br />
|
||||
You can view Google's privacy policy here:{" "}<a
|
||||
href="https://policies.google.com/privacy">https://policies.google.com/privacy</a
|
||||
>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
These providers process information for us under their own contractual and privacy
|
||||
obligations.
|
||||
</p>
|
||||
|
||||
<h3>Affiliates and Professional Advisors</h3>
|
||||
<p>
|
||||
We may share personal information with our affiliates for purposes consistent with this
|
||||
Policy and with lawyers, accountants, bankers, and other professional advisors in the
|
||||
course of the services they provide to us.
|
||||
</p>
|
||||
|
||||
<h3>Corporate Restructuring</h3>
|
||||
<p>
|
||||
We may share some or all personal information in connection with or during negotiation of
|
||||
a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of
|
||||
assets, or similar transaction. If another company acquires T3 Tools or its assets, that
|
||||
company may possess the personal information collected by us and assume the rights and
|
||||
obligations described in this Policy.
|
||||
</p>
|
||||
|
||||
<h3>Legal and Safety Disclosures</h3>
|
||||
<p>
|
||||
We may disclose personal information if we believe in good faith that disclosure is
|
||||
necessary to comply with law or legal process; protect or defend the rights, property, or
|
||||
safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent
|
||||
fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the
|
||||
Services. We may also share personal information at your direction, with your consent, or
|
||||
as described to you when the information is collected.
|
||||
</p>
|
||||
|
||||
<h3>No Sale of Personal Information</h3>
|
||||
<p>
|
||||
We do not sell your personal information or share it for cross-context behavioral or
|
||||
targeted advertising.
|
||||
</p>
|
||||
|
||||
<h3>Third-Party Websites and Services</h3>
|
||||
<p>
|
||||
The Site and the Services may contain links to third-party websites or services. When you
|
||||
follow a third-party link or connect a third-party service, that third party may collect
|
||||
personal information from you. We do not control and are not responsible for the privacy
|
||||
practices or content of third parties.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="choices">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Your Choices Regarding Your Personal Information</h2>
|
||||
|
||||
<h3>Account and Connection Choices</h3>
|
||||
<p>
|
||||
You may use local or direct connections without signing in to a T3 account. You can
|
||||
disconnect environments, sign out, disable optional notifications and Live Activities,
|
||||
and clear local caches from Settings. You can grant or revoke camera, photo, local-network,
|
||||
and notification permissions in your device settings.
|
||||
</p>
|
||||
|
||||
<h3>Cookies and Local Data</h3>
|
||||
<p>
|
||||
You can use your browser settings to stop accepting or to delete cookies, although some
|
||||
portions of the Site or the Services may not function correctly as a result. Information
|
||||
stored only on your device remains there until you clear it, remove the relevant
|
||||
connection, or uninstall the app. The mobile app provides cache controls under
|
||||
{" "}<strong>Settings → App → Client Storage</strong>.
|
||||
</p>
|
||||
|
||||
<h3>Retention and Deletion</h3>
|
||||
<p>
|
||||
We retain account, environment-link, device-registration, notification, and security
|
||||
information while your account or the relevant feature is active and for as long as
|
||||
reasonably necessary to provide the Services, protect them from abuse, comply with law,
|
||||
and resolve disputes. Operational diagnostic traces are configured to expire after 30
|
||||
days. Some records may remain longer in backups or where retention is required for
|
||||
security, fraud prevention, or legal compliance.
|
||||
</p>
|
||||
<p>
|
||||
To request deletion of your T3 account and associated T3 Connect data, email{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>{" "}from the email address associated with your account. We may need to verify your
|
||||
identity. Deleting a T3 account does not delete information held by an environment or
|
||||
coding-agent provider you control; contact those providers or delete that information
|
||||
directly.
|
||||
</p>
|
||||
|
||||
<h3>Your Privacy Rights</h3>
|
||||
<p>
|
||||
Depending on where you live, you may have rights to request access to, correction of,
|
||||
deletion of, or a portable copy of your personal information, or to restrict or object
|
||||
to certain processing. You may also have the right to appeal our response or complain to
|
||||
a data-protection authority. We will honor applicable rights after verifying your
|
||||
request.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="security">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Security of Your Personal Information</h2>
|
||||
<p>
|
||||
T3 Tools is committed to protecting the security of your personal information. We use
|
||||
administrative, technical, and organizational safeguards designed to protect personal
|
||||
information from unauthorized access, use, or disclosure. These safeguards include
|
||||
encrypted network transport, scoped and proof-bound access tokens for supported
|
||||
connection flows, protected credential storage, and redaction of authorization headers
|
||||
from relay diagnostics.
|
||||
</p>
|
||||
<p>
|
||||
No method of transmission over the Internet or method of electronic storage is completely
|
||||
secure. While we use reasonable efforts to protect personal information, we cannot
|
||||
guarantee its absolute security. You are responsible for securing the environments,
|
||||
coding-agent accounts, credentials, and networks that you connect to T3 Code.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="international">
|
||||
<p class="section-number">07</p>
|
||||
<h2>International Users</h2>
|
||||
<p>
|
||||
The Site and the Services are provided from the United States and are governed by United
|
||||
States law. If you use the Site or the Services from outside the United States, your
|
||||
personal information may be transferred to and processed in the United States and other
|
||||
countries where we or our service providers operate. Where required, we use lawful
|
||||
safeguards for international transfers of personal information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="children">
|
||||
<p class="section-number">08</p>
|
||||
<h2>Children</h2>
|
||||
<p>
|
||||
The Site and the Services are not intended for children under 13 years of age, and you
|
||||
must be at least 13 years old to use them. We do not knowingly collect, use, or disclose
|
||||
personal information from children under 13. If you believe a child under 13 has provided
|
||||
us with personal information, please contact us so that we can take appropriate action.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="do-not-track">
|
||||
<p class="section-number">09</p>
|
||||
<h2>Do Not Track</h2>
|
||||
<p>
|
||||
We currently do not respond to browser “Do Not Track” signals. T3 Code does not use
|
||||
personal information for cross-context behavioral or targeted advertising.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="updates">
|
||||
<p class="section-number">10</p>
|
||||
<h2>Updates to This Privacy Policy</h2>
|
||||
<p>
|
||||
We reserve the right to update this Policy from time to time. If we make material changes,
|
||||
we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”
|
||||
above, and provide any additional notice required by law. Except as otherwise indicated,
|
||||
changes become effective when the revised Policy is posted.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">11</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
If you have questions about this Policy or wish to make a privacy or deletion request,
|
||||
please contact us at:
|
||||
</p>
|
||||
<address>
|
||||
<strong>T3 Tools, Inc.</strong><br />
|
||||
2261 Market Street #5309<br />
|
||||
San Francisco, CA 94114<br />
|
||||
United States
|
||||
</address>
|
||||
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -1,187 +0,0 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["reporting", "Reporting security issues"],
|
||||
["safe-harbor", "Responsible research and safe harbor"],
|
||||
["practices", "Our security practices"],
|
||||
["responsibilities", "Your responsibilities"],
|
||||
["updates", "Updates to this policy"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Security Policy — T3 Code"
|
||||
description="How to report security issues in T3 Code and how T3 Tools approaches product security."
|
||||
heading="T3 Code Security Policy"
|
||||
lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."
|
||||
effectiveDate="2026-07-15"
|
||||
lastUpdated="2026-07-15"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
This Security Policy describes the vulnerability-reporting process and security practices for
|
||||
the T3 Code desktop and mobile applications, the hosted application at{" "}<a
|
||||
href="https://app.t3.codes">https://app.t3.codes</a
|
||||
>, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"
|
||||
>https://t3.codes</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
T3 Code connects software running on your devices and in environments you control with
|
||||
coding-agent harnesses and providers you choose. We secure the software and infrastructure
|
||||
operated by T3 Tools, but we do not control the security of your devices, environments,
|
||||
repositories, networks, credentials, or third-party providers. Please review the shared
|
||||
responsibilities below when assessing risk.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="reporting">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Reporting Security Issues</h2>
|
||||
<p>
|
||||
If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated
|
||||
infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not
|
||||
disclose the issue publicly until we have had a reasonable opportunity to investigate and
|
||||
remediate it.
|
||||
</p>
|
||||
<p>Please include, when available:</p>
|
||||
<ul>
|
||||
<li>A description of the issue and its potential impact;</li>
|
||||
<li>The affected application, version, URL, endpoint, or component;</li>
|
||||
<li>Clear reproduction steps or a minimal proof of concept;</li>
|
||||
<li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>
|
||||
<li>Your preferred contact information and whether you want public credit.</li>
|
||||
</ul>
|
||||
<p>
|
||||
We aim to acknowledge complete reports within one business day, keep reporters informed of
|
||||
material progress, and coordinate disclosure after a fix is available. Resolution time varies
|
||||
with severity, complexity, and dependencies on third parties.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="safe-harbor">
|
||||
<p class="section-number">03</p>
|
||||
<h2>Responsible Research and Safe Harbor</h2>
|
||||
<p>
|
||||
We support good-faith security research. If you make a genuine effort to comply with this
|
||||
policy, avoid harm, respect privacy, and report findings promptly, we will treat your research
|
||||
as authorized and will not initiate legal action against you for accidental, good-faith
|
||||
violations of this policy. If a third party initiates legal action concerning compliant
|
||||
research, we will make our authorization known where appropriate.
|
||||
</p>
|
||||
<p>To remain within this safe harbor, you must:</p>
|
||||
<ul>
|
||||
<li>Test only accounts, data, and systems you own or have explicit permission to test;</li>
|
||||
<li>Stop and report immediately if you encounter personal, confidential, or production data;</li>
|
||||
<li>Access only the minimum information needed to demonstrate the issue;</li>
|
||||
<li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>
|
||||
<li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>
|
||||
<li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>
|
||||
<li>Give us reasonable time to address the issue before public disclosure.</li>
|
||||
</ul>
|
||||
<p>
|
||||
This safe harbor does not authorize violations of law or activity outside the scope of this
|
||||
policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools
|
||||
in its discretion.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="practices">
|
||||
<p class="section-number">04</p>
|
||||
<h2>Our Security Practices</h2>
|
||||
<p>
|
||||
We use administrative, technical, and organizational safeguards designed for the nature of T3
|
||||
Code and the information processed by T3 Tools-operated services. These practices include:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain
|
||||
between your clients, your environment, and the harnesses and providers you configure. We
|
||||
process information through T3 Tools-operated infrastructure only when needed for a feature
|
||||
you enable.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted
|
||||
transport. Supported connection flows use scoped credentials and security controls designed
|
||||
to reduce unauthorized reuse.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for
|
||||
credentials and session tokens where supported. We design operational logging to avoid
|
||||
collecting secrets that are not needed to operate or troubleshoot the Services.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Access controls.</strong> Access to production systems and operational data is limited
|
||||
according to job responsibilities and protected using authentication and authorization
|
||||
controls.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for
|
||||
reliability and security events, review dependencies, and deploy updates and mitigations as
|
||||
appropriate.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Established providers.</strong> We use specialized providers for services such as
|
||||
authentication, hosting, and application distribution and evaluate the controls relevant to
|
||||
their role.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
No system is completely secure. These practices reduce risk but do not guarantee that the Site
|
||||
or Services will be free from vulnerabilities or unauthorized access.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="responsibilities">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Your Responsibilities</h2>
|
||||
<p>
|
||||
Because you control much of the T3 Code execution path, you play an important role in securing
|
||||
it. You are responsible for:
|
||||
</p>
|
||||
<ul>
|
||||
<li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>
|
||||
<li>Securing your devices, repositories, environments, networks, and backups;</li>
|
||||
<li>Protecting account, provider, repository, and environment credentials;</li>
|
||||
<li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>
|
||||
<li>Granting providers and integrations only the permissions they need;</li>
|
||||
<li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>
|
||||
<li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>
|
||||
<li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>
|
||||
</ul>
|
||||
<p>
|
||||
Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.
|
||||
Revoke any secret that may have been exposed before sharing sanitized evidence with us.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="updates">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Updates to This Policy</h2>
|
||||
<p>
|
||||
We may update this Security Policy as T3 Code, our infrastructure, and security practices
|
||||
evolve. We will post revisions at this URL and update the dates above. Material changes to the
|
||||
vulnerability-reporting process or safe-harbor terms will apply prospectively.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">07</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
Report security issues or ask security-related questions at{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>.
|
||||
</p>
|
||||
<p>
|
||||
For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
|
||||
For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.
|
||||
</p>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -1,396 +0,0 @@
|
||||
---
|
||||
import LegalPage from "../components/LegalPage.astro";
|
||||
|
||||
const sections = [
|
||||
["introduction", "Introduction"],
|
||||
["accounts", "Accounts"],
|
||||
["content", "Your content and providers"],
|
||||
["rights", "T3 Code and proprietary rights"],
|
||||
["acceptable-use", "Acceptable use"],
|
||||
["availability", "Availability and changes"],
|
||||
["fees", "Fees"],
|
||||
["privacy", "Privacy"],
|
||||
["termination", "Suspension and termination"],
|
||||
["beta", "Beta services"],
|
||||
["disclaimers", "Disclaimers"],
|
||||
["liability", "Limitation of liability"],
|
||||
["indemnification", "Indemnification"],
|
||||
["copyright", "Copyright complaints"],
|
||||
["third-parties", "Third-party services"],
|
||||
["feedback", "Feedback"],
|
||||
["disputes", "Dispute resolution"],
|
||||
["miscellaneous", "Miscellaneous"],
|
||||
["changes", "Changes to these Terms"],
|
||||
["contact", "Contact us"],
|
||||
] as const;
|
||||
---
|
||||
|
||||
<LegalPage
|
||||
title="Terms of Service — T3 Code"
|
||||
description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."
|
||||
heading="T3 Code Terms of Service"
|
||||
lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."
|
||||
effectiveDate="2026-07-15"
|
||||
lastUpdated="2026-07-15"
|
||||
sections={sections}
|
||||
>
|
||||
<section id="introduction">
|
||||
<p class="section-number">01</p>
|
||||
<h2>Introduction</h2>
|
||||
<p>
|
||||
These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.
|
||||
(“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop
|
||||
and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"
|
||||
>https://app.t3.codes</a
|
||||
>, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code
|
||||
marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).
|
||||
</p>
|
||||
<p>
|
||||
By accessing or using the Site or Services, you agree to these Terms. If you use the Services
|
||||
for an organization, you represent that you have authority to bind that organization, and
|
||||
“you” includes the organization. If you do not agree to these Terms, do not use the Site or
|
||||
Services.
|
||||
</p>
|
||||
<p>
|
||||
You must be at least 13 years old to use the Site or Services. If the law where you live
|
||||
requires a greater age to enter into these Terms, you must meet that requirement or have a
|
||||
parent or legal guardian agree on your behalf.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="accounts">
|
||||
<p class="section-number">02</p>
|
||||
<h2>Accounts</h2>
|
||||
<p>
|
||||
You can use some T3 Code features without creating a T3 account. An account may be required
|
||||
for account-backed features, including T3 Connect. You agree to provide accurate account
|
||||
information, keep your credentials secure, and promptly notify us if you suspect unauthorized
|
||||
access. You are responsible for activity performed through your account and connected devices,
|
||||
except to the extent caused by our failure to use reasonable security measures.
|
||||
</p>
|
||||
<p>
|
||||
You may not share credentials in a way that compromises the Services, impersonate another
|
||||
person, or create accounts through unauthorized automated means. We may require reasonable
|
||||
verification before restoring access or acting on an account request.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="content">
|
||||
<p class="section-number">03</p>
|
||||
<h2>Your Content and Providers</h2>
|
||||
<p>
|
||||
T3 Code can help you send prompts, source files, images, attachments, review comments, and
|
||||
instructions to coding-agent harnesses and providers you choose, and display their responses,
|
||||
command output, file changes, source code, and diffs (collectively, “User Content”). You retain
|
||||
all rights you have in your User Content.
|
||||
</p>
|
||||
<p>
|
||||
You bring and configure your own coding-agent harness and provider. Your User Content is
|
||||
ordinarily processed in the environment you control and by the providers you select, not by
|
||||
T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User
|
||||
Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and
|
||||
process that content only as reasonably necessary to provide, secure, and troubleshoot that
|
||||
feature. This license ends when the content is no longer needed for those purposes, subject to
|
||||
reasonable backup, security, and legal-retention requirements.
|
||||
</p>
|
||||
<p>
|
||||
You represent that you have the rights and permissions needed to use and submit User Content
|
||||
and to direct its processing by your selected harnesses and providers. You are responsible for
|
||||
reviewing those providers’ terms, privacy practices, data controls, and output before using
|
||||
them with confidential, proprietary, regulated, or personal information.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="rights">
|
||||
<p class="section-number">04</p>
|
||||
<h2>T3 Code and Proprietary Rights</h2>
|
||||
<p>
|
||||
T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted
|
||||
infrastructure, documentation, and other materials, excluding User Content and third-party
|
||||
materials. These Terms do not transfer ownership of either party’s intellectual property.
|
||||
</p>
|
||||
<p>
|
||||
Portions of T3 Code are available as open-source software. Your use, copying, modification, and
|
||||
distribution of that source code are governed by the license included with the applicable
|
||||
repository or component. These Terms govern your use of the hosted Services and do not limit
|
||||
rights granted to you by an applicable open-source license.
|
||||
</p>
|
||||
<p>
|
||||
Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right
|
||||
to access and use the Services for lawful personal or internal business purposes. You may not
|
||||
use our trademarks, service marks, or trade dress without written permission.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="acceptable-use">
|
||||
<p class="section-number">05</p>
|
||||
<h2>Acceptable Use</h2>
|
||||
<p>You may not use the Site or Services to:</p>
|
||||
<ul>
|
||||
<li>Violate applicable law or another person’s rights;</li>
|
||||
<li>Upload, transmit, or generate content you do not have the right to use;</li>
|
||||
<li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>
|
||||
<li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>
|
||||
<li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>
|
||||
<li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>
|
||||
<li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>
|
||||
<li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>
|
||||
</ul>
|
||||
<p>
|
||||
Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.
|
||||
We may investigate suspected violations and take proportionate action to protect users and the
|
||||
Services.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="availability">
|
||||
<p class="section-number">06</p>
|
||||
<h2>Availability and Changes</h2>
|
||||
<p>
|
||||
We may add, change, suspend, or discontinue features, integrations, or supported platforms. We
|
||||
aim to provide reasonable notice when a change materially reduces an account-backed feature,
|
||||
but urgent security, legal, or reliability changes may take effect immediately. The Services
|
||||
may be unavailable because of maintenance, provider outages, network conditions, or events
|
||||
outside our control.
|
||||
</p>
|
||||
<p>
|
||||
T3 Code depends on software, environments, networks, and coding-agent providers that you
|
||||
configure or that third parties operate. We do not control their availability, compatibility,
|
||||
pricing, or behavior.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="fees">
|
||||
<p class="section-number">07</p>
|
||||
<h2>Fees</h2>
|
||||
<p>
|
||||
T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state
|
||||
otherwise for a feature. You remain responsible for charges from your coding-agent providers,
|
||||
cloud infrastructure, network operators, app stores, and other third parties. If we introduce
|
||||
a paid feature, we will present its price and applicable payment terms before you purchase it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="privacy">
|
||||
<p class="section-number">08</p>
|
||||
<h2>Privacy</h2>
|
||||
<p>
|
||||
Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and
|
||||
shares personal information when you use the Site and Services. Third-party environments,
|
||||
harnesses, identity providers, and coding-agent providers process information under their own
|
||||
terms and privacy policies.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="termination">
|
||||
<p class="section-number">09</p>
|
||||
<h2>Suspension and Termination</h2>
|
||||
<p>
|
||||
You may stop using the Services at any time. You may disconnect environments and devices from
|
||||
within T3 Code and may request deletion of an account as described in our Privacy Policy.
|
||||
</p>
|
||||
<p>
|
||||
We may suspend or terminate access to account-backed or hosted features if we reasonably
|
||||
believe you materially violated these Terms, created a security or legal risk, failed to pay an
|
||||
applicable fee, or used the Services in a way that could harm other users or shared
|
||||
infrastructure. When practicable, we will give notice and an opportunity to cure. We may act
|
||||
immediately where needed to prevent harm or comply with law.
|
||||
</p>
|
||||
<p>
|
||||
Provisions that by their nature should survive termination—including ownership, disclaimers,
|
||||
limitations of liability, indemnification, and dispute terms—will survive.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="beta">
|
||||
<p class="section-number">10</p>
|
||||
<h2>Beta Services</h2>
|
||||
<p>
|
||||
T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,
|
||||
preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,
|
||||
change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole
|
||||
copy of important work, and review proposed commands and file changes before applying them.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="disclaimers">
|
||||
<p class="section-number">11</p>
|
||||
<h2>Disclaimers</h2>
|
||||
<p class="legal-notice">
|
||||
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS
|
||||
AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
|
||||
</p>
|
||||
<p>
|
||||
Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,
|
||||
or harmful output. You are responsible for reviewing output, commands, patches, and other
|
||||
actions before relying on or executing them. We do not warrant that the Services or third-party
|
||||
output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.
|
||||
</p>
|
||||
<p>
|
||||
Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not
|
||||
apply to you.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="liability">
|
||||
<p class="section-number">12</p>
|
||||
<h2>Limitation of Liability</h2>
|
||||
<p class="legal-notice">
|
||||
TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,
|
||||
AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
|
||||
EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS
|
||||
OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.
|
||||
</p>
|
||||
<p>
|
||||
To the maximum extent permitted by law, our aggregate liability for all claims arising from or
|
||||
relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount
|
||||
you paid directly to T3 Tools for the Services during the 12 months before the event giving rise
|
||||
to the claim. These limitations apply regardless of the legal theory and even if a remedy fails
|
||||
of its essential purpose. They do not limit liability that cannot lawfully be limited.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="indemnification">
|
||||
<p class="section-number">13</p>
|
||||
<h2>Indemnification</h2>
|
||||
<p>
|
||||
To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its
|
||||
affiliates, officers, employees, and agents from third-party claims, damages, losses, and
|
||||
reasonable legal fees arising from your User Content, your use of the Site or Services in
|
||||
violation of these Terms or law, or your infringement of another person’s rights. We will
|
||||
promptly notify you of a covered claim and reasonably cooperate in its defense. You may not
|
||||
settle a claim in a way that admits fault by or imposes obligations on us without our written
|
||||
consent.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="copyright">
|
||||
<p class="section-number">14</p>
|
||||
<h2>Copyright Complaints</h2>
|
||||
<p>
|
||||
If you believe material available through a T3 Tools-operated part of the Site or Services
|
||||
infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a
|
||||
>{" "}identifying the copyrighted work, the allegedly infringing material and its location, your
|
||||
contact information, a statement of good-faith belief, a statement under penalty of perjury
|
||||
that the notice is accurate and you are authorized to act, and your physical or electronic
|
||||
signature.
|
||||
</p>
|
||||
<p>
|
||||
T3 Tools does not control content stored only in a user’s environment or held by a user-selected
|
||||
provider. Requests concerning that material should be directed to the operator that hosts it.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="third-parties">
|
||||
<p class="section-number">15</p>
|
||||
<h2>Third-Party Services</h2>
|
||||
<p>
|
||||
The Services may connect to or display content from third-party coding agents, model providers,
|
||||
identity providers, repositories, app stores, websites, and infrastructure. Your use of those
|
||||
services is governed by their terms. We do not endorse or control third-party services and are
|
||||
not responsible for their content, security, availability, output, or data practices.
|
||||
</p>
|
||||
<p>
|
||||
Third-party and open-source software included with T3 Code is governed by its applicable
|
||||
license notices. Where those licenses conflict with these Terms for that software, the
|
||||
applicable open-source license controls.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="feedback">
|
||||
<p class="section-number">16</p>
|
||||
<h2>Feedback</h2>
|
||||
<p>
|
||||
If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a
|
||||
perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback
|
||||
without restriction or compensation. This does not transfer ownership of your User Content.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="disputes">
|
||||
<p class="section-number">17</p>
|
||||
<h2>Dispute Resolution</h2>
|
||||
<p class="legal-notice">
|
||||
PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL
|
||||
BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.
|
||||
</p>
|
||||
<h3>Informal Resolution</h3>
|
||||
<p>
|
||||
Before starting arbitration or a court proceeding, the party raising a dispute must send a
|
||||
written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a
|
||||
href="mailto:[email protected]">[email protected]</a
|
||||
>. The parties will try in good faith to resolve the dispute for at least 30 days.
|
||||
</p>
|
||||
<h3>Binding Arbitration</h3>
|
||||
<p>
|
||||
Except for disputes eligible for small-claims court and requests for injunctive relief to
|
||||
protect intellectual property or prevent unauthorized access, unresolved disputes will be
|
||||
resolved by binding individual arbitration administered by JAMS under its applicable consumer
|
||||
or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may
|
||||
take place remotely unless the arbitrator determines that an in-person hearing is necessary.
|
||||
</p>
|
||||
<h3>No Class Actions</h3>
|
||||
<p>
|
||||
Disputes must be brought only on an individual basis. Neither party may participate in a class,
|
||||
collective, consolidated, or representative action or arbitration to the extent permitted by
|
||||
law.
|
||||
</p>
|
||||
<h3>Opt Out</h3>
|
||||
<p>
|
||||
You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"
|
||||
>[email protected]</a
|
||||
> within 30 days after you first accept these Terms. Include your name, the email associated
|
||||
with your account if any, and a clear statement that you opt out of arbitration.
|
||||
</p>
|
||||
<p>
|
||||
If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the
|
||||
state and federal courts located in San Francisco County, California, and each party consents
|
||||
to those courts.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="miscellaneous">
|
||||
<p class="section-number">18</p>
|
||||
<h2>Miscellaneous</h2>
|
||||
<p>
|
||||
California law governs these Terms without regard to conflict-of-law principles, except that
|
||||
the Federal Arbitration Act governs the arbitration provisions. These Terms and documents
|
||||
incorporated by reference are the entire agreement between you and us regarding the Site and
|
||||
Services. If a provision is unenforceable, it will be modified to the minimum extent necessary
|
||||
or severed, and the remaining provisions will continue in effect.
|
||||
</p>
|
||||
<p>
|
||||
Our failure to enforce a provision is not a waiver. You may not assign these Terms without our
|
||||
written consent. We may assign them in connection with a merger, acquisition, reorganization,
|
||||
or sale of assets. We are not liable for delays or failures caused by events beyond our
|
||||
reasonable control. Headings are for convenience only, and “including” means “including without
|
||||
limitation.”
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="changes">
|
||||
<p class="section-number">19</p>
|
||||
<h2>Changes to These Terms</h2>
|
||||
<p>
|
||||
We may update these Terms from time to time. We will post updated Terms at this URL and update
|
||||
the dates above. If a change materially affects your rights, we will provide additional notice
|
||||
when reasonably practicable or as required by law. Changes apply prospectively from their
|
||||
effective date. Your continued use of the Site or Services after that date means you accept the
|
||||
updated Terms.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section id="contact">
|
||||
<p class="section-number">20</p>
|
||||
<h2>Contact Us</h2>
|
||||
<p>If you have questions about these Terms, contact us at:</p>
|
||||
<address>
|
||||
<strong>T3 Tools, Inc.</strong><br />
|
||||
2261 Market Street #5309<br />
|
||||
San Francisco, CA 94114<br />
|
||||
United States
|
||||
</address>
|
||||
<a class="contact-link" href="mailto:[email protected]">[email protected]</a>
|
||||
</section>
|
||||
</LegalPage>
|
||||
@@ -35,8 +35,8 @@ vp run ios:dev
|
||||
```
|
||||
|
||||
If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the
|
||||
reduced-capability local build. Personal Team builds omit the widget and share extensions, push
|
||||
entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and
|
||||
native Sign in with Apple entitlement; builds without this opt-in are unchanged.
|
||||
|
||||
```bash
|
||||
T3CODE_IOS_PERSONAL_TEAM=1 \
|
||||
|
||||
@@ -84,9 +84,6 @@ function resolveAppVariant(value: string | undefined): AppVariant {
|
||||
}
|
||||
|
||||
const variant = VARIANT_CONFIG[APP_VARIANT];
|
||||
const iosBundleIdentifier = isIosPersonalTeamBuild
|
||||
? personalTeamBundleIdentifier!
|
||||
: variant.iosBundleIdentifier;
|
||||
|
||||
const dmSansFonts = {
|
||||
regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",
|
||||
@@ -97,8 +94,8 @@ const dmSansFonts = {
|
||||
const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-widgets",
|
||||
{
|
||||
bundleIdentifier: `${iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${iosBundleIdentifier}`,
|
||||
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
|
||||
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
|
||||
enablePushNotifications: true,
|
||||
// Agent activity can update many times an hour; without the
|
||||
// frequent-updates entitlement iOS throttles the update budget sooner.
|
||||
@@ -114,30 +111,6 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
},
|
||||
];
|
||||
|
||||
const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
"expo-sharing",
|
||||
{
|
||||
ios: {
|
||||
// Personal Teams cannot sign App Groups or extension targets. Keep the
|
||||
// reduced-capability local build usable while release builds expose the
|
||||
// real system share target.
|
||||
enabled: !isIosPersonalTeamBuild,
|
||||
extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,
|
||||
appGroupId: `group.${iosBundleIdentifier}`,
|
||||
activationRule: {
|
||||
supportsText: true,
|
||||
supportsWebUrlWithMaxCount: 1,
|
||||
supportsImageWithMaxCount: 8,
|
||||
},
|
||||
},
|
||||
android: {
|
||||
enabled: true,
|
||||
singleShareMimeTypes: ["text/plain", "image/*"],
|
||||
multipleShareMimeTypes: ["image/*"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// These aliases match the fonts' PostScript names on iOS. Register the same
|
||||
// names on Android so React Native and the native composer use one set of
|
||||
// family names without waiting for runtime font loading.
|
||||
@@ -167,7 +140,7 @@ const config: ExpoConfig = {
|
||||
ios: {
|
||||
icon: variant.assets.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: iosBundleIdentifier,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
@@ -229,9 +202,6 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
...(isIosPersonalTeamBuild
|
||||
? [sharingPlugin]
|
||||
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
|
||||
@@ -7,7 +7,7 @@ public class T3TerminalModule: Module {
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants([
|
||||
"hardwareKeyRevision": 3,
|
||||
"hardwareKeyRevision": 2,
|
||||
])
|
||||
|
||||
View(T3TerminalView.self) {
|
||||
|
||||
@@ -119,21 +119,6 @@ private enum TerminalHardwareKeyEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalInputSequence {
|
||||
/// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
|
||||
/// which raw-mode TUIs may interpret as the literal J key.
|
||||
static let carriageReturn = "\r"
|
||||
|
||||
static func normalizingReturn(_ input: String) -> String {
|
||||
switch input {
|
||||
case "\n", "\r\n":
|
||||
return carriageReturn
|
||||
default:
|
||||
return input
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
@@ -367,9 +352,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
|
||||
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
|
||||
if !string.isEmpty {
|
||||
// Some software keyboards deliver Return through this delegate instead of
|
||||
// textFieldShouldReturn, so normalize that path too.
|
||||
emitInput(TerminalInputSequence.normalizingReturn(string))
|
||||
emitInput(string)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -377,7 +360,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
|
||||
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
emitInput(TerminalInputSequence.carriageReturn)
|
||||
emitInput("\n")
|
||||
textField.text = ""
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"dev": "expo start --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --localhost",
|
||||
"dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --clear --lan'",
|
||||
"start": "expo start",
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
@@ -91,7 +91,6 @@
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-quick-actions": "^6.0.2",
|
||||
"expo-secure-store": "~56.0.4",
|
||||
"expo-sharing": "~56.0.18",
|
||||
"expo-splash-screen": "~56.0.10",
|
||||
"expo-sqlite": "~56.0.5",
|
||||
"expo-symbols": "~56.0.6",
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
// expo-sharing intentionally uses a fixed target name and also uses that
|
||||
// internal target name as CFBundleDisplayName. Brand the extension while
|
||||
// leaving its initially-empty signing team intact: Expo uses that state to
|
||||
// select ios.appleTeamId and enable first-time profile provisioning.
|
||||
//
|
||||
// ORDERING: list this plugin BEFORE expo-sharing. Expo runs same-type mods in
|
||||
// reverse registration order, so this executes after the extension exists.
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");
|
||||
|
||||
const TARGET_NAME = "expo-sharing-extension";
|
||||
|
||||
function stripComments(section) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(section ?? {}).filter(([key]) => !key.endsWith("_comment")),
|
||||
);
|
||||
}
|
||||
|
||||
function findByName(section, name) {
|
||||
return Object.entries(stripComments(section)).find(([, value]) => value?.name === name) ?? null;
|
||||
}
|
||||
|
||||
function escapeXml(value) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function withDisplayNamePlist(config, displayName) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(cfg) => {
|
||||
const plistPath = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, "Info.plist");
|
||||
if (!fs.existsSync(plistPath)) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME}/Info.plist was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const source = fs.readFileSync(plistPath, "utf8");
|
||||
const displayNamePattern = /(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/;
|
||||
if (!displayNamePattern.test(source)) {
|
||||
throw new Error(`Could not update CFBundleDisplayName in ${plistPath}.`);
|
||||
}
|
||||
const next = source.replace(displayNamePattern, `$1${escapeXml(displayName)}$2`);
|
||||
if (next !== source) {
|
||||
fs.writeFileSync(plistPath, next);
|
||||
}
|
||||
return cfg;
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function withExtensionDisplayNameBuildSetting(config, displayName) {
|
||||
return withXcodeProject(config, (cfg) => {
|
||||
const objects = cfg.modResults.hash.project.objects;
|
||||
const targetEntry = findByName(objects.PBXNativeTarget, TARGET_NAME);
|
||||
if (!targetEntry) {
|
||||
throw new Error(
|
||||
`${TARGET_NAME} Xcode target was not generated. Register withShareExtensionDisplayName before expo-sharing.`,
|
||||
);
|
||||
}
|
||||
const target = targetEntry[1];
|
||||
const configurationList = stripComments(objects.XCConfigurationList)[
|
||||
target.buildConfigurationList
|
||||
];
|
||||
if (!configurationList) {
|
||||
throw new Error(`Could not find build configurations for ${TARGET_NAME}.`);
|
||||
}
|
||||
const buildConfigurations = stripComments(objects.XCBuildConfiguration);
|
||||
for (const reference of configurationList.buildConfigurations ?? []) {
|
||||
const buildConfiguration = buildConfigurations[reference.value];
|
||||
if (buildConfiguration?.buildSettings) {
|
||||
buildConfiguration.buildSettings.INFOPLIST_KEY_CFBundleDisplayName = `"${displayName}"`;
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = function withShareExtensionDisplayName(config) {
|
||||
const displayName = config.name;
|
||||
return withExtensionDisplayNameBuildSetting(
|
||||
withDisplayNamePlist(config, displayName),
|
||||
displayName,
|
||||
);
|
||||
};
|
||||
+5
-11
@@ -11,7 +11,6 @@ import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigati
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
@@ -27,10 +26,7 @@ const appLinking = {
|
||||
// <scheme>://expo-development-client/?url=<packager> — that URL addresses
|
||||
// the launcher, not app navigation. Without this filter it falls through
|
||||
// to the NotFound wildcard route on every dev launch.
|
||||
// expo-sharing uses a private lifecycle URL only to wake the app. The
|
||||
// persisted share inbox below owns navigation once the payload is durable.
|
||||
filter: (url: string) =>
|
||||
!url.includes("expo-development-client") && !url.includes("://expo-sharing"),
|
||||
filter: (url: string) => !url.includes("expo-development-client"),
|
||||
};
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
@@ -62,12 +58,10 @@ export default function App() {
|
||||
the system is in dark mode. */}
|
||||
{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}
|
||||
<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>
|
||||
<IncomingShareProvider>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
</IncomingShareProvider>
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
<ConfirmDialogHost />
|
||||
</BlurTargetView>
|
||||
{/* Anchored-menu overlays render here — in-window, so the
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
createNativeStackScreen,
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
@@ -45,19 +44,9 @@ import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppea
|
||||
import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import {
|
||||
SettingsLegalDocumentCloseHeaderButton,
|
||||
SettingsLegalDocumentExternalHeaderButton,
|
||||
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
|
||||
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
|
||||
import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
|
||||
import {
|
||||
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
transitionIncomingSharePresentation,
|
||||
} from "./features/sharing/incoming-share-presentation";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
@@ -117,14 +106,6 @@ const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SHEET_SOLID_HEADER_OPTIONS,
|
||||
headerBackVisible: false,
|
||||
headerLeft: SettingsLegalDocumentCloseHeaderButton,
|
||||
headerRight: () => <SettingsLegalDocumentExternalHeaderButton />,
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
@@ -258,7 +239,6 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"GitConfirm",
|
||||
"GitOverview",
|
||||
"NewTaskSheet",
|
||||
"SettingsLegal",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
]);
|
||||
@@ -281,30 +261,12 @@ function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const { pendingShare } = useIncomingShare();
|
||||
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
|
||||
useAppShortcuts(props.state);
|
||||
useEffect(() => {
|
||||
const topRouteName = props.state.routes[props.state.index]?.name;
|
||||
const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
|
||||
isShareSheetPresented: topRouteName === "NewTaskSheet",
|
||||
pendingShareId: pendingShare?.id ?? null,
|
||||
});
|
||||
sharePresentationRef.current = transition.state;
|
||||
if (!transition.shareIdToPresent) {
|
||||
return;
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTask",
|
||||
params: { incomingShareId: transition.shareIdToPresent },
|
||||
});
|
||||
}, [navigation, pendingShare, props.state]);
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
@@ -474,14 +436,6 @@ export const RootStack = createNativeStackNavigator({
|
||||
}),
|
||||
},
|
||||
}),
|
||||
SettingsLegal: createNativeStackScreen({
|
||||
screen: SettingsLegalRouteScreen,
|
||||
linking: "settings/legal",
|
||||
options: {
|
||||
...LEGAL_DOCUMENT_HEADER_OPTIONS,
|
||||
title: "Legal",
|
||||
},
|
||||
}),
|
||||
ConnectOnboarding: createNativeStackScreen({
|
||||
screen: ConnectOnboardingRouteScreen,
|
||||
linking: "connect-onboarding",
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { NativeReviewDiffRow } from "./nativeReviewDiffSurface";
|
||||
import type { NativeReviewDiffFile } from "./nativeReviewDiffTypes";
|
||||
import { highlightNativeReviewDiffVisibleRows } from "./nativeReviewDiffHighlighter";
|
||||
|
||||
const TYPESCRIPT_FILE: NativeReviewDiffFile = {
|
||||
id: "file-1",
|
||||
path: "example.ts",
|
||||
language: "typescript",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
};
|
||||
|
||||
function makeLine(
|
||||
input: Pick<NativeReviewDiffRow, "id" | "content" | "change" | "oldLineNumber" | "newLineNumber">,
|
||||
): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "line",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHunk(id: string): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "hunk",
|
||||
id,
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
text: "@@",
|
||||
};
|
||||
}
|
||||
|
||||
function highlight(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
alreadyHighlightedRowIds?: ReadonlySet<string>,
|
||||
) {
|
||||
return highlightNativeReviewDiffVisibleRows({
|
||||
rows,
|
||||
files: [TYPESCRIPT_FILE],
|
||||
scheme: "dark",
|
||||
engine: "javascript",
|
||||
firstRowIndex: 0,
|
||||
lastRowIndex: rows.length - 1,
|
||||
overscanRows: 0,
|
||||
maxRows: 100,
|
||||
alreadyHighlightedRowIds,
|
||||
});
|
||||
}
|
||||
|
||||
describe("highlightNativeReviewDiffVisibleRows", () => {
|
||||
it("does not carry grammar state across hunk boundaries", async () => {
|
||||
const exportRow = makeLine({
|
||||
id: "export-row",
|
||||
content: "export async function run() {}",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 100,
|
||||
});
|
||||
const rows = [
|
||||
makeHunk("hunk-1"),
|
||||
makeLine({
|
||||
id: "import-open",
|
||||
content: "import {",
|
||||
change: "context",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "import-entry",
|
||||
content: " Model,",
|
||||
change: "context",
|
||||
oldLineNumber: 2,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
makeHunk("hunk-2"),
|
||||
exportRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([makeHunk("standalone-hunk"), exportRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[exportRow.id]).toEqual(standalone.tokensByRowId[exportRow.id]);
|
||||
});
|
||||
|
||||
it("keeps grammar state across inline comment rows", async () => {
|
||||
const openingRow = makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const closingRow = makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
});
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const commentRow: NativeReviewDiffRow = {
|
||||
kind: "comment",
|
||||
id: "comment-1",
|
||||
fileId: TYPESCRIPT_FILE.id,
|
||||
commentText: "Review note",
|
||||
};
|
||||
|
||||
const [withComment, contiguous] = await Promise.all([
|
||||
highlight([openingRow, commentRow, closingRow, trailingRow]),
|
||||
highlight([openingRow, closingRow, trailingRow]),
|
||||
]);
|
||||
|
||||
expect(withComment.tokensByRowId).toEqual(contiguous.tokensByRowId);
|
||||
});
|
||||
|
||||
it("does not join unhighlighted rows across cached gaps", async () => {
|
||||
const trailingRow = makeLine({
|
||||
id: "trailing-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 3,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "template-open",
|
||||
content: "const message = `open",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
}),
|
||||
makeLine({
|
||||
id: "template-close",
|
||||
content: "closed`;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 2,
|
||||
}),
|
||||
trailingRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows, new Set(["template-close"])),
|
||||
highlight([trailingRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[trailingRow.id]).toEqual(
|
||||
standalone.tokensByRowId[trailingRow.id],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps deletion grammar state out of addition rows", async () => {
|
||||
const additionRow = makeLine({
|
||||
id: "addition-row",
|
||||
content: "export const answer = 42;",
|
||||
change: "add",
|
||||
oldLineNumber: null,
|
||||
newLineNumber: 1,
|
||||
});
|
||||
const rows = [
|
||||
makeLine({
|
||||
id: "deletion-row",
|
||||
content: "const removed = `open",
|
||||
change: "delete",
|
||||
oldLineNumber: 1,
|
||||
newLineNumber: null,
|
||||
}),
|
||||
additionRow,
|
||||
];
|
||||
|
||||
const [highlighted, standalone] = await Promise.all([
|
||||
highlight(rows),
|
||||
highlight([additionRow]),
|
||||
]);
|
||||
|
||||
expect(highlighted.tokensByRowId[additionRow.id]).toEqual(
|
||||
standalone.tokensByRowId[additionRow.id],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -56,11 +56,6 @@ interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
|
||||
readonly content: string;
|
||||
}
|
||||
|
||||
interface IndexedNativeReviewDiffLineRow {
|
||||
readonly row: NativeReviewDiffLineRow;
|
||||
readonly rowIndex: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffTokenChunk {
|
||||
readonly chunkIndex: number;
|
||||
readonly fileId: string;
|
||||
@@ -313,58 +308,6 @@ function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDi
|
||||
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function hasConsecutiveLineNumbers(
|
||||
previous: number | null | undefined,
|
||||
next: number | null | undefined,
|
||||
): boolean {
|
||||
return typeof previous === "number" && typeof next === "number" && next === previous + 1;
|
||||
}
|
||||
|
||||
function hasOnlyCommentRowsBetween(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
previousRowIndex: number,
|
||||
nextRowIndex: number,
|
||||
): boolean {
|
||||
for (let rowIndex = previousRowIndex + 1; rowIndex < nextRowIndex; rowIndex += 1) {
|
||||
if (rows[rowIndex]?.kind !== "comment") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canShareGrammarContext(
|
||||
previous: IndexedNativeReviewDiffLineRow,
|
||||
next: IndexedNativeReviewDiffLineRow,
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
): boolean {
|
||||
if (
|
||||
next.row.fileId !== previous.row.fileId ||
|
||||
!hasOnlyCommentRowsBetween(rows, previous.rowIndex, next.rowIndex)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (previous.row.change === "delete" || next.row.change === "delete") {
|
||||
return (
|
||||
previous.row.change !== "add" &&
|
||||
next.row.change !== "add" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
if (previous.row.change === "add" || next.row.change === "add") {
|
||||
return hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber);
|
||||
}
|
||||
|
||||
return (
|
||||
previous.row.change === "context" &&
|
||||
next.row.change === "context" &&
|
||||
hasConsecutiveLineNumbers(previous.row.oldLineNumber, next.row.oldLineNumber) &&
|
||||
hasConsecutiveLineNumbers(previous.row.newLineNumber, next.row.newLineNumber)
|
||||
);
|
||||
}
|
||||
|
||||
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
|
||||
for (const row of rows) {
|
||||
@@ -417,7 +360,7 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
|
||||
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
|
||||
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
|
||||
const selectedRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
const selectedRows: NativeReviewDiffLineRow[] = [];
|
||||
|
||||
for (
|
||||
let rowIndex = startIndex;
|
||||
@@ -431,12 +374,12 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
!input.alreadyHighlightedRowIds?.has(row.id) &&
|
||||
fileMap.has(row.fileId)
|
||||
) {
|
||||
selectedRows.push({ row, rowIndex });
|
||||
selectedRows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
|
||||
let segmentRows: IndexedNativeReviewDiffLineRow[] = [];
|
||||
let segmentRows: NativeReviewDiffLineRow[] = [];
|
||||
let segmentFile: NativeReviewDiffFile | undefined;
|
||||
|
||||
const flushSegment = () => {
|
||||
@@ -446,34 +389,27 @@ export async function highlightNativeReviewDiffVisibleRows(
|
||||
return;
|
||||
}
|
||||
|
||||
const code = segmentRows.map(({ row }) => row.content).join("\n");
|
||||
const code = segmentRows.map((row) => row.content).join("\n");
|
||||
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
|
||||
segmentRows.forEach(({ row }, rowIndex) => {
|
||||
segmentRows.forEach((row, rowIndex) => {
|
||||
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
|
||||
});
|
||||
segmentRows = [];
|
||||
segmentFile = undefined;
|
||||
};
|
||||
|
||||
for (const selectedRow of selectedRows) {
|
||||
const { row } = selectedRow;
|
||||
for (const row of selectedRows) {
|
||||
const file = fileMap.get(row.fileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const previousRow = segmentRows.at(-1);
|
||||
if (
|
||||
segmentFile &&
|
||||
(segmentFile.id !== file.id ||
|
||||
(previousRow !== undefined &&
|
||||
!canShareGrammarContext(previousRow, selectedRow, input.rows)))
|
||||
) {
|
||||
if (segmentFile && segmentFile.id !== file.id) {
|
||||
flushSegment();
|
||||
}
|
||||
|
||||
segmentFile = file;
|
||||
segmentRows.push(selectedRow);
|
||||
segmentRows.push(row);
|
||||
}
|
||||
flushSegment();
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -41,6 +41,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { SettingsLegalDocumentRouteScreen } from "./components/SettingsLegalDocumentRouteScreen";
|
||||
import { LEGAL_URL } from "./lib/legal-document-url";
|
||||
|
||||
export function SettingsLegalRouteScreen() {
|
||||
return <SettingsLegalDocumentRouteScreen documentName="Legal" documentUrl={LEGAL_URL} />;
|
||||
}
|
||||
@@ -537,7 +537,6 @@ function AppSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
import { type NavigationProp, type ParamListBase, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useLayoutEffect, useState } from "react";
|
||||
import { ActivityIndicator, Linking, Pressable, View } from "react-native";
|
||||
import { WebView } from "react-native-webview";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { LoadingStrip } from "../../../components/LoadingStrip";
|
||||
import { SymbolView } from "../../../components/AppSymbol";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url";
|
||||
|
||||
export function SettingsLegalDocumentCloseHeaderButton() {
|
||||
const navigation = useNavigation();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel="Close legal document"
|
||||
accessibilityRole="button"
|
||||
hitSlop={12}
|
||||
onPress={() => navigation.goBack()}
|
||||
className="p-2 active:opacity-60"
|
||||
>
|
||||
<SymbolView
|
||||
name="xmark"
|
||||
size={18}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsLegalDocumentExternalHeaderButton({
|
||||
externalUrl = LEGAL_URL,
|
||||
}: {
|
||||
readonly externalUrl?: string;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const safeExternalUrl = isLegalDocumentUrl(externalUrl) ? externalUrl : LEGAL_URL;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel="Open legal documents in external browser"
|
||||
accessibilityRole="button"
|
||||
hitSlop={12}
|
||||
onPress={() => void Linking.openURL(safeExternalUrl).catch(() => undefined)}
|
||||
className="p-2 active:opacity-60"
|
||||
>
|
||||
<SymbolView
|
||||
name="safari"
|
||||
size={19}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
interface SettingsLegalDocumentRouteScreenProps {
|
||||
readonly documentName: string;
|
||||
readonly documentUrl: string;
|
||||
}
|
||||
|
||||
export function SettingsLegalDocumentRouteScreen({
|
||||
documentName,
|
||||
documentUrl,
|
||||
}: SettingsLegalDocumentRouteScreenProps) {
|
||||
const navigation = useNavigation<NavigationProp<ParamListBase>>();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [loadProgress, setLoadProgress] = useState(0);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [externalUrl, setExternalUrl] = useState(documentUrl);
|
||||
const renderExternalHeaderButton = useCallback(
|
||||
() => <SettingsLegalDocumentExternalHeaderButton externalUrl={externalUrl} />,
|
||||
[externalUrl],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
navigation.setOptions({
|
||||
headerRight: renderExternalHeaderButton,
|
||||
});
|
||||
}, [navigation, renderExternalHeaderButton]);
|
||||
|
||||
const openExternalUrl = useCallback((url: string) => {
|
||||
void Linking.openURL(url).catch(() => undefined);
|
||||
}, []);
|
||||
if (loadError) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-4 bg-sheet px-8">
|
||||
<SymbolView
|
||||
name="exclamationmark.triangle"
|
||||
size={32}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<View className="items-center gap-2">
|
||||
<Text className="text-center font-t3-bold text-lg text-foreground">
|
||||
Couldn't load the {documentName.toLowerCase()}
|
||||
</Text>
|
||||
<Text selectable className="text-center text-sm leading-normal text-foreground-muted">
|
||||
{loadError}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="w-full max-w-[320px] gap-2">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => {
|
||||
setLoadError(null);
|
||||
setReloadKey((value) => value + 1);
|
||||
}}
|
||||
className="items-center rounded-xl bg-foreground px-4 py-3 active:opacity-80"
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-sheet">Try Again</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
onPress={() => openExternalUrl(documentUrl)}
|
||||
className="items-center rounded-xl px-4 py-3 active:bg-foreground/5"
|
||||
>
|
||||
<Text className="font-t3-medium text-base text-foreground-muted">Open in Browser</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-sheet">
|
||||
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
|
||||
<WebView
|
||||
key={reloadKey}
|
||||
source={{ uri: documentUrl }}
|
||||
originWhitelist={["http://*", "https://*", "mailto:*"]}
|
||||
cacheEnabled={false}
|
||||
cacheMode="LOAD_NO_CACHE"
|
||||
allowsBackForwardNavigationGestures
|
||||
domStorageEnabled={false}
|
||||
incognito
|
||||
javaScriptEnabled={false}
|
||||
setSupportMultipleWindows={false}
|
||||
sharedCookiesEnabled={false}
|
||||
thirdPartyCookiesEnabled={false}
|
||||
startInLoadingState
|
||||
onShouldStartLoadWithRequest={(request) => {
|
||||
if (isLegalDocumentUrl(request.url)) return true;
|
||||
|
||||
openExternalUrl(request.url);
|
||||
return false;
|
||||
}}
|
||||
onLoadProgress={(event) => {
|
||||
setLoadProgress(event.nativeEvent.progress);
|
||||
}}
|
||||
onLoadStart={() => {
|
||||
setLoadProgress(0.05);
|
||||
setLoadError(null);
|
||||
}}
|
||||
onLoadEnd={(event) => {
|
||||
if (isLegalDocumentUrl(event.nativeEvent.url)) {
|
||||
setExternalUrl(event.nativeEvent.url);
|
||||
}
|
||||
setLoadProgress(0);
|
||||
}}
|
||||
onError={(event) => {
|
||||
setLoadProgress(0);
|
||||
setLoadError(event.nativeEvent.description || "The page could not be loaded.");
|
||||
}}
|
||||
onHttpError={(event) => {
|
||||
if (!isLegalDocumentUrl(event.nativeEvent.url)) return;
|
||||
setLoadProgress(0);
|
||||
setLoadError(`The server returned status ${event.nativeEvent.statusCode}.`);
|
||||
}}
|
||||
renderLoading={() => (
|
||||
<View className="absolute inset-0 items-center justify-center bg-sheet">
|
||||
<ActivityIndicator />
|
||||
</View>
|
||||
)}
|
||||
style={{ flex: 1, backgroundColor: "transparent" }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { SymbolView } from "../../../components/AppSymbol";
|
||||
|
||||
import { AppText as Text } from "../../../components/AppText";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import type { SettingsLegalDocumentTarget, SettingsSheetTarget } from "./settings-sheet-targets";
|
||||
import type { SettingsSheetTarget } from "./settings-sheet-targets";
|
||||
|
||||
type SymbolName = ComponentProps<typeof SymbolView>["name"];
|
||||
|
||||
@@ -16,7 +16,6 @@ export function SettingsRow(props: {
|
||||
readonly label: string;
|
||||
readonly value?: string;
|
||||
readonly target?: SettingsSheetTarget;
|
||||
readonly fullScreenTarget?: SettingsLegalDocumentTarget;
|
||||
readonly onPress?: () => void;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
@@ -73,20 +72,6 @@ export function SettingsRow(props: {
|
||||
);
|
||||
}
|
||||
|
||||
const fullScreenTarget = props.fullScreenTarget;
|
||||
if (fullScreenTarget) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.label}
|
||||
accessibilityRole="button"
|
||||
disabled={props.disabled}
|
||||
onPress={() => navigation.navigate(fullScreenTarget)}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Pressable accessibilityRole="button" disabled={props.disabled} onPress={props.onPress}>
|
||||
{content}
|
||||
|
||||
@@ -3,5 +3,3 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -1,24 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isLegalDocumentUrl } from "./legal-document-url";
|
||||
|
||||
describe("isLegalDocumentUrl", () => {
|
||||
it.each([
|
||||
"https://t3.codes/legal",
|
||||
"https://t3.codes/legal/",
|
||||
"https://t3.codes/privacy-policy?source=app",
|
||||
"https://t3.codes/terms-of-service#updates",
|
||||
"https://t3.codes/security-policy",
|
||||
])("allows a configured legal document: %s", (url) => {
|
||||
expect(isLegalDocumentUrl(url)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://t3.codes/download",
|
||||
"https://example.com/legal",
|
||||
"javascript:alert(1)",
|
||||
"not-a-url",
|
||||
])("rejects a URL outside the legal-document allowlist: %s", (url) => {
|
||||
expect(isLegalDocumentUrl(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
const DEFAULT_MARKETING_SITE_URL = "https://t3.codes";
|
||||
|
||||
function resolveMarketingSiteUrl(override: string | undefined): URL {
|
||||
try {
|
||||
const url = new URL(override?.trim() || DEFAULT_MARKETING_SITE_URL);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
||||
return new URL(DEFAULT_MARKETING_SITE_URL);
|
||||
}
|
||||
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, "")}/`;
|
||||
return url;
|
||||
} catch {
|
||||
return new URL(DEFAULT_MARKETING_SITE_URL);
|
||||
}
|
||||
}
|
||||
|
||||
const MARKETING_SITE_URL = resolveMarketingSiteUrl(process.env.EXPO_PUBLIC_MARKETING_SITE_URL);
|
||||
|
||||
function marketingSiteDocumentUrl(path: string): string {
|
||||
return new URL(path, MARKETING_SITE_URL).toString();
|
||||
}
|
||||
|
||||
export const PRIVACY_POLICY_URL = marketingSiteDocumentUrl("privacy-policy");
|
||||
export const SECURITY_POLICY_URL = marketingSiteDocumentUrl("security-policy");
|
||||
export const TERMS_OF_SERVICE_URL = marketingSiteDocumentUrl("terms-of-service");
|
||||
export const LEGAL_URL = marketingSiteDocumentUrl("legal");
|
||||
|
||||
export const ALLOWED_LEGAL_DOCUMENT_URLS = [
|
||||
LEGAL_URL,
|
||||
PRIVACY_POLICY_URL,
|
||||
TERMS_OF_SERVICE_URL,
|
||||
SECURITY_POLICY_URL,
|
||||
] as const;
|
||||
|
||||
function webDocumentIdentity(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
|
||||
const pathname = url.pathname.replace(/\/+$/, "") || "/";
|
||||
return `${url.origin}${pathname}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ALLOWED_LEGAL_DOCUMENT_IDENTITIES = new Set(
|
||||
ALLOWED_LEGAL_DOCUMENT_URLS.map(webDocumentIdentity).filter(
|
||||
(value): value is string => value !== null,
|
||||
),
|
||||
);
|
||||
|
||||
export function isLegalDocumentUrl(value: string): boolean {
|
||||
const identity = webDocumentIdentity(value);
|
||||
return identity !== null && ALLOWED_LEGAL_DOCUMENT_IDENTITIES.has(identity);
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
import Constants from "expo-constants";
|
||||
import * as Crypto from "expo-crypto";
|
||||
import {
|
||||
clearSharedPayloads,
|
||||
getResolvedSharedPayloadsAsync,
|
||||
getSharedPayloads,
|
||||
type ResolvedSharePayload,
|
||||
type SharePayload,
|
||||
} from "expo-sharing";
|
||||
import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { Alert, AppState, Platform } from "react-native";
|
||||
|
||||
import {
|
||||
buildIncomingShareDraft,
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
import { IncomingShareInbox } from "./incoming-share-inbox";
|
||||
import {
|
||||
loadIncomingShareDrafts,
|
||||
removeIncomingShareDraft,
|
||||
writeIncomingShareDraft,
|
||||
} from "./incoming-share-storage";
|
||||
|
||||
type IncomingShareContextValue = {
|
||||
readonly pendingShare: IncomingShareDraft | null;
|
||||
readonly isLoading: boolean;
|
||||
readonly error: Error | null;
|
||||
readonly getShare: (shareId: string) => IncomingShareDraft | null;
|
||||
readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
|
||||
readonly releaseShareReservation: (
|
||||
shareId: string,
|
||||
expectedDestination: IncomingShareDestination,
|
||||
) => Promise<void>;
|
||||
readonly consumeShare: (shareId: string) => Promise<void>;
|
||||
readonly refresh: () => Promise<void>;
|
||||
};
|
||||
|
||||
const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
|
||||
|
||||
function receiveSharingEnabled(): boolean {
|
||||
if (Platform.OS === "android") {
|
||||
return true;
|
||||
}
|
||||
if (Platform.OS !== "ios") {
|
||||
return false;
|
||||
}
|
||||
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
|
||||
}
|
||||
|
||||
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
|
||||
try {
|
||||
return await getResolvedSharedPayloadsAsync();
|
||||
} catch (error) {
|
||||
// iOS already gives the containing app a copied file:// URL, so raw
|
||||
// payloads remain usable. Android normally resolves content:// into a
|
||||
// private cache file; its modern File API can still read the raw URI when
|
||||
// resolution fails.
|
||||
console.warn("[incoming-share] could not resolve shared file metadata", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
|
||||
const fingerprint = JSON.stringify(
|
||||
payloads.map((payload) => ({
|
||||
shareType: payload.shareType,
|
||||
mimeType: payload.mimeType ?? null,
|
||||
value: payload.value,
|
||||
})),
|
||||
);
|
||||
const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
|
||||
return `share-${digest}`;
|
||||
}
|
||||
|
||||
async function readBase64(uri: string): Promise<string> {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(uri).base64();
|
||||
}
|
||||
|
||||
async function removeOwnedFile(uri: string): Promise<void> {
|
||||
if (!uri.startsWith("file:")) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const file = new File(uri);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[incoming-share] could not remove temporary shared file", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeReplayedImagePayloadFiles(
|
||||
payloads: ReadonlyArray<SharePayload>,
|
||||
): Promise<void> {
|
||||
const uris = new Set<string>();
|
||||
for (const payload of payloads) {
|
||||
if (payload.shareType === "image") {
|
||||
uris.add(payload.value);
|
||||
}
|
||||
}
|
||||
if (uris.size === 0) {
|
||||
return;
|
||||
}
|
||||
const resolvedPayloads = await resolvedPayloadsForImages();
|
||||
for (const payload of resolvedPayloads) {
|
||||
if (payload.shareType === "image" && payload.contentUri) {
|
||||
uris.add(payload.contentUri);
|
||||
}
|
||||
}
|
||||
await Promise.all([...uris].map(removeOwnedFile));
|
||||
}
|
||||
|
||||
// Keep one operation queue across provider remounts (including development
|
||||
// Strict Mode remounts) so two app lifecycle notifications cannot ingest the
|
||||
// same native handoff independently.
|
||||
const incomingShareInbox = new IncomingShareInbox({
|
||||
loadDrafts: loadIncomingShareDrafts,
|
||||
writeDraft: writeIncomingShareDraft,
|
||||
removeDraft: removeIncomingShareDraft,
|
||||
getPayloads: getSharedPayloads,
|
||||
clearPayloads: clearSharedPayloads,
|
||||
buildDraft: async ({ payloads, id, createdAt }) => {
|
||||
const cleanupUris = new Set<string>();
|
||||
const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")
|
||||
? await resolvedPayloadsForImages()
|
||||
: [];
|
||||
const draft = await buildIncomingShareDraft({
|
||||
payloads,
|
||||
resolvedPayloads,
|
||||
fileReader: {
|
||||
readBase64,
|
||||
removeOwnedFile: (uri) => {
|
||||
cleanupUris.add(uri);
|
||||
},
|
||||
},
|
||||
id,
|
||||
createdAt,
|
||||
});
|
||||
return {
|
||||
draft,
|
||||
cleanup: async () => {
|
||||
await Promise.all([...cleanupUris].map(removeOwnedFile));
|
||||
},
|
||||
};
|
||||
},
|
||||
cleanupReplayedPayloads: removeReplayedImagePayloadFiles,
|
||||
idForPayloads: incomingShareIdForPayloads,
|
||||
now: () => new Date().toISOString(),
|
||||
onClearError: (error) => {
|
||||
console.warn("[incoming-share] could not acknowledge native payload", error);
|
||||
},
|
||||
onCleanupError: (error) => {
|
||||
console.warn("[incoming-share] could not remove temporary shared file", error);
|
||||
},
|
||||
});
|
||||
|
||||
export function IncomingShareProvider(props: React.PropsWithChildren) {
|
||||
const enabled = receiveSharingEnabled();
|
||||
const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const refreshPromiseRef = useRef<Promise<void> | null>(null);
|
||||
const mountedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (refreshPromiseRef.current) {
|
||||
return refreshPromiseRef.current;
|
||||
}
|
||||
|
||||
const operation = (async () => {
|
||||
try {
|
||||
const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
setError(null);
|
||||
}
|
||||
} catch (cause) {
|
||||
const persisted = await incomingShareInbox
|
||||
.refresh({ ingestNative: false })
|
||||
.catch(() => null);
|
||||
if (mountedRef.current) {
|
||||
if (persisted) {
|
||||
setDrafts(persisted);
|
||||
}
|
||||
setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
|
||||
}
|
||||
}
|
||||
})().finally(() => {
|
||||
refreshPromiseRef.current = null;
|
||||
});
|
||||
|
||||
refreshPromiseRef.current = operation;
|
||||
return operation;
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh().finally(() => {
|
||||
if (mountedRef.current) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
});
|
||||
}, [refresh]);
|
||||
|
||||
const refreshOnAppActive = useEffectEvent(() => {
|
||||
void refresh();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
refreshOnAppActive();
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
Alert.alert("Could not import shared content", error.message, [
|
||||
{ text: "Dismiss", style: "cancel", onPress: () => setError(null) },
|
||||
{
|
||||
text: "Retry",
|
||||
onPress: () => {
|
||||
setError(null);
|
||||
void refresh();
|
||||
},
|
||||
},
|
||||
]);
|
||||
}, [error, refresh]);
|
||||
|
||||
const consumeShare = useCallback(async (shareId: string) => {
|
||||
const snapshot = await incomingShareInbox.consume(shareId);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
}, []);
|
||||
const reserveShare = useCallback(
|
||||
async (shareId: string, destination: IncomingShareDestination) => {
|
||||
const snapshot = await incomingShareInbox.reserve(shareId, destination);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const releaseShareReservation = useCallback(
|
||||
async (shareId: string, expectedDestination: IncomingShareDestination) => {
|
||||
const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
|
||||
if (mountedRef.current) {
|
||||
setDrafts(snapshot);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const getShare = useCallback(
|
||||
(shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
|
||||
[drafts],
|
||||
);
|
||||
|
||||
const value = useMemo<IncomingShareContextValue>(
|
||||
() => ({
|
||||
pendingShare: drafts[0] ?? null,
|
||||
isLoading,
|
||||
error,
|
||||
getShare,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
consumeShare,
|
||||
refresh,
|
||||
}),
|
||||
[
|
||||
consumeShare,
|
||||
drafts,
|
||||
error,
|
||||
getShare,
|
||||
isLoading,
|
||||
refresh,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useIncomingShare(): IncomingShareContextValue {
|
||||
const value = React.use(IncomingShareContext);
|
||||
if (value === null) {
|
||||
throw new Error("useIncomingShare must be used within IncomingShareProvider.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
import type { IncomingShareDraft } from "./incoming-share-model";
|
||||
import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox";
|
||||
|
||||
const PAYLOAD: SharePayload = {
|
||||
shareType: "text",
|
||||
mimeType: "text/plain",
|
||||
value: "Fix this",
|
||||
};
|
||||
|
||||
function draft(id: string, createdAt = "2026-07-16T08:00:00.000Z"): IncomingShareDraft {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
createdAt,
|
||||
text: PAYLOAD.value,
|
||||
attachments: [],
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((next) => {
|
||||
resolve = next;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {}) {
|
||||
const persisted = new Map<string, IncomingShareDraft>();
|
||||
let payloads: ReadonlyArray<SharePayload> = [PAYLOAD];
|
||||
const dependencies: IncomingShareInboxDependencies = {
|
||||
loadDrafts: async () => [...persisted.values()],
|
||||
writeDraft: async (value) => {
|
||||
persisted.set(value.id, value);
|
||||
},
|
||||
removeDraft: async (shareId) => {
|
||||
persisted.delete(shareId);
|
||||
},
|
||||
getPayloads: () => payloads,
|
||||
clearPayloads: () => {
|
||||
payloads = [];
|
||||
},
|
||||
buildDraft: async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup: async () => undefined,
|
||||
}),
|
||||
idForPayloads: async () => "share-stable",
|
||||
now: () => "2026-07-16T08:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
return { inbox: new IncomingShareInbox(dependencies), persisted };
|
||||
}
|
||||
|
||||
describe("IncomingShareInbox", () => {
|
||||
it("coalesces a replay of an already-persisted native handoff", async () => {
|
||||
const buildDraft = vi.fn(async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup: async () => undefined,
|
||||
}));
|
||||
const cleanupReplayedPayloads = vi.fn(async () => undefined);
|
||||
const { inbox, persisted } = createHarness({ buildDraft, cleanupReplayedPayloads });
|
||||
persisted.set("share-stable", draft("share-stable"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: true })).resolves.toEqual([draft("share-stable")]);
|
||||
expect(buildDraft).not.toHaveBeenCalled();
|
||||
expect(cleanupReplayedPayloads).toHaveBeenCalledWith([PAYLOAD]);
|
||||
});
|
||||
|
||||
it("serializes concurrent refreshes so one native payload creates one inbox item", async () => {
|
||||
const building = deferred();
|
||||
const buildDraft = vi.fn(async ({ id, createdAt }) => {
|
||||
await building.promise;
|
||||
return { draft: draft(id, createdAt), cleanup: async () => undefined };
|
||||
});
|
||||
const { inbox } = createHarness({ buildDraft });
|
||||
|
||||
const first = inbox.refresh({ ingestNative: true });
|
||||
const second = inbox.refresh({ ingestNative: true });
|
||||
building.resolve();
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
[draft("share-stable")],
|
||||
[draft("share-stable")],
|
||||
]);
|
||||
expect(buildDraft).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("orders consumption after an in-flight refresh without restoring stale state", async () => {
|
||||
const building = deferred();
|
||||
const { inbox, persisted } = createHarness({
|
||||
buildDraft: async ({ id, createdAt }) => {
|
||||
await building.promise;
|
||||
return { draft: draft(id, createdAt), cleanup: async () => undefined };
|
||||
},
|
||||
});
|
||||
|
||||
const refresh = inbox.refresh({ ingestNative: true });
|
||||
const consume = inbox.consume("share-stable");
|
||||
building.resolve();
|
||||
|
||||
await expect(refresh).resolves.toEqual([draft("share-stable")]);
|
||||
await expect(consume).resolves.toEqual([]);
|
||||
expect([...persisted.values()]).toEqual([]);
|
||||
});
|
||||
|
||||
it("consumes only the addressed share when another share has identical content", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-first", draft("share-first", "2026-07-16T07:59:00.000Z"));
|
||||
persisted.set("share-second", draft("share-second"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
|
||||
draft("share-second"),
|
||||
draft("share-first", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
await expect(inbox.consume("share-second")).resolves.toEqual([
|
||||
draft("share-first", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
expect([...persisted.values()]).toEqual([draft("share-first", "2026-07-16T07:59:00.000Z")]);
|
||||
});
|
||||
|
||||
it("keeps content-identical shares addressable by their own ids", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-open-flow", draft("share-open-flow", "2026-07-16T07:59:00.000Z"));
|
||||
persisted.set("share-newer", draft("share-newer"));
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([
|
||||
draft("share-newer"),
|
||||
draft("share-open-flow", "2026-07-16T07:59:00.000Z"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not acknowledge a supported payload when its durable write fails", async () => {
|
||||
const clearPayloads = vi.fn();
|
||||
const cleanup = vi.fn(async () => undefined);
|
||||
const { inbox } = createHarness({
|
||||
clearPayloads,
|
||||
buildDraft: async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup,
|
||||
}),
|
||||
writeDraft: async () => {
|
||||
throw new Error("disk full");
|
||||
},
|
||||
});
|
||||
|
||||
await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full");
|
||||
expect(clearPayloads).not.toHaveBeenCalled();
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("durably reserves a share for one project before draft import", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", draft("share-stable"));
|
||||
const destination = { environmentId: "environment-1", projectId: "project-1" };
|
||||
|
||||
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
|
||||
{ ...draft("share-stable"), destination },
|
||||
]);
|
||||
expect(persisted.get("share-stable")?.destination).toEqual(destination);
|
||||
await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([
|
||||
{ ...draft("share-stable"), destination },
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects moving a reserved share to another project", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", {
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-1", projectId: "project-1" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
inbox.reserve("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-2",
|
||||
}),
|
||||
).rejects.toThrow("already reserved");
|
||||
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-1");
|
||||
});
|
||||
|
||||
it("conditionally releases a reservation when its project is unavailable", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
const destination = { environmentId: "environment-1", projectId: "project-1" };
|
||||
persisted.set("share-stable", { ...draft("share-stable"), destination });
|
||||
|
||||
await expect(inbox.releaseReservation("share-stable", destination)).resolves.toEqual([
|
||||
draft("share-stable"),
|
||||
]);
|
||||
expect(persisted.get("share-stable")?.destination).toBeUndefined();
|
||||
|
||||
await expect(
|
||||
inbox.reserve("share-stable", {
|
||||
environmentId: "environment-2",
|
||||
projectId: "project-2",
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-2", projectId: "project-2" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not release a reservation that changed concurrently", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-stable", {
|
||||
...draft("share-stable"),
|
||||
destination: { environmentId: "environment-2", projectId: "project-2" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
inbox.releaseReservation("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-1",
|
||||
}),
|
||||
).rejects.toThrow("reservation changed");
|
||||
expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-2");
|
||||
});
|
||||
|
||||
it("treats an already-removed share as an already-released reservation", async () => {
|
||||
const { inbox, persisted } = createHarness();
|
||||
persisted.set("share-other", draft("share-other"));
|
||||
|
||||
await expect(
|
||||
inbox.releaseReservation("share-stable", {
|
||||
environmentId: "environment-1",
|
||||
projectId: "project-1",
|
||||
}),
|
||||
).resolves.toEqual([draft("share-other")]);
|
||||
expect([...persisted.values()]).toEqual([draft("share-other")]);
|
||||
});
|
||||
});
|
||||
@@ -1,193 +0,0 @@
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";
|
||||
import {
|
||||
hasIncomingShareContent,
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
|
||||
export interface IncomingShareInboxDependencies {
|
||||
readonly loadDrafts: () => Promise<ReadonlyArray<IncomingShareDraft>>;
|
||||
readonly writeDraft: (draft: IncomingShareDraft) => Promise<void>;
|
||||
readonly removeDraft: (shareId: string) => Promise<void>;
|
||||
readonly getPayloads: () => ReadonlyArray<SharePayload>;
|
||||
readonly clearPayloads: () => void;
|
||||
readonly buildDraft: (input: {
|
||||
readonly payloads: ReadonlyArray<SharePayload>;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}) => Promise<{
|
||||
readonly draft: IncomingShareDraft;
|
||||
readonly cleanup: () => Promise<void>;
|
||||
}>;
|
||||
readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;
|
||||
readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
|
||||
readonly now: () => string;
|
||||
readonly onClearError?: (error: unknown) => void;
|
||||
readonly onCleanupError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
export function sortAndDedupeIncomingShares(
|
||||
drafts: ReadonlyArray<IncomingShareDraft>,
|
||||
): ReadonlyArray<IncomingShareDraft> {
|
||||
const ids = new Set<string>();
|
||||
return [...drafts]
|
||||
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
|
||||
.filter((draft) => {
|
||||
if (ids.has(draft.id)) {
|
||||
return false;
|
||||
}
|
||||
ids.add(draft.id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes every durable inbox mutation. This prevents a stale storage load
|
||||
* or a foreground refresh from restoring an item after it has been consumed.
|
||||
*/
|
||||
export class IncomingShareInbox {
|
||||
private readonly operations = new SerializedAsyncQueue();
|
||||
|
||||
constructor(private readonly dependencies: IncomingShareInboxDependencies) {}
|
||||
|
||||
private runExclusive<T>(operation: () => Promise<T>): Promise<T> {
|
||||
return this.operations.run(operation);
|
||||
}
|
||||
|
||||
private clearNativePayloads(): void {
|
||||
try {
|
||||
this.dependencies.clearPayloads();
|
||||
} catch (error) {
|
||||
this.dependencies.onClearError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
private async cleanup(operation: () => Promise<void>): Promise<void> {
|
||||
try {
|
||||
await operation();
|
||||
} catch (error) {
|
||||
this.dependencies.onCleanupError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
refresh(options: { readonly ingestNative: boolean }): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const loaded = await this.dependencies.loadDrafts();
|
||||
const persisted = sortAndDedupeIncomingShares(loaded);
|
||||
if (!options.ingestNative) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const payloads = this.dependencies.getPayloads();
|
||||
if (payloads.length === 0) {
|
||||
return persisted;
|
||||
}
|
||||
|
||||
// A share extension payload remains available until the containing app
|
||||
// acknowledges it. Use a content-derived id so a crash after the durable
|
||||
// write but before acknowledgement reuses the same inbox item.
|
||||
const shareId = await this.dependencies.idForPayloads(payloads);
|
||||
if (loaded.some((draft) => draft.id === shareId)) {
|
||||
if (this.dependencies.cleanupReplayedPayloads) {
|
||||
await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads));
|
||||
}
|
||||
this.clearNativePayloads();
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const built = await this.dependencies.buildDraft({
|
||||
payloads,
|
||||
id: shareId,
|
||||
createdAt: this.dependencies.now(),
|
||||
});
|
||||
const { draft } = built;
|
||||
if (!hasIncomingShareContent(draft)) {
|
||||
// Unsupported native payloads cannot become actionable on retry and
|
||||
// would otherwise reopen the project picker on every foreground.
|
||||
await this.cleanup(built.cleanup);
|
||||
this.clearNativePayloads();
|
||||
throw new Error(
|
||||
draft.warnings[0] ?? "The shared content is not supported by the composer.",
|
||||
);
|
||||
}
|
||||
|
||||
// The durable inbox write is the transaction boundary. Never clear the
|
||||
// native handoff first: a process termination must leave one recoverable
|
||||
// copy on one side of the boundary.
|
||||
await this.dependencies.writeDraft(draft);
|
||||
await this.cleanup(built.cleanup);
|
||||
this.clearNativePayloads();
|
||||
return sortAndDedupeIncomingShares([draft, ...persisted]);
|
||||
});
|
||||
}
|
||||
|
||||
consume(shareId: string): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
// The stable payload-derived id already coalesces retries of the same
|
||||
// native handoff. Payload equality cannot identify duplicate handoffs:
|
||||
// users may intentionally share identical content more than once.
|
||||
await this.dependencies.removeDraft(shareId);
|
||||
return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts());
|
||||
});
|
||||
}
|
||||
|
||||
reserve(
|
||||
shareId: string,
|
||||
destination: IncomingShareDestination,
|
||||
): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const persisted = await this.dependencies.loadDrafts();
|
||||
const target = persisted.find((draft) => draft.id === shareId);
|
||||
if (!target) {
|
||||
throw new Error("The shared content is no longer available.");
|
||||
}
|
||||
if (target.destination) {
|
||||
if (
|
||||
target.destination.environmentId !== destination.environmentId ||
|
||||
target.destination.projectId !== destination.projectId
|
||||
) {
|
||||
throw new Error("The shared content is already reserved for another project draft.");
|
||||
}
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
|
||||
const reserved = { ...target, destination };
|
||||
await this.dependencies.writeDraft(reserved);
|
||||
return sortAndDedupeIncomingShares(
|
||||
persisted.map((draft) => (draft.id === shareId ? reserved : draft)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
releaseReservation(
|
||||
shareId: string,
|
||||
expectedDestination: IncomingShareDestination,
|
||||
): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
return this.runExclusive(async () => {
|
||||
const persisted = await this.dependencies.loadDrafts();
|
||||
const target = persisted.find((draft) => draft.id === shareId);
|
||||
if (!target) {
|
||||
// Conditional release is idempotent: if another operation already
|
||||
// consumed the share, no reservation remains to clean up.
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
if (!target.destination) {
|
||||
return sortAndDedupeIncomingShares(persisted);
|
||||
}
|
||||
if (
|
||||
target.destination.environmentId !== expectedDestination.environmentId ||
|
||||
target.destination.projectId !== expectedDestination.projectId
|
||||
) {
|
||||
throw new Error("The shared content reservation changed before it could be released.");
|
||||
}
|
||||
|
||||
const { destination: _destination, ...unreserved } = target;
|
||||
await this.dependencies.writeDraft(unreserved);
|
||||
return sortAndDedupeIncomingShares(
|
||||
persisted.map((draft) => (draft.id === shareId ? unreserved : draft)),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model";
|
||||
|
||||
describe("incoming native shares", () => {
|
||||
it("converts shared text, URLs, and images into a durable composer draft", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const payloads: SharePayload[] = [
|
||||
{ shareType: "text", value: "Please explain this error" },
|
||||
{ shareType: "url", value: "https://example.com/issue/1" },
|
||||
{ shareType: "text", value: "Please explain this error" },
|
||||
image,
|
||||
];
|
||||
const resolvedImage: ResolvedSharePayload = {
|
||||
...image,
|
||||
contentUri: image.value,
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "Screenshot.png",
|
||||
};
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-1",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads,
|
||||
resolvedPayloads: [resolvedImage],
|
||||
fileReader: {
|
||||
readBase64: async () => "YWJj",
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
schemaVersion: 1,
|
||||
id: "share-1",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
text: "Please explain this error\n\nhttps://example.com/issue/1",
|
||||
attachments: [
|
||||
{
|
||||
id: "share-1:image:3",
|
||||
type: "image",
|
||||
name: "Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
},
|
||||
],
|
||||
warnings: [],
|
||||
});
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
|
||||
expect(hasIncomingShareContent(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips oversized images and releases the temporary native file", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/huge.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const readBase64 = vi.fn(async () => "unused");
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-2",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [image],
|
||||
resolvedPayloads: [
|
||||
{
|
||||
...image,
|
||||
contentUri: image.value,
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
|
||||
originalName: "huge.png",
|
||||
},
|
||||
],
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["'huge.png' exceeds the 10 MB attachment limit."]);
|
||||
expect(readBase64).not.toHaveBeenCalled();
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(image.value);
|
||||
expect(hasIncomingShareContent(result)).toBe(false);
|
||||
});
|
||||
|
||||
it("releases every temporary file when a share exceeds the attachment limit", async () => {
|
||||
const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
|
||||
shareType: "image" as const,
|
||||
value: `file:///shared/${index}.png`,
|
||||
mimeType: "image/png",
|
||||
}));
|
||||
const removeOwnedFile = vi.fn(() => Promise.resolve());
|
||||
const readBase64 = vi.fn(async () => "YWJj");
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-3",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads,
|
||||
resolvedPayloads: [],
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(result.attachments).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
|
||||
expect(result.warnings).toEqual([
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
|
||||
]);
|
||||
expect(readBase64).toHaveBeenCalledTimes(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
|
||||
expect(removeOwnedFile).toHaveBeenCalledTimes(payloads.length);
|
||||
});
|
||||
|
||||
it("maps duplicate image payloads to distinct resolved files", async () => {
|
||||
const duplicate: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "content://shared/screenshot",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
const resolvedPayloads: ResolvedSharePayload[] = [
|
||||
{
|
||||
...duplicate,
|
||||
contentUri: "file:///cache/first.png",
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "first.png",
|
||||
},
|
||||
{
|
||||
...duplicate,
|
||||
contentUri: "file:///cache/second.png",
|
||||
contentType: "image",
|
||||
contentMimeType: "image/png",
|
||||
contentSize: 3,
|
||||
originalName: "second.png",
|
||||
},
|
||||
];
|
||||
const readBase64 = vi.fn(async (uri: string) =>
|
||||
uri.includes("first") ? "Zmlyc3Q=" : "c2Vjb25k",
|
||||
);
|
||||
const removeOwnedFile = vi.fn(async () => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-duplicates",
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
payloads: [duplicate, duplicate],
|
||||
resolvedPayloads,
|
||||
fileReader: { readBase64, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(readBase64.mock.calls.map(([uri]) => uri)).toEqual([
|
||||
"file:///cache/first.png",
|
||||
"file:///cache/second.png",
|
||||
]);
|
||||
expect(result.attachments.map((attachment) => attachment.name)).toEqual([
|
||||
"first.png",
|
||||
"second.png",
|
||||
]);
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/first.png");
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/second.png");
|
||||
});
|
||||
|
||||
it("keeps imported content when temporary-file cleanup fails", async () => {
|
||||
const image: SharePayload = {
|
||||
shareType: "image",
|
||||
value: "file:///shared/screenshot.png",
|
||||
mimeType: "image/png",
|
||||
};
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-cleanup-failure",
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
payloads: [image],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "YWJj",
|
||||
removeOwnedFile: async () => {
|
||||
throw new Error("file is busy");
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toHaveLength(1);
|
||||
expect(result.warnings).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,217 +0,0 @@
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { estimateBase64ByteSize } from "../../lib/base64";
|
||||
|
||||
export interface IncomingShareDraft {
|
||||
readonly schemaVersion: 1;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly destination?: IncomingShareDestination;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly warnings: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface IncomingShareDestination {
|
||||
readonly environmentId: string;
|
||||
readonly projectId: string;
|
||||
}
|
||||
|
||||
const IncomingShareDestinationSchema = Schema.Struct({
|
||||
environmentId: Schema.String,
|
||||
projectId: Schema.String,
|
||||
});
|
||||
|
||||
export const IncomingShareDraftSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
id: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
destination: Schema.optional(IncomingShareDestinationSchema),
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
warnings: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
|
||||
|
||||
export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
|
||||
return decodeIncomingShareDraftSync(value);
|
||||
}
|
||||
|
||||
export interface IncomingShareFileReader {
|
||||
readonly readBase64: (uri: string) => Promise<string>;
|
||||
readonly removeOwnedFile: (uri: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function sharedText(payloads: ReadonlyArray<SharePayload>): string {
|
||||
const seen = new Set<string>();
|
||||
const values: string[] = [];
|
||||
for (const payload of payloads) {
|
||||
if (payload.shareType !== "text" && payload.shareType !== "url") {
|
||||
continue;
|
||||
}
|
||||
const value = payload.value.trim();
|
||||
if (!value || seen.has(value)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(value);
|
||||
values.push(value);
|
||||
}
|
||||
return values.join("\n\n");
|
||||
}
|
||||
|
||||
function resolvedImageFor(
|
||||
payload: SharePayload,
|
||||
index: number,
|
||||
resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,
|
||||
consumedIndexes: Set<number>,
|
||||
): ResolvedSharePayload | undefined {
|
||||
const sameIndex = resolvedPayloads[index];
|
||||
if (
|
||||
!consumedIndexes.has(index) &&
|
||||
sameIndex?.shareType === payload.shareType &&
|
||||
sameIndex.value === payload.value
|
||||
) {
|
||||
consumedIndexes.add(index);
|
||||
return sameIndex;
|
||||
}
|
||||
const matchingIndex = resolvedPayloads.findIndex(
|
||||
(candidate, candidateIndex) =>
|
||||
!consumedIndexes.has(candidateIndex) &&
|
||||
candidate.shareType === payload.shareType &&
|
||||
candidate.value === payload.value,
|
||||
);
|
||||
if (matchingIndex < 0) {
|
||||
return undefined;
|
||||
}
|
||||
consumedIndexes.add(matchingIndex);
|
||||
return resolvedPayloads[matchingIndex];
|
||||
}
|
||||
|
||||
async function releaseOwnedFiles(
|
||||
fileReader: IncomingShareFileReader,
|
||||
uris: ReadonlyArray<string | undefined>,
|
||||
): Promise<void> {
|
||||
for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {
|
||||
try {
|
||||
await fileReader.removeOwnedFile(uri);
|
||||
} catch {
|
||||
// Temporary-file cleanup is best-effort and must never discard content
|
||||
// that was successfully converted into a durable composer attachment.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackName(uri: string, index: number, mimeType: string): string {
|
||||
try {
|
||||
const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
|
||||
if (pathName) {
|
||||
return decodeURIComponent(pathName);
|
||||
}
|
||||
} catch {
|
||||
// Fall through to a deterministic attachment name.
|
||||
}
|
||||
const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png";
|
||||
return `shared-image-${index + 1}.${extension}`;
|
||||
}
|
||||
|
||||
export async function buildIncomingShareDraft(input: {
|
||||
readonly payloads: ReadonlyArray<SharePayload>;
|
||||
readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
|
||||
readonly fileReader: IncomingShareFileReader;
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}): Promise<IncomingShareDraft> {
|
||||
const attachments: DraftComposerImageAttachment[] = [];
|
||||
const warnings: string[] = [];
|
||||
const consumedResolvedPayloadIndexes = new Set<number>();
|
||||
let warnedAttachmentLimit = false;
|
||||
|
||||
for (const [index, payload] of input.payloads.entries()) {
|
||||
if (payload.shareType !== "image") {
|
||||
continue;
|
||||
}
|
||||
const resolved = resolvedImageFor(
|
||||
payload,
|
||||
index,
|
||||
input.resolvedPayloads,
|
||||
consumedResolvedPayloadIndexes,
|
||||
);
|
||||
const uri = resolved?.contentUri ?? payload.value;
|
||||
if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
if (!warnedAttachmentLimit) {
|
||||
warnings.push(
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
|
||||
);
|
||||
warnedAttachmentLimit = true;
|
||||
}
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
|
||||
const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();
|
||||
if (!uri || !mimeType.startsWith("image/")) {
|
||||
warnings.push("One shared item was not a supported image.");
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
resolved?.contentSize !== null &&
|
||||
resolved?.contentSize !== undefined &&
|
||||
resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
|
||||
) {
|
||||
warnings.push(
|
||||
`'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
|
||||
);
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const base64 = await input.fileReader.readBase64(uri);
|
||||
const sizeBytes = resolved?.contentSize ?? estimateBase64ByteSize(base64);
|
||||
if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
warnings.push(
|
||||
`'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const dataUrl = `data:${mimeType};base64,${base64}`;
|
||||
attachments.push({
|
||||
id: `${input.id}:image:${index}`,
|
||||
type: "image",
|
||||
name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
dataUrl,
|
||||
// The share provider's file is temporary. A data-backed preview keeps
|
||||
// the composer valid after its source file and App Group entry are gone.
|
||||
previewUri: dataUrl,
|
||||
});
|
||||
} catch {
|
||||
warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`);
|
||||
} finally {
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: input.id,
|
||||
createdAt: input.createdAt,
|
||||
text: sharedText(input.payloads),
|
||||
attachments,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {
|
||||
return draft.text.trim().length > 0 || draft.attachments.length > 0;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
transitionIncomingSharePresentation,
|
||||
} from "./incoming-share-presentation";
|
||||
|
||||
describe("incoming share presentation", () => {
|
||||
it("does not reopen a dismissed share when refresh returns a new object for the same id", () => {
|
||||
const presented = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(presented.shareIdToPresent).toBe("share-1");
|
||||
|
||||
const whilePresented = transitionIncomingSharePresentation(presented.state, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(whilePresented).toEqual({ state: presented.state, shareIdToPresent: null });
|
||||
|
||||
const dismissed = transitionIncomingSharePresentation(whilePresented.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(dismissed.state.dismissedShareId).toBe("share-1");
|
||||
|
||||
expect(
|
||||
transitionIncomingSharePresentation(dismissed.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}),
|
||||
).toEqual({ state: dismissed.state, shareIdToPresent: null });
|
||||
});
|
||||
|
||||
it("presents the next queued share immediately after the previous sheet closes", () => {
|
||||
const first = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
|
||||
const next = transitionIncomingSharePresentation(first.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-2",
|
||||
});
|
||||
expect(next.shareIdToPresent).toBe("share-2");
|
||||
expect(next.state).toEqual({ presentedShareId: "share-2", dismissedShareId: null });
|
||||
});
|
||||
|
||||
it("forgets dismissal after consumption so a later handoff may reuse the id", () => {
|
||||
const dismissed = {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: "share-1",
|
||||
};
|
||||
const consumed = transitionIncomingSharePresentation(dismissed, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: null,
|
||||
});
|
||||
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
|
||||
expect(
|
||||
transitionIncomingSharePresentation(consumed.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}).shareIdToPresent,
|
||||
).toBe("share-1");
|
||||
});
|
||||
|
||||
it("forgets a consumed presentation while its sheet is still mounted", () => {
|
||||
const presented = {
|
||||
presentedShareId: "share-1",
|
||||
dismissedShareId: null,
|
||||
};
|
||||
const consumed = transitionIncomingSharePresentation(presented, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: null,
|
||||
});
|
||||
expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
|
||||
const replacementWhileOpen = transitionIncomingSharePresentation(consumed.state, {
|
||||
isShareSheetPresented: true,
|
||||
pendingShareId: "share-1",
|
||||
});
|
||||
expect(replacementWhileOpen.shareIdToPresent).toBeNull();
|
||||
expect(
|
||||
transitionIncomingSharePresentation(replacementWhileOpen.state, {
|
||||
isShareSheetPresented: false,
|
||||
pendingShareId: "share-1",
|
||||
}).shareIdToPresent,
|
||||
).toBe("share-1");
|
||||
});
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
export interface IncomingSharePresentationState {
|
||||
readonly presentedShareId: string | null;
|
||||
readonly dismissedShareId: string | null;
|
||||
}
|
||||
|
||||
export interface IncomingSharePresentationTransition {
|
||||
readonly state: IncomingSharePresentationState;
|
||||
readonly shareIdToPresent: string | null;
|
||||
}
|
||||
|
||||
export const EMPTY_INCOMING_SHARE_PRESENTATION_STATE: IncomingSharePresentationState = {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Tracks presentation by durable share id rather than object identity. A user
|
||||
* dismissal suppresses only that inbox item until it is consumed or replaced.
|
||||
*/
|
||||
export function transitionIncomingSharePresentation(
|
||||
state: IncomingSharePresentationState,
|
||||
input: {
|
||||
readonly isShareSheetPresented: boolean;
|
||||
readonly pendingShareId: string | null;
|
||||
},
|
||||
): IncomingSharePresentationTransition {
|
||||
if (input.isShareSheetPresented) {
|
||||
if (state.presentedShareId !== null && input.pendingShareId !== state.presentedShareId) {
|
||||
// Consumption may happen while the sheet remains mounted. Forget the
|
||||
// old presentation immediately so a later handoff may reuse its id.
|
||||
return {
|
||||
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
return { state, shareIdToPresent: null };
|
||||
}
|
||||
|
||||
let nextState = state;
|
||||
if (state.presentedShareId !== null) {
|
||||
if (input.pendingShareId === state.presentedShareId) {
|
||||
return {
|
||||
state: {
|
||||
presentedShareId: null,
|
||||
dismissedShareId: state.presentedShareId,
|
||||
},
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
nextState = { ...state, presentedShareId: null };
|
||||
}
|
||||
|
||||
if (input.pendingShareId === null) {
|
||||
return {
|
||||
state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
|
||||
shareIdToPresent: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (nextState.dismissedShareId === input.pendingShareId) {
|
||||
return { state: nextState, shareIdToPresent: null };
|
||||
}
|
||||
|
||||
return {
|
||||
state: {
|
||||
presentedShareId: input.pendingShareId,
|
||||
dismissedShareId: null,
|
||||
},
|
||||
shareIdToPresent: input.pendingShareId,
|
||||
};
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
|
||||
|
||||
const INCOMING_SHARE_DIRECTORY = "incoming-shares";
|
||||
|
||||
export class IncomingShareStorageError extends Schema.TaggedErrorClass<IncomingShareStorageError>()(
|
||||
"IncomingShareStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["load", "write", "remove"]),
|
||||
shareId: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function fileName(shareId: string): string {
|
||||
return `${encodeURIComponent(shareId)}.json`;
|
||||
}
|
||||
|
||||
async function getDirectory() {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return directory;
|
||||
}
|
||||
|
||||
async function getFile(shareId: string) {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(await getDirectory(), fileName(shareId));
|
||||
}
|
||||
|
||||
export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const drafts: IncomingShareDraft[] = [];
|
||||
for (const entry of (await getDirectory()).list()) {
|
||||
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[incoming-share] ignored invalid persisted share",
|
||||
new IncomingShareStorageError({ operation: "load", shareId: null, cause }),
|
||||
);
|
||||
}
|
||||
}
|
||||
return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
|
||||
try {
|
||||
const file = await getFile(draft.id);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(draft));
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeIncomingShareDraft(shareId: string): Promise<void> {
|
||||
try {
|
||||
const file = await getFile(shareId);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (cause) {
|
||||
throw new IncomingShareStorageError({ operation: "remove", shareId, cause });
|
||||
}
|
||||
}
|
||||
@@ -145,8 +145,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
|
||||
onSubmitEditing={(event) => {
|
||||
const text = event.nativeEvent.text;
|
||||
if (text.length > 0) {
|
||||
// Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
|
||||
props.onInput(`${text}\r`);
|
||||
props.onInput(`${text}\n`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -9,7 +9,6 @@ type NewTaskDraftRouteParams = {
|
||||
readonly projectId?: string | string[];
|
||||
readonly title?: string | string[];
|
||||
readonly pendingTaskId?: string | string[];
|
||||
readonly incomingShareId?: string | string[];
|
||||
};
|
||||
|
||||
export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
|
||||
@@ -37,9 +36,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
|
||||
/>
|
||||
<NewTaskDraftScreen
|
||||
initialProjectRef={initialProjectRef}
|
||||
incomingShareId={
|
||||
Array.isArray(params.incomingShareId) ? params.incomingShareId[0] : params.incomingShareId
|
||||
}
|
||||
pendingTaskId={
|
||||
Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
@@ -35,13 +35,7 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
restoreComposerDraftSnapshot,
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
@@ -49,7 +43,6 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
readonly workspaceMode: string;
|
||||
@@ -70,20 +63,11 @@ export function NewTaskDraftScreen(props: {
|
||||
};
|
||||
/** Queued outbox message id when editing an existing pending task. */
|
||||
readonly pendingTaskId?: string;
|
||||
/** Durable native share inbox item to merge into this project draft. */
|
||||
readonly incomingShareId?: string;
|
||||
}) {
|
||||
const projects = useProjects();
|
||||
const createProjectThread = useCreateProjectThread();
|
||||
const flow = useNewTaskFlow();
|
||||
const navigation = useNavigation();
|
||||
const {
|
||||
consumeShare,
|
||||
getShare,
|
||||
isLoading: isIncomingShareInboxLoading,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
} = useIncomingShare();
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
@@ -98,94 +82,10 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
|
||||
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
|
||||
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
|
||||
const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
|
||||
const [shareImportAttempt, setShareImportAttempt] = useState(0);
|
||||
const startedShareImportKeyRef = useRef<string | null>(null);
|
||||
const cancellingShareImportKeyRef = useRef<string | null>(null);
|
||||
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
|
||||
const activeShareImportTokenRef = useRef<symbol | null>(null);
|
||||
const shareImportMountedRef = useRef(true);
|
||||
const latestDraftKeyRef = useRef(flow.draftKey);
|
||||
const latestIncomingShareIdRef = useRef(props.incomingShareId);
|
||||
latestDraftKeyRef.current = flow.draftKey;
|
||||
latestIncomingShareIdRef.current = props.incomingShareId;
|
||||
const isImportingShare = importingShareKey !== null;
|
||||
const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
|
||||
const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
|
||||
const requestedInitialProjectAvailable = Boolean(
|
||||
props.initialProjectRef?.environmentId &&
|
||||
props.initialProjectRef.projectId &&
|
||||
projects.some(
|
||||
(project) =>
|
||||
project.environmentId === props.initialProjectRef?.environmentId &&
|
||||
project.id === props.initialProjectRef?.projectId,
|
||||
),
|
||||
);
|
||||
const isProjectPickerReturnActive =
|
||||
isReturningToProjectPicker && !requestedInitialProjectAvailable;
|
||||
const isIncomingShareTransferPending = Boolean(
|
||||
incomingShare && cancelledIncomingShareId !== props.incomingShareId,
|
||||
);
|
||||
usePreventRemove(
|
||||
(isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
|
||||
() => undefined,
|
||||
);
|
||||
const hasImportedIncomingShare = Boolean(
|
||||
props.incomingShareId &&
|
||||
flow.draftKey &&
|
||||
getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),
|
||||
);
|
||||
const isIncomingShareUnavailable = Boolean(
|
||||
props.incomingShareId &&
|
||||
!isIncomingShareInboxLoading &&
|
||||
!incomingShare &&
|
||||
!hasImportedIncomingShare,
|
||||
);
|
||||
const isIncomingShareReady =
|
||||
!props.incomingShareId ||
|
||||
(hasImportedIncomingShare && !incomingShare) ||
|
||||
isIncomingShareUnavailable;
|
||||
const appliedInitialProjectKeyRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (cancelledIncomingShareId === props.incomingShareId) {
|
||||
navigation.goBack();
|
||||
}
|
||||
}, [cancelledIncomingShareId, navigation, props.incomingShareId]);
|
||||
useEffect(() => {
|
||||
if (!isReturningToProjectPicker) {
|
||||
return;
|
||||
}
|
||||
if (requestedInitialProjectAvailable) {
|
||||
setIsReturningToProjectPicker(false);
|
||||
return;
|
||||
}
|
||||
// Let usePreventRemove commit its disabled state before replacing this
|
||||
// route, otherwise the transfer guard can swallow the fallback action.
|
||||
const frame = requestAnimationFrame(() => {
|
||||
navigation.dispatch(
|
||||
StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
|
||||
);
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
isReturningToProjectPicker,
|
||||
navigation,
|
||||
props.incomingShareId,
|
||||
requestedInitialProjectAvailable,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!shareImportMountedRef.current) {
|
||||
startedShareImportKeyRef.current = null;
|
||||
}
|
||||
shareImportMountedRef.current = true;
|
||||
return () => {
|
||||
appliedInitialProjectKeyRef.current = null;
|
||||
shareImportMountedRef.current = false;
|
||||
activeShareImportTokenRef.current = null;
|
||||
cancellingShareImportKeyRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -263,14 +163,6 @@ export function NewTaskDraftScreen(props: {
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (projects.length > 0) {
|
||||
// Never fall through to the flow provider's temporary first-project
|
||||
// default. Return to the picker with the share id intact so the user
|
||||
// can choose an available destination.
|
||||
setIsReturningToProjectPicker(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProject) {
|
||||
@@ -287,7 +179,6 @@ export function NewTaskDraftScreen(props: {
|
||||
logicalProjects,
|
||||
projects,
|
||||
props.initialProjectRef,
|
||||
props.incomingShareId,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
@@ -307,205 +198,6 @@ export function NewTaskDraftScreen(props: {
|
||||
void flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
const shareId = props.incomingShareId;
|
||||
const draftKey = flow.draftKey;
|
||||
const destinationProject = selectedProject;
|
||||
const initialEnvironmentId = props.initialProjectRef?.environmentId;
|
||||
const initialProjectId = props.initialProjectRef?.projectId;
|
||||
const selectedProjectMatchesRoute =
|
||||
!initialEnvironmentId ||
|
||||
!initialProjectId ||
|
||||
(destinationProject?.environmentId === initialEnvironmentId &&
|
||||
destinationProject.id === initialProjectId);
|
||||
if (
|
||||
!shareId ||
|
||||
!draftKey ||
|
||||
!destinationProject ||
|
||||
!selectedProjectMatchesRoute ||
|
||||
cancelledIncomingShareId === shareId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const importKey = `${shareId}:${draftKey}`;
|
||||
if (
|
||||
startedShareImportKeyRef.current === importKey ||
|
||||
cancellingShareImportKeyRef.current === importKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!incomingShare) {
|
||||
if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
|
||||
alertedUnavailableIncomingShareIdRef.current = shareId;
|
||||
Alert.alert(
|
||||
"Shared content unavailable",
|
||||
"The shared content is no longer in the inbox. You can continue editing this task draft.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (alertedUnavailableIncomingShareIdRef.current === shareId) {
|
||||
alertedUnavailableIncomingShareIdRef.current = null;
|
||||
}
|
||||
startedShareImportKeyRef.current = importKey;
|
||||
const draftBackup =
|
||||
shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
|
||||
shareImportDraftBackupRef.current.set(importKey, draftBackup);
|
||||
const importToken = Symbol(importKey);
|
||||
let didReserveShare = false;
|
||||
let needsDraftRestore = false;
|
||||
activeShareImportTokenRef.current = importToken;
|
||||
setImportingShareKey(importKey);
|
||||
void (async () => {
|
||||
await reserveShare(shareId, {
|
||||
environmentId: String(destinationProject.environmentId),
|
||||
projectId: String(destinationProject.id),
|
||||
});
|
||||
didReserveShare = true;
|
||||
if (
|
||||
!shareImportMountedRef.current ||
|
||||
activeShareImportTokenRef.current !== importToken ||
|
||||
latestDraftKeyRef.current !== draftKey ||
|
||||
latestIncomingShareIdRef.current !== shareId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
needsDraftRestore = true;
|
||||
const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
|
||||
text: incomingShare.text,
|
||||
attachments: incomingShare.attachments,
|
||||
sourceShareId: shareId,
|
||||
});
|
||||
if (
|
||||
!shareImportMountedRef.current ||
|
||||
activeShareImportTokenRef.current !== importToken ||
|
||||
latestDraftKeyRef.current !== draftKey ||
|
||||
latestIncomingShareIdRef.current !== shareId
|
||||
) {
|
||||
// The durable reservation makes an interrupted transfer resume only
|
||||
// in this project instead of copying into a second project draft.
|
||||
return;
|
||||
}
|
||||
await consumeShare(shareId);
|
||||
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
|
||||
return;
|
||||
}
|
||||
const warnings = [...incomingShare.warnings];
|
||||
if (skippedAttachmentCount > 0) {
|
||||
warnings.push(
|
||||
`${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
|
||||
);
|
||||
}
|
||||
if (warnings.length > 0) {
|
||||
Alert.alert("Some shared content was skipped", warnings.join("\n"));
|
||||
}
|
||||
shareImportDraftBackupRef.current.delete(importKey);
|
||||
})()
|
||||
.catch((error) => {
|
||||
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"Could not import shared content",
|
||||
error instanceof Error ? error.message : "The shared content could not be saved.",
|
||||
[
|
||||
{
|
||||
text: "Cancel import",
|
||||
style: "cancel",
|
||||
onPress: () => {
|
||||
const cancelImport = async (): Promise<void> => {
|
||||
if (!shareImportMountedRef.current) {
|
||||
return;
|
||||
}
|
||||
// Latch synchronously before restoring the draft. The
|
||||
// restore publishes atom state and can re-run the import
|
||||
// effect before React commits the cancelling state update.
|
||||
cancellingShareImportKeyRef.current = importKey;
|
||||
setIsCancellingShareImport(true);
|
||||
try {
|
||||
if (needsDraftRestore) {
|
||||
await restoreComposerDraftSnapshot(draftKey, draftBackup);
|
||||
needsDraftRestore = false;
|
||||
}
|
||||
if (didReserveShare) {
|
||||
await releaseShareReservation(shareId, {
|
||||
environmentId: String(destinationProject.environmentId),
|
||||
projectId: String(destinationProject.id),
|
||||
});
|
||||
}
|
||||
shareImportDraftBackupRef.current.delete(importKey);
|
||||
if (shareImportMountedRef.current) {
|
||||
setIsCancellingShareImport(false);
|
||||
setCancelledIncomingShareId(shareId);
|
||||
}
|
||||
} catch (cancelError) {
|
||||
if (!shareImportMountedRef.current) {
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"Could not cancel import",
|
||||
cancelError instanceof Error
|
||||
? cancelError.message
|
||||
: "The shared content could not be restored safely.",
|
||||
[
|
||||
{
|
||||
text: "Retry import",
|
||||
onPress: () => {
|
||||
cancellingShareImportKeyRef.current = null;
|
||||
setIsCancellingShareImport(false);
|
||||
setShareImportAttempt((attempt) => attempt + 1);
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Retry cancel",
|
||||
onPress: () => void cancelImport(),
|
||||
},
|
||||
],
|
||||
{ cancelable: false },
|
||||
);
|
||||
}
|
||||
};
|
||||
void cancelImport();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Retry",
|
||||
onPress: () => setShareImportAttempt((attempt) => attempt + 1),
|
||||
},
|
||||
],
|
||||
{ cancelable: false },
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (startedShareImportKeyRef.current === importKey) {
|
||||
// Every terminal path, including an invalidated operation, must
|
||||
// release the synchronous start latch so this transfer can retry.
|
||||
startedShareImportKeyRef.current = null;
|
||||
}
|
||||
if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
|
||||
activeShareImportTokenRef.current = null;
|
||||
setImportingShareKey(null);
|
||||
}
|
||||
});
|
||||
}, [
|
||||
consumeShare,
|
||||
cancelledIncomingShareId,
|
||||
flow.draftKey,
|
||||
hasImportedIncomingShare,
|
||||
incomingShare,
|
||||
isIncomingShareInboxLoading,
|
||||
isIncomingShareUnavailable,
|
||||
props.incomingShareId,
|
||||
props.initialProjectRef?.environmentId,
|
||||
props.initialProjectRef?.projectId,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
selectedProject,
|
||||
shareImportAttempt,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Android starts with the collapsed composer pill (like an open thread)
|
||||
// and only expands/focuses when tapped.
|
||||
@@ -531,11 +223,10 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.environments.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.environmentLabel,
|
||||
attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,
|
||||
state:
|
||||
flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
|
||||
})),
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
[flow.environments, flow.selectedEnvironmentId],
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
@@ -700,23 +391,20 @@ export function NewTaskDraftScreen(props: {
|
||||
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
|
||||
);
|
||||
function handleModelMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
|
||||
if (!event.startsWith("environment:")) {
|
||||
return;
|
||||
}
|
||||
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
|
||||
}
|
||||
|
||||
function handleOptionsMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
|
||||
if (providerOptions) {
|
||||
flow.setSelectedModelOptions(providerOptions);
|
||||
@@ -736,9 +424,6 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
|
||||
function handleWorkspaceMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("workspace:mode:")) {
|
||||
flow.setWorkspaceMode(
|
||||
event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
|
||||
@@ -759,9 +444,6 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
}
|
||||
const result = await pickComposerImages({ existingCount: flow.attachments.length });
|
||||
if (result.images.length > 0) {
|
||||
flow.appendAttachments(result.images);
|
||||
@@ -844,7 +526,8 @@ export function NewTaskDraftScreen(props: {
|
||||
if (editingPendingTask) {
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
}
|
||||
navigation.getParent()?.goBack();
|
||||
return;
|
||||
@@ -902,7 +585,8 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
flow.finishEditingPendingTask();
|
||||
} else {
|
||||
clearComposerDraftContent(draftKey);
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
}
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
@@ -936,15 +620,12 @@ export function NewTaskDraftScreen(props: {
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
flow.prompt.trim().length > 0 &&
|
||||
isIncomingShareReady &&
|
||||
!isImportingShare &&
|
||||
!flow.submitting &&
|
||||
!(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
autoFocus={!isAndroid}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
value={flow.prompt}
|
||||
@@ -979,7 +660,6 @@ export function NewTaskDraftScreen(props: {
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
showChevron={false}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
@@ -987,7 +667,6 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={flow.selectedModelOption?.label ?? "Model"}
|
||||
/>
|
||||
@@ -998,7 +677,6 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
@@ -1009,7 +687,6 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Environment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={selectedEnvironmentLabel}
|
||||
/>
|
||||
@@ -1020,7 +697,6 @@ export function NewTaskDraftScreen(props: {
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Workspace"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
label={workspaceLabel}
|
||||
/>
|
||||
@@ -1087,9 +763,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
onRemove={flow.removeAttachment}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -1133,7 +807,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<View className="px-4 pt-3">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
onRemove={flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useMemo } from "react";
|
||||
import { ActivityIndicator, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { cn } from "../../lib/cn";
|
||||
@@ -16,11 +16,6 @@ import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
};
|
||||
|
||||
function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
readonly title: string;
|
||||
@@ -77,29 +72,15 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
};
|
||||
}
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
export function NewTaskRouteScreen() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
const { layout } = useAdaptiveWorkspaceLayout();
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
: route.params?.incomingShareId;
|
||||
const incomingShare = routeShareId ? getShare(routeShareId) : null;
|
||||
const incomingShareSubtitle = incomingShare
|
||||
? incomingShare.attachments.length === 0
|
||||
? "Choose a project for what you shared"
|
||||
: incomingShare.attachments.length === 1
|
||||
? "Choose a project for the image you shared"
|
||||
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
|
||||
: null;
|
||||
const screenTitle = incomingShare ? "Start a task" : "Choose project";
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
@@ -128,70 +109,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
const resumedDestinationKeyRef = useRef<string | null>(null);
|
||||
const reservedDestinationProject = incomingShare?.destination
|
||||
? (projects.find(
|
||||
(project) =>
|
||||
project.environmentId === incomingShare.destination?.environmentId &&
|
||||
project.id === incomingShare.destination?.projectId,
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
async function selectProject(item: (typeof items)[number]): Promise<void> {
|
||||
if (incomingShare?.destination && !reservedDestinationProject) {
|
||||
try {
|
||||
await releaseShareReservation(incomingShare.id, incomingShare.destination);
|
||||
} catch (error) {
|
||||
Alert.alert(
|
||||
"Could not change project",
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The shared content reservation could not be updated.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const destination = incomingShare?.destination;
|
||||
if (!destination) {
|
||||
resumedDestinationKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (!isFocused) {
|
||||
// Returning from the reserved draft is a fresh resume attempt. Keeping
|
||||
// this latch set would leave every project row disabled with no route.
|
||||
resumedDestinationKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
|
||||
if (resumedDestinationKeyRef.current === destinationKey) {
|
||||
return;
|
||||
}
|
||||
if (!reservedDestinationProject) {
|
||||
return;
|
||||
}
|
||||
resumedDestinationKeyRef.current = destinationKey;
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: reservedDestinationProject.environmentId,
|
||||
projectId: reservedDestinationProject.id,
|
||||
title: reservedDestinationProject.title,
|
||||
incomingShareId: incomingShare.id,
|
||||
},
|
||||
});
|
||||
}, [incomingShare, isFocused, navigation, reservedDestinationProject]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -200,8 +117,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
{/* Android renders its own in-screen header instead of the native bar. */}
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader
|
||||
title={screenTitle}
|
||||
subtitle={incomingShareSubtitle}
|
||||
title="Choose project"
|
||||
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
|
||||
actions={[
|
||||
{
|
||||
@@ -213,29 +129,21 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: screenTitle,
|
||||
unstable_headerSubtitle: incomingShareSubtitle ?? undefined,
|
||||
}}
|
||||
/>
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Close new task"
|
||||
icon="xmark"
|
||||
onPress={() => navigation.goBack()}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
accessibilityLabel="Close new task"
|
||||
icon="xmark"
|
||||
onPress={() => navigation.goBack()}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
</>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
|
||||
<ScrollView
|
||||
@@ -244,7 +152,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 12,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
@@ -287,8 +194,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(item)}
|
||||
onPress={() =>
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
},
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
"bg-card px-4 py-3.5",
|
||||
!isFirst && "border-t border-border-subtle",
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
export function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
}
|
||||
@@ -36,37 +36,7 @@ vi.mock("./uuid", () => ({
|
||||
uuidv4: () => "attachment-id",
|
||||
}));
|
||||
|
||||
import {
|
||||
convertPastedImagesToAttachments,
|
||||
isOwnedPastedImageUri,
|
||||
toUploadChatImageAttachments,
|
||||
} from "./composerImages";
|
||||
|
||||
describe("toUploadChatImageAttachments", () => {
|
||||
it("strips client draft id and previewUri for the startTurn wire shape", () => {
|
||||
expect(
|
||||
toUploadChatImageAttachments([
|
||||
{
|
||||
id: "client-draft-id",
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
previewUri: "file:///tmp/preview.png",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
import { convertPastedImagesToAttachments, isOwnedPastedImageUri } from "./composerImages";
|
||||
|
||||
describe("native pasted image cleanup", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { estimateBase64ByteSize } from "./base64";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -11,21 +10,13 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
readonly previewUri: string;
|
||||
}
|
||||
|
||||
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
|
||||
export function toUploadChatImageAttachments(
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
): ReadonlyArray<UploadChatImageAttachment> {
|
||||
return attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
dataUrl: attachment.dataUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
function estimateBase64ByteSize(base64: string): number {
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((base64.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
return await import("expo-image-picker");
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
|
||||
import type { DraftComposerImageAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -55,7 +55,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
role: "user" as const,
|
||||
text: spec.text,
|
||||
attachments: toUploadChatImageAttachments(spec.attachments),
|
||||
attachments: spec.attachments,
|
||||
},
|
||||
modelSelection: spec.modelSelection,
|
||||
titleSeed: title,
|
||||
|
||||
@@ -38,6 +38,8 @@ function makeThread(
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { SerializedAsyncQueue } from "./serialized-async-queue";
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((next) => {
|
||||
resolve = next;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe("SerializedAsyncQueue", () => {
|
||||
it("does not let a newer operation overtake an in-flight operation", async () => {
|
||||
const queue = new SerializedAsyncQueue();
|
||||
const firstGate = deferred();
|
||||
const events: string[] = [];
|
||||
|
||||
const first = queue.run(async () => {
|
||||
events.push("first:start");
|
||||
await firstGate.promise;
|
||||
events.push("first:end");
|
||||
});
|
||||
const second = queue.run(async () => {
|
||||
events.push("second");
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
expect(events).toEqual(["first:start"]);
|
||||
firstGate.resolve();
|
||||
await Promise.all([first, second]);
|
||||
expect(events).toEqual(["first:start", "first:end", "second"]);
|
||||
});
|
||||
|
||||
it("continues after a rejected operation", async () => {
|
||||
const queue = new SerializedAsyncQueue();
|
||||
const first = queue.run(async () => {
|
||||
throw new Error("failed");
|
||||
});
|
||||
const second = queue.run(async () => "recovered");
|
||||
|
||||
await expect(first).rejects.toThrow("failed");
|
||||
await expect(second).resolves.toBe("recovered");
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
/**
|
||||
* Runs asynchronous operations in call order while keeping the queue usable
|
||||
* after an individual operation rejects.
|
||||
*/
|
||||
export class SerializedAsyncQueue {
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
|
||||
run<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.tail.then(operation, operation);
|
||||
this.tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ function makeThread(
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -195,7 +195,7 @@ function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {
|
||||
if (typeName === "NativeHeaderToolbarButton") {
|
||||
return {
|
||||
type: "button",
|
||||
label: typeof child.props.label === "string" ? child.props.label : "",
|
||||
label: "",
|
||||
accessibilityLabel:
|
||||
typeof child.props.accessibilityLabel === "string"
|
||||
? child.props.accessibilityLabel
|
||||
@@ -293,7 +293,6 @@ function NativeHeaderToolbarButton(_props: {
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly disabled?: boolean;
|
||||
readonly icon?: string;
|
||||
readonly label?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly separateBackground?: boolean;
|
||||
readonly tintColor?: ColorValue;
|
||||
|
||||
@@ -8,9 +8,7 @@ import {
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContentState,
|
||||
removeComposerDraftsForEnvironment,
|
||||
restoreComposerDraftSnapshotState,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
@@ -96,7 +94,6 @@ describe("mobile composer drafts", () => {
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
importedShareIds: ["share-1"],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
@@ -111,8 +108,7 @@ describe("mobile composer drafts", () => {
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
modelSelection: draft.modelSelection,
|
||||
workspaceSelection: draft.workspaceSelection,
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
@@ -135,90 +131,6 @@ describe("mobile composer drafts", () => {
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("merges shared content into a project draft without duplicating retries", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const sharedAttachment = {
|
||||
id: "share-1:image:0",
|
||||
type: "image" as const,
|
||||
name: "Screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
};
|
||||
const existing: Record<string, ComposerDraft> = {
|
||||
[draftKey]: { text: "Existing context", attachments: [] },
|
||||
};
|
||||
const content = {
|
||||
text: "Shared note",
|
||||
attachments: [sharedAttachment],
|
||||
sourceShareId: "share-1",
|
||||
};
|
||||
|
||||
const merged = mergeComposerDraftContentState(existing, draftKey, content);
|
||||
expect(merged[draftKey]).toMatchObject({
|
||||
text: "Existing context\n\nShared note",
|
||||
attachments: [sharedAttachment],
|
||||
importedShareIds: ["share-1"],
|
||||
});
|
||||
expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
|
||||
|
||||
const edited = {
|
||||
...merged,
|
||||
[draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
|
||||
};
|
||||
expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
|
||||
});
|
||||
|
||||
it("preserves existing images when shared content exceeds the draft attachment limit", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const image = (id: string) => ({
|
||||
id,
|
||||
type: "image" as const,
|
||||
name: `${id}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
});
|
||||
const existingImage = image("existing");
|
||||
const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
|
||||
|
||||
const merged = mergeComposerDraftContentState(
|
||||
{ [draftKey]: { text: "", attachments: [existingImage] } },
|
||||
draftKey,
|
||||
{ text: "", attachments: sharedImages },
|
||||
);
|
||||
|
||||
expect(merged[draftKey]?.attachments).toHaveLength(8);
|
||||
expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
|
||||
expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
|
||||
});
|
||||
|
||||
it("restores the exact draft captured before an interrupted share import", () => {
|
||||
const draftKey = "new-task:environment-1:project-1";
|
||||
const beforeImport: ComposerDraft = {
|
||||
text: "Existing context",
|
||||
attachments: [],
|
||||
runtimeMode: "approval-required",
|
||||
};
|
||||
const imported: ComposerDraft = {
|
||||
...beforeImport,
|
||||
text: "Existing context\n\nShared note",
|
||||
importedShareIds: ["share-1"],
|
||||
};
|
||||
|
||||
expect(
|
||||
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
|
||||
).toEqual({ [draftKey]: beforeImport });
|
||||
expect(
|
||||
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
|
||||
text: "",
|
||||
attachments: [],
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
@@ -15,7 +14,6 @@ import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
|
||||
@@ -40,19 +38,12 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly importedShareIds?: ReadonlyArray<string>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
export interface ComposerDraftContent {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly sourceShareId?: string;
|
||||
}
|
||||
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
@@ -75,7 +66,6 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
importedShareIds: Schema.optional(Schema.Array(Schema.String)),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
@@ -103,7 +93,6 @@ export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).p
|
||||
|
||||
let loadPromise: Promise<void> | null = null;
|
||||
let persistTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const persistenceQueue = new SerializedAsyncQueue();
|
||||
|
||||
function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
if (!draft) {
|
||||
@@ -204,7 +193,7 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
|
||||
async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
|
||||
try {
|
||||
await persistenceQueue.run(() => writePersistedComposerDrafts(drafts));
|
||||
await writePersistedComposerDrafts(drafts);
|
||||
} catch (error) {
|
||||
console.warn("[composer-drafts] failed to persist drafts", error);
|
||||
// Draft persistence is best-effort; in-memory drafts still keep working.
|
||||
@@ -377,9 +366,8 @@ export function clearComposerDraftContentState(
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const { importedShareIds: _importedShareIds, ...retained } = existing;
|
||||
const draft = {
|
||||
...retained,
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
@@ -394,138 +382,6 @@ export function clearComposerDraftContentState(
|
||||
};
|
||||
}
|
||||
|
||||
export function restoreComposerDraftSnapshotState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
snapshot: ComposerDraft,
|
||||
): Record<string, ComposerDraft> {
|
||||
const next = { ...current };
|
||||
if (isEmptyDraft(snapshot)) {
|
||||
delete next[draftKey];
|
||||
} else {
|
||||
next[draftKey] = snapshot;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function mergeComposerDraftText(existing: string, incoming: string): string {
|
||||
if (incoming.length === 0) {
|
||||
return existing;
|
||||
}
|
||||
if (existing.length === 0) {
|
||||
return incoming;
|
||||
}
|
||||
// Import retries are possible after an interrupted native handoff. Keep the
|
||||
// operation idempotent when the same shared text is already present.
|
||||
if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
|
||||
return existing;
|
||||
}
|
||||
return `${existing}\n\n${incoming}`;
|
||||
}
|
||||
|
||||
export function mergeComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
content: ComposerDraftContent,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = normalizeDraft(current[draftKey]);
|
||||
if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
|
||||
return current;
|
||||
}
|
||||
const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
|
||||
const incomingAttachments = content.attachments.filter((attachment) => {
|
||||
if (attachmentIds.has(attachment.id)) {
|
||||
return false;
|
||||
}
|
||||
attachmentIds.add(attachment.id);
|
||||
return true;
|
||||
});
|
||||
const attachments = [...existing.attachments, ...incomingAttachments].slice(
|
||||
0,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
);
|
||||
const text = mergeComposerDraftText(existing.text, content.text);
|
||||
const importedShareIds = content.sourceShareId
|
||||
? [...(existing.importedShareIds ?? []), content.sourceShareId]
|
||||
: existing.importedShareIds;
|
||||
if (
|
||||
text === existing.text &&
|
||||
attachments.length === existing.attachments.length &&
|
||||
importedShareIds === existing.importedShareIds
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: {
|
||||
...existing,
|
||||
text,
|
||||
attachments,
|
||||
...(importedShareIds ? { importedShareIds } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically moves an incoming share into a project-scoped composer draft.
|
||||
* The durable write happens before the share inbox item can be acknowledged.
|
||||
*/
|
||||
export async function mergeComposerDraftContent(
|
||||
draftKey: string,
|
||||
content: ComposerDraftContent,
|
||||
): Promise<{ readonly skippedAttachmentCount: number }> {
|
||||
ensureComposerDraftsLoaded();
|
||||
if (loadPromise !== null) {
|
||||
await loadPromise;
|
||||
}
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
persistTimer = null;
|
||||
}
|
||||
const current = appAtomRegistry.get(composerDraftsAtom);
|
||||
const next = mergeComposerDraftContentState(current, draftKey, content);
|
||||
const currentAttachmentIds = new Set(
|
||||
normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
|
||||
);
|
||||
const nextAttachmentIds = new Set(
|
||||
normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
|
||||
);
|
||||
const skippedAttachmentCount = content.attachments.filter(
|
||||
(attachment) =>
|
||||
!currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
|
||||
).length;
|
||||
// Publish the content and its import receipt together before the filesystem
|
||||
// await. Typing during persistence then builds on the receipt-bearing state,
|
||||
// and its debounced write is serialized after this transaction.
|
||||
if (next !== current) {
|
||||
appAtomRegistry.set(composerDraftsAtom, next);
|
||||
}
|
||||
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
|
||||
return { skippedAttachmentCount };
|
||||
}
|
||||
|
||||
/** Restores the exact content/settings captured before an interrupted import. */
|
||||
export async function restoreComposerDraftSnapshot(
|
||||
draftKey: string,
|
||||
snapshot: ComposerDraft,
|
||||
): Promise<void> {
|
||||
ensureComposerDraftsLoaded();
|
||||
if (loadPromise !== null) {
|
||||
await loadPromise;
|
||||
}
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
persistTimer = null;
|
||||
}
|
||||
const next = restoreComposerDraftSnapshotState(
|
||||
appAtomRegistry.get(composerDraftsAtom),
|
||||
draftKey,
|
||||
snapshot,
|
||||
);
|
||||
appAtomRegistry.set(composerDraftsAtom, next);
|
||||
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
|
||||
import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
@@ -222,7 +221,7 @@ export function useThreadOutboxDrain(): void {
|
||||
messageId: queuedMessage.messageId,
|
||||
role: "user",
|
||||
text: queuedMessage.text,
|
||||
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
|
||||
@@ -58,6 +58,8 @@ function threadDetailToShell(
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
settledOverride: thread.settledOverride,
|
||||
settledAt: thread.settledAt,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
|
||||
@@ -146,6 +146,8 @@ describe("OrchestrationEngine", () => {
|
||||
createdAt: "2026-03-03T00:00:02.000Z",
|
||||
updatedAt: "2026-03-03T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -607,6 +607,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -645,6 +647,38 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.settled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: "settled",
|
||||
settledAt: event.payload.settledAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.unsettled": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
settledOverride: event.payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -308,6 +308,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -418,6 +420,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -334,6 +334,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -362,6 +364,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -392,6 +396,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -754,6 +760,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1186,6 +1194,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1384,6 +1394,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1513,6 +1525,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1647,6 +1661,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
settledOverride: row.settledOverride,
|
||||
settledAt: row.settledAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1887,6 +1903,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -1981,6 +1999,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
settledOverride: threadRow.value.settledOverride,
|
||||
settledAt: threadRow.value.settledAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -4,11 +4,13 @@ import {
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
|
||||
ThreadSettledPayload as ContractsThreadSettledPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -29,11 +31,13 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
|
||||
export const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -68,6 +68,8 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -91,6 +93,8 @@ const readModel: OrchestrationReadModel = {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
@@ -72,30 +71,6 @@ export function requireProjectAbsent(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function requireActiveProjectWorkspaceRootAbsent(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly workspaceRoot: string;
|
||||
readonly exceptProjectId?: ProjectId;
|
||||
}): Effect.Effect<void, OrchestrationCommandInvariantError> {
|
||||
const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);
|
||||
const existingProject = input.readModel.projects.find(
|
||||
(project) =>
|
||||
project.deletedAt === null &&
|
||||
normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&
|
||||
project.id !== input.exceptProjectId,
|
||||
);
|
||||
if (existingProject === undefined) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.fail(
|
||||
invariantError(
|
||||
input.command.type,
|
||||
`Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function requireThread(input: {
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
readonly command: OrchestrationCommand;
|
||||
|
||||
@@ -94,117 +94,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.create for an active workspace root that already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const readModel = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-existing"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-existing"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-duplicate-root"),
|
||||
projectId: asProjectId("project-duplicate-root"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project/",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure.message).toContain(
|
||||
"Active project 'project-existing' already exists for workspace root '/tmp/project'.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.meta.update when moving onto another active workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withFirstProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-first"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-first"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-first"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-first"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-first"),
|
||||
title: "First",
|
||||
workspaceRoot: "/tmp/project-first",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withFirstProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-project-create-second"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-second"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-second"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-second"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-second"),
|
||||
title: "Second",
|
||||
workspaceRoot: "/tmp/project-second",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-duplicate-root"),
|
||||
projectId: asProjectId("project-second"),
|
||||
workspaceRoot: "/tmp/project-first",
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure.message).toContain(
|
||||
"Active project 'project-first' already exists for workspace root '/tmp/project-first'.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-01-01T00:00:00.000Z";
|
||||
const SETTLED_AT = "2025-12-30T00:00:00.000Z";
|
||||
|
||||
function makeReadModel(
|
||||
settledOverride: OrchestrationThread["settledOverride"],
|
||||
archivedAt: string | null = null,
|
||||
): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt,
|
||||
settledOverride,
|
||||
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
|
||||
return {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status,
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("settled thread decider", (it) => {
|
||||
it.effect("settles active threads and re-emits idempotently for settled ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null),
|
||||
});
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.type).toBe("thread.settled");
|
||||
if (events[0]?.type === "thread.settled") {
|
||||
expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
|
||||
}
|
||||
|
||||
// Already settled: the engine rejects zero-event commands, so idempotency
|
||||
// is by re-emission — preserving the original settledAt.
|
||||
const reEmit = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
|
||||
expect(reEmitEvents).toHaveLength(1);
|
||||
expect(reEmitEvents[0]?.type).toBe("thread.settled");
|
||||
if (reEmitEvents[0]?.type === "thread.settled") {
|
||||
expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
|
||||
expect(reEmitEvents[0].payload.updatedAt).toBe(SETTLED_AT);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects settling and unsettling archived threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const settleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("cmd-settle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
},
|
||||
readModel: makeReadModel(null, NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
const unsettleError = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-archived"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled", NOW),
|
||||
}).pipe(Effect.flip);
|
||||
expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
|
||||
Effect.gen(function* () {
|
||||
const userEvent = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
|
||||
expect(userEvents).toHaveLength(1);
|
||||
expect(userEvents[0]?.type).toBe("thread.unsettled");
|
||||
if (userEvents[0]?.type === "thread.unsettled") {
|
||||
expect(userEvents[0].payload.reason).toBe("user");
|
||||
}
|
||||
|
||||
// Re-dispatching against the already-reached state re-emits rather than
|
||||
// producing zero events (the engine rejects empty commands).
|
||||
const userAgain = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.unsettle",
|
||||
commandId: CommandId.make("cmd-unsettle-user-again"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
|
||||
expect(userAgainEvents).toHaveLength(1);
|
||||
expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepends activity unsets for turn starts and live session updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const sessionResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession("running"),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
|
||||
expect(sessionEvents.map((event) => event.type)).toEqual(["thread.session-set"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves an explicit active override during activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const turnResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-active-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-active"),
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
|
||||
expect(turnEvents.map((event) => event.type)).toEqual([
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
|
||||
const activityResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-active-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-active"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("active"),
|
||||
});
|
||||
const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
|
||||
expect(activityEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not unsettle for session stop/error status writes", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const status of ["stopped", "error", "ready", "idle"] as const) {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make(`cmd-session-${status}`),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: makeSession(status),
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsettles for approval and user-input activities but not others", () =>
|
||||
Effect.gen(function* () {
|
||||
const approvalResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-1"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
|
||||
expect(approvalEvents.map((event) => event.type)).toEqual([
|
||||
"thread.unsettled",
|
||||
"thread.activity-appended",
|
||||
]);
|
||||
|
||||
const routineResult = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.make("cmd-activity-routine"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.make("activity-2"),
|
||||
tone: "info",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool completed",
|
||||
payload: null,
|
||||
turnId: null,
|
||||
createdAt: NOW,
|
||||
},
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel("settled"),
|
||||
});
|
||||
const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
|
||||
expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -12,7 +12,6 @@ import type * as PlatformError from "effect/PlatformError";
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
import {
|
||||
listThreadsByProjectId,
|
||||
requireActiveProjectWorkspaceRootAbsent,
|
||||
requireProject,
|
||||
requireProjectAbsent,
|
||||
requireThread,
|
||||
@@ -112,12 +111,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
projectId: command.projectId,
|
||||
});
|
||||
yield* requireActiveProjectWorkspaceRootAbsent({
|
||||
readModel,
|
||||
command,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
exceptProjectId: command.projectId,
|
||||
});
|
||||
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
@@ -145,14 +138,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
projectId: command.projectId,
|
||||
});
|
||||
if (command.workspaceRoot !== undefined) {
|
||||
yield* requireActiveProjectWorkspaceRootAbsent({
|
||||
readModel,
|
||||
command,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
exceptProjectId: command.projectId,
|
||||
});
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
@@ -327,6 +312,61 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.settle": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
// Settling an already-settled thread re-emits with the original
|
||||
// settledAt: the engine rejects zero-event commands, and bulk-settle /
|
||||
// double-click must stay silent no-ops rather than surface errors.
|
||||
const settledAt =
|
||||
thread.settledOverride === "settled" && thread.settledAt !== null
|
||||
? thread.settledAt
|
||||
: occurredAt;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.settled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
settledAt,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsettle": {
|
||||
yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
// Idempotent by re-emission (see thread.settle): reducing the event a
|
||||
// second time lands on the same override state.
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.meta.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
@@ -479,7 +519,24 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
if (targetThread.settledOverride !== "settled") {
|
||||
return [userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, userMessageEvent, turnStartRequestedEvent];
|
||||
}
|
||||
|
||||
case "thread.turn.interrupt": {
|
||||
@@ -600,12 +657,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.session.set": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -619,6 +676,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
session: command.session,
|
||||
},
|
||||
};
|
||||
// Only a session coming alive is activity worth waking a settled thread
|
||||
// for — status writes like ready/stopped/error arrive after the fact and
|
||||
// must not fight a user's explicit settle.
|
||||
const isSessionActivity =
|
||||
command.session.status === "starting" || command.session.status === "running";
|
||||
if (thread.settledOverride !== "settled" || !isSessionActivity) {
|
||||
return sessionSetEvent;
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, sessionSetEvent];
|
||||
}
|
||||
|
||||
case "thread.message.assistant.delta": {
|
||||
@@ -745,7 +825,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.activity.append": {
|
||||
yield* requireThread({
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
@@ -758,7 +838,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? ((command.activity.payload as { requestId: string })
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
return {
|
||||
const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -772,6 +852,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
activity: command.activity,
|
||||
},
|
||||
};
|
||||
// An approval or user-input request is blocked-on-you work — it must
|
||||
// never stay hidden inside a settled slim row.
|
||||
const wakesSettledThread =
|
||||
command.activity.kind === "approval.requested" ||
|
||||
command.activity.kind === "user-input.requested";
|
||||
if (thread.settledOverride !== "settled" || !wakesSettledThread) {
|
||||
return activityAppendedEvent;
|
||||
}
|
||||
const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
return [unsettledEvent, activityAppendedEvent];
|
||||
}
|
||||
|
||||
default: {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
function makeEvent(input: {
|
||||
readonly sequence: number;
|
||||
readonly type: OrchestrationEvent["type"];
|
||||
readonly payload: unknown;
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: CommandId.make(`command-${input.sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: input.payload as never,
|
||||
} as OrchestrationEvent;
|
||||
}
|
||||
|
||||
it.effect("projects settled lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const created = yield* projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const settled = yield* projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.settled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), settledAt: now, updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(settled.threads[0]?.settledOverride).toBe("settled");
|
||||
expect(settled.threads[0]?.settledAt).toBe(now);
|
||||
|
||||
const userUnsettled = yield* projectEvent(
|
||||
settled,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "user", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(userUnsettled.threads[0]?.settledOverride).toBe("active");
|
||||
expect(userUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
|
||||
const activityUnsettled = yield* projectEvent(
|
||||
userUnsettled,
|
||||
makeEvent({
|
||||
sequence: 4,
|
||||
type: "thread.unsettled",
|
||||
payload: { threadId: ThreadId.make("thread-1"), reason: "activity", updatedAt: now },
|
||||
}),
|
||||
);
|
||||
expect(activityUnsettled.threads[0]?.settledOverride).toBeNull();
|
||||
expect(activityUnsettled.threads[0]?.settledAt).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -89,6 +89,8 @@ describe("orchestration projector", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -22,7 +22,9 @@ import {
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
ThreadUnarchivedPayload,
|
||||
ThreadUnsettledPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -286,6 +288,8 @@ export function projectEvent(
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -337,6 +341,30 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.settled":
|
||||
return decodeForEvent(ThreadSettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: "settled",
|
||||
settledAt: payload.settledAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.unsettled":
|
||||
return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
settledOverride: payload.reason === "user" ? "active" : null,
|
||||
settledAt: null,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -91,6 +91,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
|
||||
@@ -43,6 +43,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
settled_override,
|
||||
settled_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -62,6 +64,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.settledOverride},
|
||||
${row.settledAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -81,6 +85,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
settled_override = excluded.settled_override,
|
||||
settled_at = excluded.settled_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -107,6 +113,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -135,6 +143,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
settled_override AS "settledOverride",
|
||||
settled_at AS "settledAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
|
||||
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -89,6 +90,7 @@ export const migrationEntries = [
|
||||
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "settled_override")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN settled_override TEXT
|
||||
`;
|
||||
}
|
||||
|
||||
if (!columns.some((column) => column.name === "settled_at")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN settled_at TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -36,6 +36,8 @@ export const ProjectionThread = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
archivedAt: Schema.NullOr(IsoDateTime),
|
||||
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -974,13 +974,8 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "request.opened" && event.requestId && !interrupted) {
|
||||
if (event.type === "request.opened" && !interrupted) {
|
||||
interrupted = true;
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(event.requestId)),
|
||||
"cancel",
|
||||
);
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
return;
|
||||
}
|
||||
@@ -1035,10 +1030,15 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
entry.result.outcome !== null &&
|
||||
"outcome" in entry.result.outcome &&
|
||||
entry.result.outcome.outcome === "cancelled";
|
||||
const cancelRequests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
const approvalResponses = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
isCancelledApprovalResponse,
|
||||
);
|
||||
assert.isTrue(cancelRequests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(approvalResponses.some(isCancelledApprovalResponse));
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
|
||||
@@ -100,6 +100,8 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
|
||||
@@ -305,6 +305,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -451,6 +453,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
@@ -606,6 +610,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
|
||||
@@ -163,6 +163,8 @@ const makeDefaultOrchestrationReadModel = () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
@@ -192,6 +194,8 @@ const makeDefaultOrchestrationThreadShell = (
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
@@ -5495,6 +5499,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { it, describe, expect } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
@@ -66,7 +64,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
relativePath: "src/index.ts",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
expect(result).toEqual({
|
||||
relativePath: "src/index.ts",
|
||||
contents: "export const answer = 42;\n",
|
||||
byteLength: 26,
|
||||
@@ -84,8 +82,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
.readFile({ cwd, relativePath: "../escape.md" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.include(
|
||||
error.message,
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
}),
|
||||
@@ -110,14 +107,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
|
||||
const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
|
||||
|
||||
assert.strictEqual(error._tag, "WorkspaceFilePathEscapeError");
|
||||
assert.deepInclude(error, {
|
||||
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "linked-secret.txt",
|
||||
resolvedWorkspaceRoot,
|
||||
resolvedPath,
|
||||
});
|
||||
assert.notProperty(error, "cause");
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -134,13 +131,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
.pipe(Effect.flip);
|
||||
const resolvedPath = yield* fileSystem.realPath(path.join(cwd, "src"));
|
||||
|
||||
assert.strictEqual(error._tag, "WorkspacePathNotFileError");
|
||||
assert.deepInclude(error, {
|
||||
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "src",
|
||||
resolvedPath,
|
||||
});
|
||||
assert.notProperty(error, "cause");
|
||||
expect("cause" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -158,31 +155,14 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
.pipe(Effect.flip);
|
||||
const resolvedPath = yield* fileSystem.realPath(absolutePath);
|
||||
|
||||
assert.strictEqual(error._tag, "WorkspaceBinaryFileError");
|
||||
assert.deepInclude(error, {
|
||||
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "asset.bin",
|
||||
resolvedPath,
|
||||
});
|
||||
assert.notProperty(error, "cause");
|
||||
assert.notProperty(error, "contents");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads at most the preview limit", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "large.txt", "a".repeat(1024 * 1024 + 1));
|
||||
|
||||
const result = yield* workspaceFileSystem.readFile({
|
||||
cwd,
|
||||
relativePath: "large.txt",
|
||||
});
|
||||
|
||||
assert.strictEqual(result.contents.length, 1024 * 1024);
|
||||
assert.strictEqual(result.byteLength, 1024 * 1024 + 1);
|
||||
assert.isTrue(result.truncated);
|
||||
expect("cause" in error).toBe(false);
|
||||
expect("contents" in error).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -197,16 +177,16 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
.readFile({ cwd, relativePath: "missing.txt" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "WorkspaceFileSystemOperationError");
|
||||
assert.deepInclude(error, {
|
||||
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError);
|
||||
expect(error).toMatchObject({
|
||||
workspaceRoot: cwd,
|
||||
relativePath: "missing.txt",
|
||||
resolvedPath,
|
||||
operationPath: resolvedPath,
|
||||
operation: "realpath-target",
|
||||
});
|
||||
assert.instanceOf(error.cause, PlatformError.PlatformError);
|
||||
assert.strictEqual((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
|
||||
expect(error.cause).toBeInstanceOf(Error);
|
||||
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -227,8 +207,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
|
||||
.pipe(Effect.orDie);
|
||||
|
||||
assert.deepStrictEqual(result, { relativePath: "plans/effect-rpc.md" });
|
||||
assert.strictEqual(saved, "# Plan\n");
|
||||
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
|
||||
expect(saved).toBe("# Plan\n");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -240,7 +220,9 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
|
||||
|
||||
const beforeWrite = yield* workspaceEntries.list({ cwd });
|
||||
assert.isFalse(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
|
||||
expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
yield* workspaceFileSystem.writeFile({
|
||||
cwd,
|
||||
@@ -249,8 +231,10 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
});
|
||||
|
||||
const afterWrite = yield* workspaceEntries.list({ cwd });
|
||||
assert.isTrue(afterWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
|
||||
assert.isFalse(afterWrite.truncated);
|
||||
expect(afterWrite.entries).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
|
||||
);
|
||||
expect(afterWrite.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -269,14 +253,15 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.include(
|
||||
error.message,
|
||||
expect(error.message).toContain(
|
||||
"Workspace file path must be relative to the project root: ../escape.md",
|
||||
);
|
||||
|
||||
const escapedPath = path.resolve(cwd, "..", "escape.md");
|
||||
const escapedStat = yield* fileSystem.stat(escapedPath).pipe(Effect.option);
|
||||
assert.isTrue(Option.isNone(escapedStat));
|
||||
const escapedStat = yield* fileSystem
|
||||
.stat(escapedPath)
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
expect(escapedStat).toBeNull();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
|
||||
*
|
||||
@@ -6,6 +7,7 @@
|
||||
*
|
||||
* @module WorkspaceFileSystem
|
||||
*/
|
||||
import * as NodeFSP from "node:fs/promises";
|
||||
|
||||
import type {
|
||||
ProjectReadFileInput,
|
||||
@@ -17,7 +19,6 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -139,32 +140,30 @@ export const make = Effect.gen(function* () {
|
||||
relativePath: input.relativePath,
|
||||
});
|
||||
|
||||
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: input.cwd,
|
||||
operation: "realpath-workspace-root",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: target.absolutePath,
|
||||
operation: "realpath-target",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const realWorkspaceRoot = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.realpath(input.cwd),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: input.cwd,
|
||||
operation: "realpath-workspace-root",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const realTargetPath = yield* Effect.tryPromise({
|
||||
try: () => NodeFSP.realpath(target.absolutePath),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: target.absolutePath,
|
||||
operationPath: target.absolutePath,
|
||||
operation: "realpath-target",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
|
||||
if (
|
||||
relativeRealPath.startsWith(`..${path.sep}`) ||
|
||||
@@ -179,24 +178,24 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const handle = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
operationPath: realTargetPath,
|
||||
operation: "open",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const stat = yield* handle.stat.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
return yield* Effect.acquireUseRelease(
|
||||
Effect.tryPromise({
|
||||
try: () => NodeFSP.open(realTargetPath, "r"),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
operationPath: realTargetPath,
|
||||
operation: "open",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(handle) =>
|
||||
Effect.gen(function* () {
|
||||
const stat = yield* Effect.tryPromise({
|
||||
try: () => handle.stat(),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
@@ -205,21 +204,20 @@ export const make = Effect.gen(function* () {
|
||||
operation: "stat",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (stat.type !== "File") {
|
||||
return yield* new WorkspacePathNotFileError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
});
|
||||
}
|
||||
if (!stat.isFile()) {
|
||||
return yield* new WorkspacePathNotFileError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
});
|
||||
}
|
||||
|
||||
const byteLength = Number(stat.size);
|
||||
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
|
||||
const maybeFileBytes = yield* handle.readAlloc(bytesToRead).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
|
||||
const buffer = Buffer.alloc(bytesToRead);
|
||||
const { bytesRead } = yield* Effect.tryPromise({
|
||||
try: () => handle.read(buffer, 0, bytesToRead, 0),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
@@ -228,24 +226,36 @@ export const make = Effect.gen(function* () {
|
||||
operation: "read",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const fileBytes = Option.getOrElse(maybeFileBytes, () => new Uint8Array());
|
||||
if (fileBytes.includes(0)) {
|
||||
return yield* new WorkspaceBinaryFileError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
});
|
||||
}
|
||||
const fileBytes = buffer.subarray(0, bytesRead);
|
||||
if (fileBytes.includes(0)) {
|
||||
return yield* new WorkspaceBinaryFileError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
relativePath: target.relativePath,
|
||||
contents: new TextDecoder("utf-8").decode(fileBytes),
|
||||
byteLength,
|
||||
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
|
||||
};
|
||||
}),
|
||||
return {
|
||||
relativePath: target.relativePath,
|
||||
contents: new TextDecoder("utf-8").decode(fileBytes),
|
||||
byteLength: stat.size,
|
||||
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
|
||||
};
|
||||
}),
|
||||
(handle) =>
|
||||
Effect.tryPromise({
|
||||
try: () => handle.close(),
|
||||
catch: (cause) =>
|
||||
new WorkspaceFileSystemOperationError({
|
||||
workspaceRoot: input.cwd,
|
||||
relativePath: input.relativePath,
|
||||
resolvedPath: realTargetPath,
|
||||
operationPath: realTargetPath,
|
||||
operation: "close",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -25,89 +25,6 @@ describe("browser target resolver", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("maps localhost URL navigation onto a remote Tailscale IPv4 host", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "http://localhost:5173/dashboard?mode=test#results",
|
||||
}),
|
||||
).toEqual({
|
||||
requestedUrl: "http://localhost:5173/dashboard?mode=test#results",
|
||||
resolvedUrl: "http://100.65.180.100:5173/dashboard?mode=test#results",
|
||||
resolutionKind: "direct-private-network",
|
||||
environmentId: "environment-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves URL credentials when mapping localhost onto a remote host", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://100.65.180.100:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "http://user:p%40ss@localhost:5173/dashboard",
|
||||
}).resolvedUrl,
|
||||
).toBe("http://user:p%[email protected]:5173/dashboard");
|
||||
});
|
||||
|
||||
it("maps credentialed localhost URLs onto private IPv6 hosts", async () => {
|
||||
readPreparedConnection.mockReturnValue({
|
||||
httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773",
|
||||
});
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "http://user:p%40ss@localhost:5173/dashboard?mode=test#results",
|
||||
}).resolvedUrl,
|
||||
).toBe("http://user:p%40ss@[fd7a:115c:a1e0::53]:5173/dashboard?mode=test#results");
|
||||
});
|
||||
|
||||
it("maps schemeless localhost navigation onto a remote environment host", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.1.25:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "localhost:3000/app",
|
||||
}).resolvedUrl,
|
||||
).toBe("http://192.168.1.25:3000/app");
|
||||
});
|
||||
|
||||
it("keeps localhost navigation local for a local environment", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "localhost:3000/app",
|
||||
}),
|
||||
).toEqual({
|
||||
requestedUrl: "localhost:3000/app",
|
||||
resolvedUrl: "localhost:3000/app",
|
||||
resolutionKind: "direct",
|
||||
environmentId: "environment-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps localhost navigation local for the full IPv4 loopback range", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.2:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "http://localhost:3000/app",
|
||||
}),
|
||||
).toEqual({
|
||||
requestedUrl: "http://localhost:3000/app",
|
||||
resolvedUrl: "http://localhost:3000/app",
|
||||
resolutionKind: "direct",
|
||||
environmentId: "environment-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses public relay hosts until the authenticated gateway exists", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://relay.example.com" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
@@ -117,12 +34,6 @@ describe("browser target resolver", () => {
|
||||
port: 5173,
|
||||
}),
|
||||
).toThrow(/authenticated preview gateway/);
|
||||
expect(() =>
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "url",
|
||||
url: "http://localhost:5173",
|
||||
}),
|
||||
).toThrow(/authenticated preview gateway/);
|
||||
});
|
||||
|
||||
it("normalizes schemeless localhost server-picker values", async () => {
|
||||
@@ -152,9 +63,7 @@ describe("browser target resolver", () => {
|
||||
});
|
||||
|
||||
it("supports private IPv6 environment hosts", async () => {
|
||||
readPreparedConnection.mockReturnValue({
|
||||
httpBaseUrl: "http://[fd7a:115c:a1e0::53]:3773",
|
||||
});
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
@@ -162,18 +71,7 @@ describe("browser target resolver", () => {
|
||||
port: 5173,
|
||||
path: "/app?mode=test",
|
||||
}).resolvedUrl,
|
||||
).toBe("http://[fd7a:115c:a1e0::53]:5173/app?mode=test");
|
||||
});
|
||||
|
||||
it("supports a local IPv6 environment host", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://[::1]:3773" });
|
||||
const { resolveBrowserNavigationTarget } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveBrowserNavigationTarget(EnvironmentId.make("environment-1"), {
|
||||
kind: "environment-port",
|
||||
port: 5173,
|
||||
}).resolvedUrl,
|
||||
).toBe("http://[::1]:5173/");
|
||||
).toBe("http://[::1]:5173/app?mode=test");
|
||||
});
|
||||
|
||||
it("leaves malformed input for the normal navigation error path", async () => {
|
||||
|
||||
@@ -7,86 +7,26 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
|
||||
import { readPreparedConnection } from "~/state/session";
|
||||
|
||||
const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
|
||||
const parseIpv4Address = (host: string): readonly number[] | null => {
|
||||
const parts = normalizeHostname(host).split(".").map(Number);
|
||||
return parts.length === 4 &&
|
||||
parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
|
||||
? parts
|
||||
: null;
|
||||
};
|
||||
|
||||
const isLocalLoopbackHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (normalized === "localhost" || normalized === "::1") return true;
|
||||
return parseIpv4Address(normalized)?.[0] === 127;
|
||||
};
|
||||
|
||||
const isPrivateNetworkHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) {
|
||||
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (normalized === "localhost" || normalized === "::1" || normalized.endsWith(".local")) {
|
||||
return true;
|
||||
}
|
||||
if (normalized.endsWith(".ts.net")) return true;
|
||||
const parts = parseIpv4Address(normalized);
|
||||
if (parts) {
|
||||
return (
|
||||
parts[0] === 10 ||
|
||||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
|
||||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
|
||||
(parts[0] === 192 && parts[1] === 168) ||
|
||||
(parts[0] === 169 && parts[1] === 254)
|
||||
);
|
||||
}
|
||||
const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
|
||||
if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
|
||||
const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
|
||||
const parts = normalized.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
|
||||
return (
|
||||
Number.isInteger(firstIpv6Hextet) &&
|
||||
((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80)
|
||||
parts[0] === 10 ||
|
||||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
|
||||
(parts[0] === 192 && parts[1] === 168) ||
|
||||
parts[0] === 127 ||
|
||||
(parts[0] === 169 && parts[1] === 254)
|
||||
);
|
||||
};
|
||||
|
||||
const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
return new URL(connection.httpBaseUrl);
|
||||
};
|
||||
|
||||
const resolveEnvironmentPortTarget = (
|
||||
environmentId: EnvironmentId,
|
||||
target: Extract<BrowserNavigationTarget, { readonly kind: "environment-port" }>,
|
||||
environmentUrl: URL,
|
||||
requestedUrl?: string,
|
||||
sourceUrl?: URL,
|
||||
): PreviewUrlResolution => {
|
||||
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
|
||||
throw new Error(
|
||||
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
|
||||
);
|
||||
}
|
||||
const protocol = target.protocol ?? "http";
|
||||
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
|
||||
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
|
||||
const resolvedHost = normalizedEnvironmentHost.includes(":")
|
||||
? `[${normalizedEnvironmentHost}]`
|
||||
: normalizedEnvironmentHost;
|
||||
const resolved = sourceUrl
|
||||
? new URL(sourceUrl)
|
||||
: new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
|
||||
if (sourceUrl) {
|
||||
resolved.hostname = resolvedHost;
|
||||
resolved.port = String(target.port);
|
||||
}
|
||||
return {
|
||||
requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`,
|
||||
resolvedUrl: resolved.toString(),
|
||||
resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost)
|
||||
? "direct"
|
||||
: "direct-private-network",
|
||||
environmentId,
|
||||
};
|
||||
const isLocalLoopbackHost = (host: string): boolean => {
|
||||
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
||||
};
|
||||
|
||||
export function resolveBrowserNavigationTarget(
|
||||
@@ -94,30 +34,6 @@ export function resolveBrowserNavigationTarget(
|
||||
target: BrowserNavigationTarget,
|
||||
): PreviewUrlResolution {
|
||||
if (target.kind === "url") {
|
||||
let parsed: URL | null = null;
|
||||
try {
|
||||
parsed = new URL(normalizePreviewUrl(target.url));
|
||||
} catch {
|
||||
// Preserve the existing direct-navigation behavior so the preview host
|
||||
// reports malformed URL errors through its normal navigation path.
|
||||
}
|
||||
if (parsed && isLoopbackHost(parsed.hostname)) {
|
||||
const environmentUrl = readEnvironmentUrl(environmentId);
|
||||
if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) {
|
||||
return resolveEnvironmentPortTarget(
|
||||
environmentId,
|
||||
{
|
||||
kind: "environment-port",
|
||||
port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
|
||||
protocol: parsed.protocol === "https:" ? "https" : "http",
|
||||
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
|
||||
},
|
||||
environmentUrl,
|
||||
target.url,
|
||||
parsed,
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
requestedUrl: target.url,
|
||||
resolvedUrl: target.url,
|
||||
@@ -125,15 +41,50 @@ export function resolveBrowserNavigationTarget(
|
||||
environmentId,
|
||||
};
|
||||
}
|
||||
return resolveEnvironmentPortTarget(environmentId, target, readEnvironmentUrl(environmentId));
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
const environmentUrl = new URL(connection.httpBaseUrl);
|
||||
if (!isPrivateNetworkHost(environmentUrl.hostname)) {
|
||||
throw new Error(
|
||||
"This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
|
||||
);
|
||||
}
|
||||
const protocol = target.protocol ?? "http";
|
||||
const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
|
||||
const requestedUrl = `${protocol}://localhost:${target.port}${path}`;
|
||||
const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
|
||||
const resolvedHost = normalizedEnvironmentHost.includes(":")
|
||||
? `[${normalizedEnvironmentHost}]`
|
||||
: normalizedEnvironmentHost;
|
||||
const resolved = new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
|
||||
return {
|
||||
requestedUrl,
|
||||
resolvedUrl: resolved.toString(),
|
||||
resolutionKind:
|
||||
normalizedEnvironmentHost === "localhost" || normalizedEnvironmentHost === "127.0.0.1"
|
||||
? "direct"
|
||||
: "direct-private-network",
|
||||
environmentId,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
|
||||
try {
|
||||
const normalizedUrl = normalizePreviewUrl(rawUrl);
|
||||
const parsed = new URL(normalizedUrl);
|
||||
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
const environmentUrl = new URL(connection.httpBaseUrl);
|
||||
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
|
||||
return normalizedUrl;
|
||||
}
|
||||
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
|
||||
return resolveBrowserNavigationTarget(environmentId, {
|
||||
kind: "url",
|
||||
url: normalizedUrl,
|
||||
kind: "environment-port",
|
||||
port,
|
||||
protocol: parsed.protocol === "https:" ? "https" : "http",
|
||||
path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
|
||||
}).resolvedUrl;
|
||||
} catch {
|
||||
return rawUrl;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect, type CSSProperties, type ReactNode } from "react";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./ui/sidebar";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
@@ -55,35 +57,17 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
|
||||
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
|
||||
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
|
||||
return isMacosDesktop && typeof getWindowFullscreenState === "function"
|
||||
? getWindowFullscreenState()
|
||||
: false;
|
||||
});
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
// Settings routes render the settings nav, which lives in the v1 component
|
||||
// and is identical for both sidebars — so v1 stays mounted there.
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
|
||||
const useSidebarV2 = sidebarV2Enabled && !isOnSettings;
|
||||
const macosWindowControlsStyle =
|
||||
isMacosDesktop && !isWindowFullscreen
|
||||
isElectron && isMacPlatform(navigator.platform)
|
||||
? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMacosDesktop) return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge) return;
|
||||
const { getWindowFullscreenState, onWindowFullscreenStateChange } = bridge;
|
||||
if (
|
||||
typeof getWindowFullscreenState !== "function" ||
|
||||
typeof onWindowFullscreenStateChange !== "function"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unsubscribe = onWindowFullscreenStateChange(setIsWindowFullscreen);
|
||||
setIsWindowFullscreen(getWindowFullscreenState());
|
||||
return unsubscribe;
|
||||
}, [isMacosDesktop]);
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
@@ -106,7 +90,14 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
className="border-r border-border bg-card text-foreground"
|
||||
className={
|
||||
// v2 is a darker, higher-contrast panel: it sits below the main
|
||||
// surface instead of matching it, so its bordered cards read as
|
||||
// raised blocks.
|
||||
useSidebarV2
|
||||
? "border-r border-black/15 bg-neutral-100 text-foreground dark:border-white/10 dark:bg-neutral-950"
|
||||
: "border-r border-border bg-card text-foreground"
|
||||
}
|
||||
resizable={{
|
||||
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
|
||||
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
|
||||
@@ -114,7 +105,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
|
||||
}}
|
||||
>
|
||||
<ThreadSidebar />
|
||||
{useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />}
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
|
||||
import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -240,6 +241,21 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center gap-2 px-2.5 pb-3 pt-1 sm:px-3">
|
||||
{/* The submit target leads the run-context strip: this is the one
|
||||
surface where "which project am I about to send this to" must be
|
||||
answered before the first keystroke, especially on drafts.
|
||||
Mirrors the sidebar cards' title bar — favicon + mono name. */}
|
||||
<span className="inline-flex shrink-0 items-center gap-1.5 border border-black/12 py-0.5 pl-1.5 pr-2 dark:border-white/12">
|
||||
<ProjectFavicon
|
||||
environmentId={activeProject.environmentId}
|
||||
cwd={activeProject.workspaceRoot}
|
||||
className="size-3"
|
||||
/>
|
||||
<span className="max-w-32 truncate font-mono text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{activeProject.title}
|
||||
</span>
|
||||
</span>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
|
||||
{isMobile ? (
|
||||
<MobileRunContextSelector
|
||||
envLocked={envLocked}
|
||||
|
||||
@@ -32,7 +32,7 @@ import React, {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components, Options as ReactMarkdownOptions } from "react-markdown";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
serializeTableElementToCsv,
|
||||
serializeTableElementToMarkdown,
|
||||
} from "../markdown-clipboard";
|
||||
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
|
||||
import {
|
||||
normalizeMarkdownLinkDestination,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
@@ -165,24 +164,6 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
|
||||
},
|
||||
} satisfies Parameters<typeof rehypeSanitize>[0];
|
||||
|
||||
const CHAT_MARKDOWN_REMARK_PLUGINS = [
|
||||
remarkGfm,
|
||||
remarkNormalizeListItemIndentation,
|
||||
remarkPreserveCodeMeta,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
remarkGfm,
|
||||
remarkNormalizeListItemIndentation,
|
||||
remarkBreaks,
|
||||
remarkPreserveCodeMeta,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
|
||||
rehypeRaw,
|
||||
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
|
||||
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
const raw = match?.[1] ?? "text";
|
||||
@@ -1564,9 +1545,11 @@ function ChatMarkdown({
|
||||
>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={
|
||||
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
|
||||
lineBreaks
|
||||
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
|
||||
: [remarkGfm, remarkPreserveCodeMeta]
|
||||
}
|
||||
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
|
||||
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
|
||||
components={markdownComponents}
|
||||
urlTransform={markdownUrlTransform}
|
||||
>
|
||||
|
||||
@@ -42,6 +42,8 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
|
||||
@@ -45,6 +45,8 @@ export function buildLocalDraftThread(
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
|
||||
@@ -5040,6 +5040,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.title}
|
||||
activeProjectCwd={activeProject?.workspaceRoot ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
|
||||
@@ -24,6 +24,8 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
|
||||
@@ -16,8 +16,10 @@ import {
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveSidebarV2Status,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortThreadsForSidebarV2,
|
||||
sortProjectsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
@@ -564,6 +566,84 @@ describe("isContextMenuPointerDown", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Status", () => {
|
||||
const session = {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
};
|
||||
|
||||
it("prioritizes approval over a running session", () => {
|
||||
expect(resolveSidebarV2Status({ hasPendingApprovals: true, session })).toBe("approval");
|
||||
});
|
||||
|
||||
it("reports working for running and starting sessions", () => {
|
||||
expect(resolveSidebarV2Status({ hasPendingApprovals: false, session })).toBe("working");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
hasPendingApprovals: false,
|
||||
session: { ...session, status: "starting" as const },
|
||||
}),
|
||||
).toBe("working");
|
||||
});
|
||||
|
||||
it("reports failed only while the session status is error", () => {
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
hasPendingApprovals: false,
|
||||
session: { ...session, status: "error" as const, lastError: "boom" },
|
||||
}),
|
||||
).toBe("failed");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
hasPendingApprovals: false,
|
||||
session: { ...session, status: "stopped" as const, lastError: "persisted" },
|
||||
}),
|
||||
).toBe("ready");
|
||||
expect(
|
||||
resolveSidebarV2Status({
|
||||
hasPendingApprovals: false,
|
||||
session: { ...session, status: "ready" as const, lastError: "persisted" },
|
||||
}),
|
||||
).toBe("ready");
|
||||
});
|
||||
|
||||
it("defaults to ready with no session", () => {
|
||||
expect(resolveSidebarV2Status({ hasPendingApprovals: false, session: null })).toBe("ready");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForSidebarV2", () => {
|
||||
const sortable = (input: { id: string; createdAt: string }) => ({
|
||||
id: input.id,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForSidebarV2([
|
||||
sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }),
|
||||
sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }),
|
||||
sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
|
||||
it("breaks creation-time ties by id so the order is stable", () => {
|
||||
const sorted = sortThreadsForSidebarV2([
|
||||
sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }),
|
||||
]);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
hasActionableProposedPlan: false,
|
||||
@@ -830,6 +910,8 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
|
||||
@@ -357,6 +357,41 @@ export function resolveThreadRowClassName(input: {
|
||||
return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
|
||||
}
|
||||
|
||||
// ── Sidebar v2 status model ─────────────────────────────────────────
|
||||
// Four visual states, three colors: color is reserved for "act now"
|
||||
// (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
// unlabeled resting state — the agent stopped and is waiting on the user,
|
||||
// whether it finished, asked a question, or proposed a plan.
|
||||
export type SidebarV2Status = "approval" | "working" | "failed" | "ready";
|
||||
|
||||
type SidebarV2StatusInput = Pick<SidebarThreadSummary, "hasPendingApprovals" | "session">;
|
||||
|
||||
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
}
|
||||
|
||||
// v2 sort: static creation order, newest thread on top. Activity NEVER
|
||||
// reorders the list — a row holds its position from open until settled, so
|
||||
// the screen only moves at lifecycle transitions. Status (including pending
|
||||
// approval) is carried by each card's edge strip, not by position.
|
||||
export function sortThreadsForSidebarV2<
|
||||
T extends { readonly id: string; readonly createdAt: string },
|
||||
>(threads: readonly T[]): T[] {
|
||||
return [...threads].toSorted(
|
||||
(left, right) =>
|
||||
Date.parse(right.createdAt) - Date.parse(left.createdAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
}): ThreadStatusPill | null {
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
Globe2Icon,
|
||||
LoaderIcon,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -63,7 +62,7 @@ import {
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { Link, useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
|
||||
import { useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router";
|
||||
import {
|
||||
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||
MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||
@@ -74,7 +73,6 @@ import {
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
@@ -168,9 +166,7 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
@@ -178,7 +174,6 @@ import {
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
@@ -191,7 +186,6 @@ import {
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
@@ -201,12 +195,12 @@ import {
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
|
||||
import { primaryServerConfigAtom, primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
@@ -220,7 +214,6 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
created_at: "Created at",
|
||||
@@ -2739,100 +2732,6 @@ function SortableProjectItem({
|
||||
);
|
||||
}
|
||||
|
||||
const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
isElectron,
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="@container/sidebar-header drag-region h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
|
||||
<SidebarTrigger className="md:hidden" />
|
||||
<SidebarBrand />
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
<SidebarHeader className="@container/sidebar-header h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
|
||||
<SidebarTrigger className="md:hidden" />
|
||||
<SidebarBrand />
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
|
||||
function SidebarBrand() {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
|
||||
return (
|
||||
<Link
|
||||
aria-label="Go to threads"
|
||||
className="sidebar-brand ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md text-foreground outline-hidden ring-ring focus-visible:ring-2"
|
||||
to="/"
|
||||
>
|
||||
<T3Wordmark />
|
||||
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||
Code
|
||||
</span>
|
||||
<span className="sidebar-brand-stage shrink-0 items-center whitespace-nowrap rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
|
||||
{stageLabel}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-2.5 w-auto shrink-0 text-foreground"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
const navigate = useNavigate();
|
||||
const { isMobile, setOpenMobile } = useSidebar();
|
||||
const handleSettingsClick = useCallback(() => {
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void navigate({ to: "/settings" });
|
||||
}, [isMobile, navigate, setOpenMobile]);
|
||||
|
||||
return (
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarProviderUpdatePill />
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
|
||||
onClick={handleSettingsClick}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
<span className="text-xs">Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
);
|
||||
});
|
||||
|
||||
interface SidebarProjectsContentProps {
|
||||
showArm64IntelBuildWarning: boolean;
|
||||
arm64IntelBuildWarningDescription: string | null;
|
||||
@@ -3183,9 +3082,8 @@ export default function Sidebar() {
|
||||
return buildPhysicalToLogicalProjectKeyMap({
|
||||
projects: orderedProjects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
});
|
||||
}, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
|
||||
}, [orderedProjects, projectGroupingSettings]);
|
||||
const projectPhysicalKeyByScopedRef = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2049,7 +2049,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"group rounded-[22px] p-px transition-colors duration-200",
|
||||
"group rounded-[13px] p-px transition-colors duration-200",
|
||||
composerProviderState.composerFrameClassName,
|
||||
)}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
@@ -2061,8 +2061,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
"chat-composer-glass rounded-[12px] border transition-colors duration-200 has-focus-visible:border-foreground/40",
|
||||
isDragOverComposer
|
||||
? "border-primary/70 bg-accent/45"
|
||||
: "border-black/12 dark:border-white/12",
|
||||
environmentUnavailable ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
@@ -2087,14 +2089,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
>
|
||||
{!isComposerCollapsedMobile &&
|
||||
(activePendingApproval ? (
|
||||
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
|
||||
<div className="rounded-t-[11px] border-b border-border/65 bg-muted/20">
|
||||
<ComposerPendingApprovalPanel
|
||||
approval={activePendingApproval}
|
||||
pendingCount={pendingApprovals.length}
|
||||
/>
|
||||
</div>
|
||||
) : pendingUserInputs.length > 0 ? (
|
||||
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
|
||||
<div className="rounded-t-[11px] border-b border-border/65 bg-muted/20">
|
||||
<ComposerPendingUserInputPanel
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
@@ -2105,7 +2107,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
/>
|
||||
</div>
|
||||
) : showPlanFollowUpPrompt && activeProposedPlan ? (
|
||||
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
|
||||
<div className="rounded-t-[11px] border-b border-border/65 bg-muted/20">
|
||||
<ComposerPlanFollowUpBanner
|
||||
key={activeProposedPlan.id}
|
||||
planTitle={proposedPlanTitle(activeProposedPlan.planMarkdown) ?? null}
|
||||
@@ -2115,7 +2117,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
{isComposerCollapsedMobile && activePendingApproval ? (
|
||||
<div
|
||||
className="rounded-t-[19px] border-b border-border/65 bg-muted/20"
|
||||
className="rounded-t-[11px] border-b border-border/65 bg-muted/20"
|
||||
data-chat-composer-collapsed-controls="true"
|
||||
>
|
||||
<ComposerPendingApprovalPanel
|
||||
@@ -2132,7 +2134,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
</div>
|
||||
) : isComposerCollapsedMobile && pendingUserInputs.length > 0 ? (
|
||||
<div
|
||||
className="rounded-t-[19px] border-b border-border/65 bg-muted/20"
|
||||
className="rounded-t-[11px] border-b border-border/65 bg-muted/20"
|
||||
data-chat-composer-collapsed-controls="true"
|
||||
>
|
||||
<ComposerPendingUserInputPanel
|
||||
|
||||
@@ -16,6 +16,7 @@ import ProjectScriptsControl, {
|
||||
} from "../ProjectScriptsControl";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../state/environments";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
@@ -24,6 +25,7 @@ interface ChatHeaderProps {
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
activeProjectCwd: string | null;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -58,6 +60,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
activeProjectCwd,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -79,6 +82,27 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
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">
|
||||
{/* The project always leads the header: knowing which project a
|
||||
thread lives in is priority zero, and the thread title alone
|
||||
doesn't answer it. Mirrors the sidebar cards' title bar —
|
||||
favicon + mono uppercase name. */}
|
||||
{activeProjectName ? (
|
||||
<span className="inline-flex shrink-0 items-center gap-2">
|
||||
<span className="inline-flex items-center gap-1.5 border border-black/12 py-0.5 pl-1.5 pr-2 dark:border-white/12">
|
||||
<ProjectFavicon
|
||||
environmentId={activeThreadEnvironmentId}
|
||||
cwd={activeProjectCwd ?? ""}
|
||||
className="size-3"
|
||||
/>
|
||||
<span className="max-w-40 truncate font-mono text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{activeProjectName}
|
||||
</span>
|
||||
</span>
|
||||
<span aria-hidden className="text-muted-foreground/40">
|
||||
/
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user