Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc5065c2f1 | ||
|
|
856a097a5e | ||
|
|
b9cebff072 | ||
|
|
535449600a | ||
|
|
af880a2740 | ||
|
|
351a34b0ac | ||
|
|
da08b588fa | ||
|
|
a2f8028f13 | ||
|
|
f74e7ba83c | ||
|
|
20a3eaa563 | ||
|
|
23d7a3d1c8 | ||
|
|
ab23a82b1d | ||
|
|
069f271b1c | ||
|
|
e17a333d3f | ||
|
|
5dfc78e85e |
No files matched your search
@@ -1,134 +0,0 @@
|
||||
name: Mobile Showcase Screenshots
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: Device platforms to capture
|
||||
required: true
|
||||
default: all
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- ios
|
||||
- android
|
||||
appearance:
|
||||
description: System appearances to capture
|
||||
required: true
|
||||
default: both
|
||||
type: choice
|
||||
options:
|
||||
- both
|
||||
- dark
|
||||
- light
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
jobs:
|
||||
ios:
|
||||
name: iPhone 6.9, iPhone 6.5, and iPad 13
|
||||
if: inputs.platform == 'all' || inputs.platform == 'ios'
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Capture iOS showcase
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate App Store Connect assets
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload iOS screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-store-connect-screenshots
|
||||
path: artifacts/app-store/screenshots/apple/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
android:
|
||||
name: Android phone, 7-inch tablet, and 10-inch tablet
|
||||
if: inputs.platform == 'all' || inputs.platform == 'android'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle cache
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
|
||||
- name: Enable KVM
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
|
||||
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Capture Android showcase
|
||||
uses: reactivecircus/android-emulator-runner@v2
|
||||
with:
|
||||
api-level: 36
|
||||
target: google_apis
|
||||
arch: x86_64
|
||||
profile: pixel_7_pro
|
||||
avd-name: Pixel_10_Pro
|
||||
cores: 8
|
||||
ram-size: 4096M
|
||||
disable-animations: false
|
||||
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate Google Play assets
|
||||
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload Android screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: google-play-screenshots
|
||||
path: artifacts/app-store/screenshots/google-play/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -27,9 +27,6 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -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.
|
||||
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const LAUNCHER_VERSION = 12;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
@@ -220,12 +220,11 @@ function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
|
||||
{
|
||||
@@ -278,25 +277,11 @@ function readJson(path) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
|
||||
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
|
||||
const launcherExecutableName = `${displayName} Launcher`;
|
||||
return {
|
||||
launcherExecutableName,
|
||||
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
|
||||
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
|
||||
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
|
||||
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
@@ -313,8 +298,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
NodeFS.existsSync(launcherBinaryPath) &&
|
||||
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
|
||||
NodeFS.existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
@@ -322,10 +306,10 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return launcherBinaryPath;
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
@@ -337,24 +321,15 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
});
|
||||
patchMainBundleInfoPlist(
|
||||
targetAppBundlePath,
|
||||
iconPath,
|
||||
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
|
||||
);
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
if (isDevelopment) {
|
||||
// Keep Electron's native executable inside the branded bundle. Launching the
|
||||
// node_modules copy makes macOS associate the process (and Dock label) with
|
||||
// Electron.app even though this bundle's Info.plist has the T3 Code name.
|
||||
// Its conventional executable name also keeps Electron's default-app runtime
|
||||
// in development mode instead of making app.isPackaged report true.
|
||||
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
|
||||
return launcherBinaryPath;
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -49,33 +45,4 @@ describe("electron development launcher", () => {
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
|
||||
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
|
||||
const paths = resolveMacLauncherPaths(
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
|
||||
"T3 Code (Dev)",
|
||||
);
|
||||
|
||||
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
|
||||
assert.equal(
|
||||
paths.launcherBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
|
||||
);
|
||||
assert.equal(
|
||||
paths.runtimeElectronBinaryPath,
|
||||
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
|
||||
);
|
||||
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: paths.runtimeElectronBinaryPath,
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {},
|
||||
});
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
});
|
||||
@@ -31,12 +31,6 @@ const TestLayer = ElectronMenu.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
|
||||
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
|
||||
({
|
||||
id: 7,
|
||||
webContents: { getZoomFactor: () => zoomFactor },
|
||||
}) as unknown as Electron.BrowserWindow;
|
||||
|
||||
describe("ElectronMenu", () => {
|
||||
beforeEach(() => {
|
||||
buildFromTemplateMock.mockReset();
|
||||
@@ -76,7 +70,7 @@ describe("ElectronMenu", () => {
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: makeWindow(),
|
||||
window: {} as Electron.BrowserWindow,
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.none(),
|
||||
});
|
||||
@@ -87,24 +81,20 @@ describe("ElectronMenu", () => {
|
||||
|
||||
it.effect("resolves with none when the menu closes without a click", () =>
|
||||
Effect.gen(function* () {
|
||||
let popupOptions: Electron.PopupOptions | undefined;
|
||||
buildFromTemplateMock.mockImplementation(() => ({
|
||||
popup: (options: Electron.PopupOptions) => {
|
||||
popupOptions = options;
|
||||
options.callback?.();
|
||||
},
|
||||
}));
|
||||
|
||||
const electronMenu = yield* ElectronMenu.ElectronMenu;
|
||||
const selectedItemId = yield* electronMenu.showContextMenu({
|
||||
window: makeWindow(2),
|
||||
window: {} as Electron.BrowserWindow,
|
||||
items: [{ id: "copy", label: "Copy" }],
|
||||
position: Option.some({ x: 10.8, y: 20.2 }),
|
||||
});
|
||||
|
||||
assert.isTrue(Option.isNone(selectedItemId));
|
||||
assert.equal(popupOptions?.x, 21);
|
||||
assert.equal(popupOptions?.y, 40);
|
||||
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
|
||||
label: "Copy",
|
||||
enabled: true,
|
||||
|
||||
@@ -94,20 +94,13 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
// Renderer positions arrive in CSS pixels; popup() expects window points, so
|
||||
// page zoom must be factored in or menus drift proportionally to their
|
||||
// distance from the window origin.
|
||||
const normalizePosition = (
|
||||
position: Option.Option<ElectronMenuPosition>,
|
||||
zoomFactor: number,
|
||||
): Option.Option<ElectronMenuPosition> =>
|
||||
Option.filter(
|
||||
position,
|
||||
({ x, y }) =>
|
||||
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
|
||||
).pipe(
|
||||
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
|
||||
);
|
||||
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
|
||||
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
@@ -221,10 +214,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
try {
|
||||
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
|
||||
const popupPosition = normalizePosition(
|
||||
input.position,
|
||||
input.window.webContents.getZoomFactor(),
|
||||
);
|
||||
const popupPosition = normalizePosition(input.position);
|
||||
const popupOptions = Option.match(popupPosition, {
|
||||
onNone: (): Electron.PopupOptions => ({
|
||||
window: input.window,
|
||||
|
||||
@@ -10,7 +10,6 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
|
||||
autoInstallOnAppQuit: true,
|
||||
channel: "latest",
|
||||
disableDifferentialDownload: false,
|
||||
fullChangelog: false,
|
||||
checkForUpdates: vi.fn(() => Promise.resolve(null)),
|
||||
downloadUpdate: vi.fn(() => Promise.resolve([])),
|
||||
on: vi.fn(),
|
||||
@@ -34,7 +33,6 @@ describe("ElectronUpdater", () => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true;
|
||||
autoUpdaterMock.channel = "latest";
|
||||
autoUpdaterMock.disableDifferentialDownload = false;
|
||||
autoUpdaterMock.fullChangelog = false;
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null));
|
||||
autoUpdaterMock.downloadUpdate.mockClear();
|
||||
@@ -100,18 +98,6 @@ describe("ElectronUpdater", () => {
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("sets full changelog mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const updater = yield* ElectronUpdater.ElectronUpdater;
|
||||
|
||||
yield* updater.setFullChangelog(true);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, true);
|
||||
|
||||
yield* updater.setFullChangelog(false);
|
||||
assert.equal(autoUpdaterMock.fullChangelog, false);
|
||||
}).pipe(Effect.provide(ElectronUpdater.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("quit and install failed");
|
||||
|
||||
@@ -66,7 +66,6 @@ export class ElectronUpdater extends Context.Service<
|
||||
readonly setAllowPrerelease: (value: boolean) => Effect.Effect<void>;
|
||||
readonly allowDowngrade: Effect.Effect<boolean>;
|
||||
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
|
||||
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
|
||||
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
|
||||
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
|
||||
@@ -113,11 +112,6 @@ export const make = ElectronUpdater.of({
|
||||
autoUpdater.allowDowngrade = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.fullChangelog = value;
|
||||
return Effect.void;
|
||||
}),
|
||||
setDisableDifferentialDownload: (value) =>
|
||||
Effect.suspend(() => {
|
||||
autoUpdater.disableDifferentialDownload = value;
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -38,7 +38,6 @@ const flushCallbacks = Effect.yieldNow;
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
@@ -74,10 +73,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
@@ -191,7 +186,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
@@ -293,49 +287,6 @@ describe("DesktopUpdates", () => {
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("enables nightly full changelog release notes and broadcasts summaries", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
yield* updates.setChannel("nightly");
|
||||
assert.equal(harness.fullChangelog(), true);
|
||||
|
||||
harness.emit("update-available", {
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
releaseNotes: [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
note: `<h2>What's Changed</h2><ul><li>feat(client): persist offline environment data by <a>@juliusmarminge</a> in <a>#3795</a></li></ul><h2>Full Changelog</h2>`,
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821",
|
||||
},
|
||||
],
|
||||
});
|
||||
yield* flushCallbacks;
|
||||
|
||||
const state = yield* updates.getState;
|
||||
assert.equal(state.status, "available");
|
||||
assert.deepEqual(state.releaseNotes, [
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.766",
|
||||
items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"],
|
||||
},
|
||||
{
|
||||
version: "1.2.4-nightly.20260709.765",
|
||||
items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"],
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("keeps raw updater event failures out of update state", () => {
|
||||
const harness = makeHarness();
|
||||
const cause = new Error(
|
||||
|
||||
@@ -27,7 +27,6 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as IpcChannels from "../ipc/channels.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
@@ -50,10 +49,6 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type;
|
||||
|
||||
const UpdateInfo = Schema.Struct({
|
||||
version: Schema.String,
|
||||
// Left unvalidated on purpose: a malformed release-notes payload must never
|
||||
// fail the decode and block the update state transition. The shape is
|
||||
// validated defensively in normalizeDesktopUpdateReleaseNotes.
|
||||
releaseNotes: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const DownloadProgressInfo = Schema.Struct({
|
||||
@@ -335,12 +330,10 @@ export const make = Effect.gen(function* () {
|
||||
yield* electronUpdater.setChannel(channel);
|
||||
yield* electronUpdater.setAllowPrerelease(allowsPrerelease);
|
||||
yield* electronUpdater.setAllowDowngrade(allowsPrerelease);
|
||||
yield* electronUpdater.setFullChangelog(allowsPrerelease);
|
||||
yield* logUpdaterInfo("using update channel", {
|
||||
channel,
|
||||
allowPrerelease: allowsPrerelease,
|
||||
allowDowngrade: allowsPrerelease,
|
||||
fullChangelog: allowsPrerelease,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -574,15 +567,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const checkedAt = yield* currentIsoTimestamp;
|
||||
const releaseNotes = normalizeDesktopUpdateReleaseNotes(info.releaseNotes, info.version);
|
||||
yield* setState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt, releaseNotes),
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(state, info.version, checkedAt),
|
||||
);
|
||||
yield* Ref.set(lastLoggedDownloadMilestoneRef, -1);
|
||||
yield* logUpdaterInfo("update available", {
|
||||
version: info.version,
|
||||
releaseNoteGroups: releaseNotes.length,
|
||||
});
|
||||
yield* logUpdaterInfo("update available", { version: info.version });
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
|
||||
|
||||
describe("normalizeDesktopUpdateReleaseNotes", () => {
|
||||
it("splits a plain string note into items under the fallback version", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
"## What's changed\n- First fix\n- Second fix",
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["First fix", "Second fix"] }]);
|
||||
});
|
||||
|
||||
it("keeps per-version groups and drops empty ones", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Newer change" },
|
||||
{ version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" },
|
||||
{ version: "1.2.1", note: "- Older change" },
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([
|
||||
{ version: "1.2.3", items: ["Newer change"] },
|
||||
{ version: "1.2.1", items: ["Older change"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("decodes valid HTML entities", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Fix & polish 😀", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Fix & polish 😀"] }]);
|
||||
});
|
||||
|
||||
it("ignores malformed entries instead of throwing", () => {
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[
|
||||
{ version: "1.2.3", note: "- Valid change" },
|
||||
{ version: 42, note: "- Bad version type" },
|
||||
{ version: "1.2.1", note: { html: "<p>object note</p>" } },
|
||||
"not an object",
|
||||
null,
|
||||
],
|
||||
"1.2.3",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.2.3", items: ["Valid change"] }]);
|
||||
});
|
||||
|
||||
it("returns non-empty groups even when preceded by many boilerplate-only groups", () => {
|
||||
const boilerplate = Array.from({ length: 7 }, (_, index) => ({
|
||||
version: `1.3.${9 - index}`,
|
||||
note: "Full changelog: https://example.com/compare/x...y",
|
||||
}));
|
||||
const notes = normalizeDesktopUpdateReleaseNotes(
|
||||
[...boilerplate, { version: "1.3.2", note: "- Older but real change" }],
|
||||
"1.3.9",
|
||||
);
|
||||
expect(notes).toEqual([{ version: "1.3.2", items: ["Older but real change"] }]);
|
||||
});
|
||||
|
||||
it("does not throw on out-of-range numeric entities and keeps the literal", () => {
|
||||
expect(() =>
|
||||
normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0"),
|
||||
).not.toThrow();
|
||||
const notes = normalizeDesktopUpdateReleaseNotes("- Broken entity �", "1.0.0");
|
||||
expect(notes).toEqual([{ version: "1.0.0", items: ["Broken entity �"] }]);
|
||||
});
|
||||
});
|
||||
@@ -1,125 +0,0 @@
|
||||
import type { DesktopUpdateReleaseNote } from "@t3tools/contracts";
|
||||
|
||||
interface ElectronReleaseNoteInfo {
|
||||
readonly version: string;
|
||||
readonly note: string | null | undefined;
|
||||
}
|
||||
|
||||
function isElectronReleaseNoteInfo(value: unknown): value is ElectronReleaseNoteInfo {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const candidate = value as { readonly version?: unknown; readonly note?: unknown };
|
||||
return (
|
||||
typeof candidate.version === "string" &&
|
||||
(typeof candidate.note === "string" || candidate.note === null || candidate.note === undefined)
|
||||
);
|
||||
}
|
||||
|
||||
const MAX_RELEASE_NOTE_GROUPS = 6;
|
||||
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
|
||||
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
|
||||
|
||||
const HTML_ENTITY_REPLACEMENTS: Readonly<Record<string, string>> = {
|
||||
amp: "&",
|
||||
apos: "'",
|
||||
gt: ">",
|
||||
lt: "<",
|
||||
nbsp: " ",
|
||||
quot: '"',
|
||||
};
|
||||
|
||||
function decodeCodePoint(codePoint: number, entity: string): string {
|
||||
// String.fromCodePoint throws RangeError outside the valid Unicode range, and
|
||||
// Number.isFinite alone lets oversized values (e.g. �) through.
|
||||
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
|
||||
return `&${entity};`;
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
}
|
||||
|
||||
function decodeHtmlEntity(entity: string): string {
|
||||
const named = HTML_ENTITY_REPLACEMENTS[entity];
|
||||
if (named) return named;
|
||||
if (entity.startsWith("#x")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
|
||||
}
|
||||
if (entity.startsWith("#")) {
|
||||
return decodeCodePoint(Number.parseInt(entity.slice(1), 10), entity);
|
||||
}
|
||||
return `&${entity};`;
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(input: string): string {
|
||||
return input.replace(/&([a-zA-Z]+|#\d+|#x[0-9a-fA-F]+);/g, (_, entity: string) =>
|
||||
decodeHtmlEntity(entity),
|
||||
);
|
||||
}
|
||||
|
||||
function stripMarkup(input: string): string {
|
||||
return decodeHtmlEntities(
|
||||
input
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<li\b[^>]*>/gi, "\n- ")
|
||||
.replace(/<\/(?:p|div|li|h[1-6]|ul|ol|blockquote)>/gi, "\n")
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||
.replace(/\*\*([^*]+)\*\*/g, "$1"),
|
||||
);
|
||||
}
|
||||
|
||||
function truncateReleaseNoteItem(item: string): string {
|
||||
if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item;
|
||||
return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`;
|
||||
}
|
||||
|
||||
function isIgnoredReleaseNoteLine(line: string): boolean {
|
||||
const normalized = line
|
||||
.toLowerCase()
|
||||
.replace(/[*_`#]/g, "")
|
||||
.trim();
|
||||
return (
|
||||
normalized === "" ||
|
||||
normalized === "what's changed" ||
|
||||
normalized === "whats changed" ||
|
||||
normalized === "full changelog" ||
|
||||
normalized === "new contributors" ||
|
||||
normalized.startsWith("compare: ") ||
|
||||
normalized.includes("/compare/")
|
||||
);
|
||||
}
|
||||
|
||||
function extractReleaseNoteItems(note: string | null | undefined): ReadonlyArray<string> {
|
||||
if (!note) return [];
|
||||
|
||||
const items: string[] = [];
|
||||
for (const rawLine of stripMarkup(note).split("\n")) {
|
||||
const item = rawLine
|
||||
.trim()
|
||||
.replace(/^[-*]\s+/, "")
|
||||
.replace(/^\d+[.)]\s+/, "")
|
||||
.replace(/\s+/g, " ");
|
||||
if (isIgnoredReleaseNoteLine(item)) continue;
|
||||
items.push(truncateReleaseNoteItem(item));
|
||||
if (items.length >= MAX_RELEASE_NOTE_ITEMS_PER_GROUP) break;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function normalizeDesktopUpdateReleaseNotes(
|
||||
releaseNotes: unknown,
|
||||
fallbackVersion: string,
|
||||
): ReadonlyArray<DesktopUpdateReleaseNote> {
|
||||
const rawNotes =
|
||||
typeof releaseNotes === "string"
|
||||
? [{ version: fallbackVersion, note: releaseNotes }]
|
||||
: Array.isArray(releaseNotes)
|
||||
? releaseNotes.filter(isElectronReleaseNoteInfo)
|
||||
: [];
|
||||
|
||||
return rawNotes
|
||||
.map((entry) => ({
|
||||
version: entry.version,
|
||||
items: extractReleaseNoteItems(entry.note),
|
||||
}))
|
||||
.filter((entry) => entry.items.length > 0)
|
||||
.slice(0, MAX_RELEASE_NOTE_GROUPS);
|
||||
}
|
||||
@@ -118,12 +118,6 @@ describe("updateMachine", () => {
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const releaseNotes = [
|
||||
{
|
||||
version: "1.1.0",
|
||||
items: ["feat: add update release notes"],
|
||||
},
|
||||
];
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
@@ -132,33 +126,15 @@ describe("updateMachine", () => {
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
releaseNotes,
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(available.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.releaseNotes).toBe(releaseNotes);
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("clears release notes when checking again", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"),
|
||||
enabled: true,
|
||||
status: "available",
|
||||
availableVersion: "1.1.0-nightly.1",
|
||||
releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"] }],
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.releaseNotes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateReleaseNote,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -30,7 +29,6 @@ export function createInitialDesktopUpdateState(
|
||||
runningUnderArm64Translation: runtimeInfo.runningUnderArm64Translation,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
@@ -47,7 +45,6 @@ export function reduceDesktopUpdateStateOnCheckStart(
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
releaseNotes: [],
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
@@ -75,14 +72,12 @@ export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote> = [],
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
releaseNotes,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
@@ -100,7 +95,6 @@ export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
|
||||
@@ -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 = () => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
formatNodePtyProbeFailureReason,
|
||||
formatWslShellTransportFailureReason,
|
||||
parseNodePath,
|
||||
parseNodeVersion,
|
||||
parseResolvedPath,
|
||||
parseToolchainReport,
|
||||
probeWslDistros,
|
||||
@@ -174,29 +173,6 @@ describe("parseNodePath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseNodeVersion", () => {
|
||||
it("extracts the node version from a nodeVersion: line", () => {
|
||||
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
|
||||
});
|
||||
|
||||
it("returns null when the version value is empty", () => {
|
||||
expect(parseNodeVersion("nodeVersion:")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when there is no nodeVersion line at all", () => {
|
||||
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores surrounding noise and trims whitespace", () => {
|
||||
const stdout = [
|
||||
"some preamble noise",
|
||||
" nodeVersion:22.16.0 ",
|
||||
"nodePath:/usr/bin/node",
|
||||
].join("\n");
|
||||
expect(parseNodeVersion(stdout)).toBe("22.16.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseResolvedPath", () => {
|
||||
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
|
||||
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
|
||||
|
||||
@@ -32,11 +32,7 @@ export interface EnsureWslNodePtyOptions {
|
||||
}
|
||||
|
||||
export type EnsureWslNodePtyResult =
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly nodePath: string;
|
||||
readonly resolvedPath: string;
|
||||
}
|
||||
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
@@ -226,7 +222,6 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null
|
||||
const NODE_PTY_PROBE_SCRIPT = (
|
||||
linuxServerDir: string,
|
||||
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
@@ -323,16 +318,6 @@ export const parseNodePath = (stdout: string): string | null => {
|
||||
return path ?? null;
|
||||
};
|
||||
|
||||
export const parseNodeVersion = (stdout: string): string | null => {
|
||||
const version = stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith("nodeVersion:"))
|
||||
.map((line) => line.slice("nodeVersion:".length).trim())
|
||||
.find((value) => value.length > 0);
|
||||
return version ?? null;
|
||||
};
|
||||
|
||||
// Captures the login-shell PATH after the shared resolver has loaded version
|
||||
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
|
||||
// paths containing spaces or apostrophes can be forwarded as one env argv.
|
||||
@@ -419,11 +404,7 @@ const ensureNodePtyImpl = (
|
||||
|
||||
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
|
||||
if (transportFailureReason !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: transportFailureReason,
|
||||
fatal: false,
|
||||
} as const;
|
||||
return { ok: false, reason: transportFailureReason, fatal: false } as const;
|
||||
}
|
||||
|
||||
// No node at all, even after the shared resolver repaired PATH. Surface
|
||||
@@ -476,31 +457,12 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (probe.exitCode === 0) {
|
||||
const rawVersion = parseNodeVersion(probe.stdout);
|
||||
if (
|
||||
rawVersion !== null &&
|
||||
options.nodeEngineRange &&
|
||||
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
|
||||
) {
|
||||
const range = options.nodeEngineRange.trim();
|
||||
return {
|
||||
ok: false,
|
||||
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
return { ok: true, nodePath, resolvedPath } as const;
|
||||
}
|
||||
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
|
||||
|
||||
if (options.allowBuild !== true) {
|
||||
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
|
||||
if (packagedProbeFailure !== null) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: packagedProbeFailure,
|
||||
fatal: true,
|
||||
} as const;
|
||||
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
|
||||
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 665 B After Width: | Height: | Size: 649 B |
@@ -1,4 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
|
||||
<path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
|
||||
<path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 948 B |
@@ -1,6 +1,6 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "14k+",
|
||||
githubStars: "12k+",
|
||||
users: "100,000",
|
||||
} as const;
|
||||
@@ -33,9 +33,6 @@ const mobileEndorsementRows = [
|
||||
<span class="hero-float-mark hf-cursor" title="Cursor">
|
||||
<img src="/harnesses/cursor_light.svg" alt="" />
|
||||
</span>
|
||||
<span class="hero-float-mark hf-grok" title="Grok">
|
||||
<img src="/harnesses/grok-dark.svg" alt="" />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="container hero-inner">
|
||||
@@ -44,7 +41,7 @@ const mobileEndorsementRows = [
|
||||
</h1>
|
||||
|
||||
<p class="hero-sub">
|
||||
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
|
||||
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
|
||||
Bring your own subscription. Fork the whole thing.
|
||||
</p>
|
||||
|
||||
@@ -176,7 +173,7 @@ const mobileEndorsementRows = [
|
||||
<h2>Bring your own sub</h2>
|
||||
<p>
|
||||
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
|
||||
Cursor, or Grok with the credentials you already have — we orchestrate
|
||||
or Cursor with the credentials you already have — we orchestrate
|
||||
them, you keep your plan.
|
||||
</p>
|
||||
</div>
|
||||
@@ -210,13 +207,6 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Grok CLI</div>
|
||||
<div class="harness-tag">grok login</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="harness-footer">
|
||||
@@ -625,9 +615,8 @@ const mobileEndorsementRows = [
|
||||
|
||||
.hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
|
||||
.hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
|
||||
.hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
|
||||
.hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
|
||||
@@ -636,7 +625,6 @@ const mobileEndorsementRows = [
|
||||
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
|
||||
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
|
||||
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
|
||||
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
|
||||
}
|
||||
|
||||
@media (max-width: 820px) {
|
||||
@@ -671,18 +659,17 @@ const mobileEndorsementRows = [
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
|
||||
/* Two above the title, two flanking the call-to-action area. */
|
||||
.hero-float-mark.hf-claude {
|
||||
top: 44px;
|
||||
left: 10px;
|
||||
transform: rotate(-10deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 240px;
|
||||
left: 4px;
|
||||
right: auto;
|
||||
transform: rotate(-4deg);
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode {
|
||||
@@ -692,12 +679,6 @@ const mobileEndorsementRows = [
|
||||
transform: rotate(-6deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-codex {
|
||||
top: 44px;
|
||||
right: 10px;
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 474px;
|
||||
right: 4px;
|
||||
@@ -707,14 +688,6 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 220px;
|
||||
left: 0;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-opencode,
|
||||
.hero-float-mark.hf-cursor {
|
||||
top: 580px;
|
||||
@@ -731,7 +704,6 @@ const mobileEndorsementRows = [
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-grok img,
|
||||
.hero-float-mark.hf-opencode img,
|
||||
.hero-float-mark.hf-cursor img {
|
||||
width: 30px;
|
||||
@@ -778,7 +750,7 @@ const mobileEndorsementRows = [
|
||||
|
||||
.harness-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
@@ -1233,10 +1205,6 @@ const mobileEndorsementRows = [
|
||||
.harness-grid { grid-template-columns: 1fr 1fr; }
|
||||
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
|
||||
.harness:nth-child(5):last-child {
|
||||
grid-column: 1 / -1;
|
||||
border-right: 0;
|
||||
}
|
||||
.git-inner { grid-template-columns: 1fr; gap: 40px; }
|
||||
.open-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { ExpoConfig } from "expo/config";
|
||||
|
||||
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
|
||||
|
||||
type AppVariant = "development" | "preview" | "production";
|
||||
@@ -14,8 +13,6 @@ const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
|
||||
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
|
||||
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
|
||||
|
||||
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
|
||||
|
||||
if (
|
||||
isIosPersonalTeamBuild &&
|
||||
(!personalTeamBundleIdentifier ||
|
||||
@@ -27,31 +24,20 @@ if (
|
||||
}
|
||||
|
||||
const DEVELOPMENT_ASSETS = {
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
|
||||
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
|
||||
appIcon: "./assets/splash-icon-dev.png",
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
splashIcon: "./assets/splash-icon-dev.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
|
||||
androidAdaptiveBackgroundColor: "#00639B",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#00639B",
|
||||
} as const;
|
||||
|
||||
const PREVIEW_ASSETS = {
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
|
||||
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
|
||||
androidAdaptiveBackgroundColor: "#111533",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
androidNotificationIcon: "./assets/android-notification-icon.png",
|
||||
androidNotificationColor: "#7565C7",
|
||||
} as const;
|
||||
|
||||
const RELEASE_ASSETS = {
|
||||
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
|
||||
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
|
||||
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
|
||||
appIcon: "./assets/splash-icon-prod.png",
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
splashIcon: "./assets/splash-icon-prod.png",
|
||||
androidAdaptiveForeground: "./assets/android-icon-mark.png",
|
||||
androidAdaptiveBackgroundColor: "#000000",
|
||||
androidMonochromeIcon: "./assets/android-icon-mark.png",
|
||||
@@ -74,7 +60,7 @@ const VARIANT_CONFIG = {
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
assets: PREVIEW_ASSETS,
|
||||
assets: RELEASE_ASSETS,
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
@@ -98,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",
|
||||
@@ -111,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.
|
||||
@@ -128,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.
|
||||
@@ -181,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).
|
||||
@@ -243,9 +202,6 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-sqlite",
|
||||
...(isIosPersonalTeamBuild
|
||||
? [sharingPlugin]
|
||||
: ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
|
||||
|
After Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 920 B After Width: | Height: | Size: 920 B |
|
After Width: | Height: | Size: 10 MiB |
|
After Width: | Height: | Size: 1.7 MiB |
@@ -6,40 +6,35 @@
|
||||
{
|
||||
"layers": [
|
||||
{
|
||||
"glass": true,
|
||||
"image-name": "text.svg",
|
||||
"name": "Text",
|
||||
"hidden": false,
|
||||
"image-name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr.png",
|
||||
"name": "gpt-image-1.5-jd70szmrd03p36z4zv48ycsbax81egvr",
|
||||
"position": {
|
||||
"scale": 8.5,
|
||||
"scale": 1.1,
|
||||
"translation-in-points": [0, 0]
|
||||
}
|
||||
},
|
||||
{
|
||||
"glass": false,
|
||||
"image-name": "annotations.svg",
|
||||
"name": "Annotations",
|
||||
"image-name": "T3.svg",
|
||||
"name": "T3",
|
||||
"position": {
|
||||
"scale": 8.5,
|
||||
"scale": 10,
|
||||
"translation-in-points": [0, 0]
|
||||
}
|
||||
},
|
||||
{
|
||||
"glass": true,
|
||||
"image-name": "background.svg",
|
||||
"name": "Background",
|
||||
"position": {
|
||||
"scale": 8.1,
|
||||
"translation-in-points": [0, 0]
|
||||
}
|
||||
"hidden": true,
|
||||
"image-name": "Texturelabs_Paper_381XL.jpg",
|
||||
"name": "Texturelabs_Paper_381XL"
|
||||
}
|
||||
],
|
||||
"shadow": {
|
||||
"kind": "neutral",
|
||||
"opacity": 0.6
|
||||
"opacity": 0.5
|
||||
},
|
||||
"translucency": {
|
||||
"enabled": true,
|
||||
"value": 0.2
|
||||
"value": 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 920 B |
@@ -6,8 +6,8 @@
|
||||
{
|
||||
"layers": [
|
||||
{
|
||||
"image-name": "text.svg",
|
||||
"name": "Text",
|
||||
"image-name": "T3.svg",
|
||||
"name": "T3",
|
||||
"position": {
|
||||
"scale": 10,
|
||||
"translation-in-points": [0, 0]
|
||||
|
After Width: | Height: | Size: 2.0 MiB |
|
After Width: | Height: | Size: 302 KiB |
@@ -1,6 +1,5 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import { LogBox } from "react-native";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
|
||||
import App from "./src/App";
|
||||
@@ -9,8 +8,4 @@ import App from "./src/App";
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
LogBox.ignoreAllLogs();
|
||||
}
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -7,32 +7,6 @@ class T3NativeControlsModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
appContext.currentActivity?.intent?.getStringExtra("showcasePairingUrl")
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") {
|
||||
val storedScene = appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-scene")
|
||||
?.takeIf { it.isFile }
|
||||
?.readText()
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
storedScene ?: appContext.currentActivity?.intent?.getStringExtra("showcaseScene")
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
// Android app data is cleared by the host runner before launch.
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { scene: String ->
|
||||
appContext.reactContext
|
||||
?.filesDir
|
||||
?.resolve("t3-showcase-ready")
|
||||
?.writeText(scene)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView::class) {
|
||||
Prop("label") { view: T3HeaderButtonView, label: String ->
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -1,48 +1,9 @@
|
||||
import ExpoModulesCore
|
||||
import Security
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
Function("getShowcasePairingUrl") {
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcasePairingUrl"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("getShowcaseScene") { () -> String? in
|
||||
let scenePath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseScene"
|
||||
if let storedScene = try? String(contentsOfFile: scenePath, encoding: .utf8)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines), !storedScene.isEmpty {
|
||||
return storedScene
|
||||
}
|
||||
let arguments = ProcessInfo.processInfo.arguments
|
||||
guard
|
||||
let flagIndex = arguments.firstIndex(of: "--showcaseScene"),
|
||||
arguments.indices.contains(flagIndex + 1)
|
||||
else {
|
||||
return nil as String?
|
||||
}
|
||||
return arguments[flagIndex + 1]
|
||||
}
|
||||
|
||||
Function("prepareShowcaseCapture") {
|
||||
for itemClass in [kSecClassGenericPassword, kSecClassInternetPassword] {
|
||||
SecItemDelete([kSecClass as String: itemClass] as CFDictionary)
|
||||
}
|
||||
}
|
||||
|
||||
Function("markShowcaseReady") { (scene: String) in
|
||||
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
|
||||
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
|
||||
@@ -30,10 +30,6 @@ class T3TerminalModule : Module() {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -76,17 +76,6 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus: Boolean = true
|
||||
set(value) {
|
||||
field = value
|
||||
if (value) {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputView.clearFocus()
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColorHex: String = "#24292E"
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -379,13 +368,6 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
inputMethodManager?.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun hideKeyboard() {
|
||||
val inputMethodManager = context.getSystemService(
|
||||
Context.INPUT_METHOD_SERVICE
|
||||
) as? InputMethodManager
|
||||
inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
|
||||
private fun applyTheme() {
|
||||
setBackgroundColor(backgroundColorValue)
|
||||
container.setBackgroundColor(backgroundColorValue)
|
||||
|
||||
@@ -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) {
|
||||
@@ -27,10 +27,6 @@ public class T3TerminalModule: Module {
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in
|
||||
view.autoFocus = autoFocus
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -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)?
|
||||
@@ -248,17 +233,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var autoFocus = true {
|
||||
didSet {
|
||||
guard oldValue != autoFocus else { return }
|
||||
if autoFocus {
|
||||
requestKeyboardFocus()
|
||||
} else {
|
||||
inputField.resignFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
@@ -370,7 +344,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
|
||||
guard window != nil, autoFocus else { return }
|
||||
guard window != nil else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.requestKeyboardFocus()
|
||||
}
|
||||
@@ -378,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
|
||||
}
|
||||
|
||||
@@ -388,7 +360,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
|
||||
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
emitInput(TerminalInputSequence.carriageReturn)
|
||||
emitInput("\n")
|
||||
textField.text = ""
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -11,8 +11,6 @@
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
"start:prod": "APP_VARIANT=production expo start",
|
||||
"showcase": "APP_VARIANT=development EXPO_PUBLIC_SHOWCASE=1 expo start --dev-client --scheme t3code-dev --clear",
|
||||
"screenshots": "node ../../scripts/mobile-showcase.ts",
|
||||
"android": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
"android:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && REACT_NATIVE_PACKAGER_HOSTNAME=localhost expo run:android",
|
||||
"android:preview": "APP_VARIANT=preview EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
|
||||
@@ -93,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,
|
||||
);
|
||||
};
|
||||
@@ -11,8 +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 { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
@@ -22,20 +20,13 @@ import { useThemeColor } from "./lib/useThemeColor";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
|
||||
prepareNativeShowcaseCapture();
|
||||
}
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
// The Expo dev client launches the app via
|
||||
// <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);
|
||||
@@ -67,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,12 +10,10 @@ 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";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { renderCompactBrandTitle } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
@@ -49,17 +47,11 @@ import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnv
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
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";
|
||||
|
||||
@@ -283,30 +275,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);
|
||||
@@ -315,7 +289,6 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
@@ -378,8 +351,7 @@ export const RootStack = createNativeStackNavigator({
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
title: "T3 Code",
|
||||
title: "Threads",
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
|
||||
@@ -1,23 +1,13 @@
|
||||
import Constants from "expo-constants";
|
||||
import { Image } from "expo-image";
|
||||
import { View } from "react-native";
|
||||
import { Image, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
const BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
const DEFAULT_STAGE_LABEL =
|
||||
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
|
||||
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
|
||||
|
||||
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
|
||||
const compact = props.compact ?? false;
|
||||
const iconSize = compact ? 32 : 44;
|
||||
const stageLabel = props.stageLabel ?? DEFAULT_STAGE_LABEL;
|
||||
const stageLabel = props.stageLabel ?? "Alpha";
|
||||
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
export function CompactBrandTitle() {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
|
||||
return (
|
||||
<View
|
||||
aria-level={1}
|
||||
accessibilityLabel="T3 Code"
|
||||
accessible
|
||||
role="heading"
|
||||
style={{ alignItems: "center", flexDirection: "row", gap: 6 }}
|
||||
>
|
||||
<T3Wordmark color={iconColor} height={11} />
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Medium",
|
||||
fontSize: 14,
|
||||
letterSpacing: -0.35,
|
||||
}}
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function renderCompactBrandTitle() {
|
||||
return <CompactBrandTitle />;
|
||||
}
|
||||
@@ -33,8 +33,6 @@ import { type RelayEnvironmentView, useConnectionController } from "./useConnect
|
||||
export function CloudEnvironmentRows(props: {
|
||||
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
|
||||
readonly showcaseSignedIn?: boolean;
|
||||
/**
|
||||
* Hide the "T3 Connect" section title + refresh button for hosts that
|
||||
* provide their own chrome (the onboarding sheet's native header and
|
||||
@@ -45,8 +43,7 @@ export function CloudEnvironmentRows(props: {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const availableCloudEnvironments = controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -67,7 +64,7 @@ export function CloudEnvironmentRows(props: {
|
||||
|
||||
const showHeader = props.showHeader ?? true;
|
||||
|
||||
if (!(props.showcaseSignedIn ?? isSignedIn)) return null;
|
||||
if (!isSignedIn) return null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -96,22 +96,5 @@ describe("isPendingNativeViewRegistration", () => {
|
||||
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPendingNativeViewRegistration(
|
||||
new Error(
|
||||
"Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isNativeReviewDiffDrawEvent", () => {
|
||||
it("accepts only native events emitted after diff rows draw", async () => {
|
||||
const { isNativeReviewDiffDrawEvent } = await import("./nativeReviewDiffSurface");
|
||||
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "draw-metrics" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "visible-range" })).toBe(true);
|
||||
expect(isNativeReviewDiffDrawEvent({ message: "rows-decoded" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -149,10 +149,6 @@ export interface NativeReviewDiffViewHandle {
|
||||
readonly scrollToTop: (animated?: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
|
||||
return payload.message === "draw-metrics" || payload.message === "visible-range";
|
||||
}
|
||||
|
||||
interface NativeReviewDiffViewRef {
|
||||
readonly setRowsJson: (rowsJson: string) => Promise<void>;
|
||||
readonly setTokensJson: (tokensJson: string) => Promise<void>;
|
||||
@@ -174,11 +170,9 @@ let nativeReviewDiffViewResolutionFailed = false;
|
||||
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
|
||||
|
||||
export function isPendingNativeViewRegistration(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return (
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
|
||||
(error.message.includes("Unable to find the class") &&
|
||||
error.message.includes("T3ReviewDiffView view with tag"))
|
||||
error instanceof Error &&
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -29,7 +28,8 @@ export function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
@@ -87,9 +87,7 @@ export function HomeRouteScreen() {
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "T3 Code", headerTitle: renderCompactBrandTitle }}
|
||||
/>
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
searchQuery={searchQuery}
|
||||
@@ -114,6 +112,8 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
|
||||
@@ -14,16 +14,18 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, View } from "react-native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Platform, Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
@@ -32,6 +34,8 @@ import {
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import { ThreadListV2Row } from "../threads/thread-list-v2-items";
|
||||
import { buildThreadListV2Items, type ThreadListV2Item } from "../threads/threadListV2";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
@@ -73,6 +77,9 @@ interface HomeScreenProps {
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** Resolves true iff the settle was dispatched and succeeded. */
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -81,6 +88,10 @@ interface HomeScreenProps {
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
// v2 settled-tail paging: recent history is the common lookup; the deep
|
||||
// tail stays behind an explicit Show more.
|
||||
const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
@@ -162,11 +173,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const effectiveGroupDisplayStates = useMemo(() => {
|
||||
const next = new Map(groupDisplayStates);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
@@ -266,6 +281,207 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const projectByKey = useMemo(() => {
|
||||
const map = new Map<string, EnvironmentProject>();
|
||||
for (const project of props.projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project);
|
||||
}
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
// Thread List v2 (beta): one flat list in creation order, no grouping.
|
||||
// Settled threads collapse into a recency tail below the card block.
|
||||
// Settle = archive in the client-only model, and the live shell stream
|
||||
// drops archived threads — merge them back from the archived snapshot so
|
||||
// they render as the settled tail. Live shells win on overlap.
|
||||
const archivedEnvironmentIds = useMemo(
|
||||
() =>
|
||||
threadListV2Enabled ? props.environments.map((environment) => environment.environmentId) : [],
|
||||
[props.environments, threadListV2Enabled],
|
||||
);
|
||||
const { snapshots: archivedSnapshots } = useArchivedThreadSnapshots(archivedEnvironmentIds);
|
||||
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
|
||||
// closed PR auto-settles its thread on the next partition (mirrors web).
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
// Bridge the gap between the live stream dropping a just-settled thread
|
||||
// and the archived snapshot returning it: hold the shell we settled,
|
||||
// marked archived, until the snapshot carries it. Held explicitly at
|
||||
// settle time so deleted threads are never resurrected.
|
||||
const [settledHolds, setSettledHolds] = useState<ReadonlyMap<string, EnvironmentThreadShell>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const handleSettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
setSettledHolds((current) =>
|
||||
new Map(current).set(threadKey, {
|
||||
...thread,
|
||||
archivedAt: thread.archivedAt ?? new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
void (async () => {
|
||||
// Roll the optimistic hold back if the settle was blocked or failed —
|
||||
// otherwise a never-archived thread would render settled forever.
|
||||
const succeeded = await props.onSettleThread(thread);
|
||||
if (!succeeded) {
|
||||
setSettledHolds((current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
})();
|
||||
},
|
||||
[props.onSettleThread],
|
||||
);
|
||||
// Delete and un-settle both invalidate any hold for the thread.
|
||||
const dropSettledHold = useCallback((thread: EnvironmentThreadShell) => {
|
||||
setSettledHolds((current) => {
|
||||
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (!current.has(threadKey)) return current;
|
||||
const next = new Map(current);
|
||||
next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const handleDeleteThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
dropSettledHold(thread);
|
||||
props.onDeleteThread(thread);
|
||||
},
|
||||
[dropSettledHold, props.onDeleteThread],
|
||||
);
|
||||
const handleUnsettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
dropSettledHold(thread);
|
||||
props.onUnsettleThread(thread);
|
||||
},
|
||||
[dropSettledHold, props.onUnsettleThread],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (settledHolds.size === 0) return;
|
||||
const covered = new Set<string>();
|
||||
for (const { environmentId, snapshot } of archivedSnapshots) {
|
||||
for (const thread of snapshot.threads) {
|
||||
covered.add(scopedThreadKey(environmentId, thread.id));
|
||||
}
|
||||
}
|
||||
if ([...settledHolds.keys()].some((threadKey) => covered.has(threadKey))) {
|
||||
setSettledHolds((current) => {
|
||||
const next = new Map(current);
|
||||
for (const threadKey of covered) next.delete(threadKey);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [archivedSnapshots, settledHolds]);
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
// context changes so environment/search flips never inherit a deep page.
|
||||
const [settledVisibleCount, setSettledVisibleCount] = useState(
|
||||
THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
|
||||
);
|
||||
const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${props.searchQuery.trim()}`;
|
||||
const lastSettledResetKeyRef = useRef(settledResetKey);
|
||||
if (lastSettledResetKeyRef.current !== settledResetKey) {
|
||||
lastSettledResetKeyRef.current = settledResetKey;
|
||||
setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
|
||||
}
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
|
||||
[],
|
||||
);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
|
||||
const merged = new Map<string, EnvironmentThreadShell>();
|
||||
for (const { environmentId, snapshot } of archivedSnapshots) {
|
||||
for (const thread of snapshot.threads) {
|
||||
merged.set(scopedThreadKey(environmentId, thread.id), { ...thread, environmentId });
|
||||
}
|
||||
}
|
||||
for (const thread of props.threads) {
|
||||
merged.set(scopedThreadKey(thread.environmentId, thread.id), thread);
|
||||
}
|
||||
for (const [threadKey, shell] of settledHolds) {
|
||||
if (merged.has(threadKey)) continue;
|
||||
merged.set(threadKey, shell);
|
||||
}
|
||||
return buildThreadListV2Items({
|
||||
threads: [...merged.values()],
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
changeRequestStateByKey,
|
||||
settledLimit: settledVisibleCount,
|
||||
});
|
||||
}, [
|
||||
changeRequestStateByKey,
|
||||
settledHolds,
|
||||
settledVisibleCount,
|
||||
archivedSnapshots,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threads,
|
||||
threadListV2Enabled,
|
||||
]);
|
||||
const threadListV2Items = threadListV2Layout.items;
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: LegendListRenderItemProps<ThreadListV2Item>) => (
|
||||
<ThreadListV2Row
|
||||
thread={item.thread}
|
||||
variant={item.variant}
|
||||
showSettledDivider={item.showSettledDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={handleDeleteThread}
|
||||
onSettleThread={handleSettleThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(item.thread.environmentId, item.thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
),
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
handleSettleThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onSelectThread,
|
||||
],
|
||||
);
|
||||
const v2KeyExtractor = useCallback(
|
||||
(item: ThreadListV2Item) => `${item.thread.environmentId}:${item.thread.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
@@ -359,8 +575,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
// v2 shows archived threads as its settled tail, so an archived-only
|
||||
// workspace still has a list to render there.
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
props.threads.some((thread) => thread.archivedAt === null) ||
|
||||
props.pendingTasks.length > 0 ||
|
||||
(threadListV2Enabled && threadListV2Items.length > 0);
|
||||
const hasResults = projectGroups.length > 0;
|
||||
const selectedEnvironmentLabel =
|
||||
props.selectedEnvironmentId === null
|
||||
@@ -426,6 +646,28 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
</>
|
||||
);
|
||||
|
||||
// v2 renders queued offline tasks above the thread cards — they are not
|
||||
// thread shells, so the v2 item builder never sees them, but they must
|
||||
// stay visible and deletable while their environment is offline.
|
||||
const v2ListHeader = (
|
||||
<>
|
||||
{listHeader}
|
||||
{props.pendingTasks.map((pendingTask, index) => (
|
||||
<PendingTaskListRow
|
||||
key={pendingTask.message.messageId}
|
||||
variant="compact"
|
||||
pendingTask={pendingTask}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[pendingTask.message.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
isLast={index === props.pendingTasks.length - 1}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
@@ -439,6 +681,56 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
)
|
||||
) : null;
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<LegendList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
|
||||
extraData={projectByKey}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Show ${Math.min(threadListV2Layout.hiddenSettledCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
|
||||
onPress={showMoreSettled}
|
||||
className="mx-5 mt-1 items-center rounded-full bg-subtle py-2"
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground-muted">
|
||||
Show more ({threadListV2Layout.hiddenSettledCount} settled hidden)
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={listEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
recycleItems
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 24
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
|
||||
|
||||
@@ -167,6 +167,13 @@ export function ThreadSwipeable(props: {
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
/**
|
||||
* What a full swipe commits: "delete" (default, v1 behavior — the Delete
|
||||
* button stretches) or "primary" — the advertised primary action fires and
|
||||
* its button stretches instead. A full swipe must always match the action
|
||||
* the stretching button advertises.
|
||||
*/
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
@@ -239,7 +246,11 @@ export function ThreadSwipeable(props: {
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
if (props.fullSwipeAction === "primary") {
|
||||
props.primaryAction.onPress();
|
||||
} else {
|
||||
props.onDelete();
|
||||
}
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
@@ -247,6 +258,7 @@ export function ThreadSwipeable(props: {
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
fullSwipeAction={props.fullSwipeAction ?? "delete"}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
@@ -422,6 +434,7 @@ function SwipeActionButton(props: {
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly fullSwipeAction?: "delete" | "primary";
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
@@ -430,6 +443,7 @@ export function ThreadSwipeActions(props: {
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const fullSwipeIsPrimary = props.fullSwipeAction === "primary";
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
@@ -457,7 +471,7 @@ export function ThreadSwipeActions(props: {
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={false}
|
||||
stretchesOnFullSwipe={fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
@@ -471,7 +485,7 @@ export function ThreadSwipeActions(props: {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe
|
||||
stretchesOnFullSwipe={!fullSwipeIsPrimary}
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -6,19 +6,26 @@ import { Alert } from "react-native";
|
||||
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
archive: "archived",
|
||||
unarchive: "unarchived",
|
||||
delete: "deleted",
|
||||
settle: "settled",
|
||||
unsettle: "un-settled",
|
||||
};
|
||||
|
||||
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
|
||||
const error = Cause.squash(cause);
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
return `The thread could not be ${ACTION_VERBS[action]}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
@@ -28,54 +35,97 @@ function selectionHaptic(): void {
|
||||
function actionFailureTitle(action: ThreadListAction): string {
|
||||
if (action === "archive") return "Could not archive thread";
|
||||
if (action === "unarchive") return "Could not unarchive thread";
|
||||
if (action === "settle") return "Could not settle thread";
|
||||
if (action === "unsettle") return "Could not un-settle thread";
|
||||
return "Could not delete thread";
|
||||
}
|
||||
|
||||
/** Resolves to true iff the action was dispatched and succeeded. */
|
||||
function useThreadActionExecutor(
|
||||
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
|
||||
) {
|
||||
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
|
||||
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
|
||||
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
|
||||
// Client-only settled model: settle/unsettle ride the archive lifecycle so
|
||||
// no server upgrade is required. See client-runtime threadSettled.ts.
|
||||
const settleMutation = archiveMutation;
|
||||
const unsettleMutation = unarchiveMutation;
|
||||
const inFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const executeAction = useCallback(
|
||||
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (inFlightThreadKeys.current.has(key)) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
// Settle rides archive, so it inherits archive's guard: never
|
||||
// interrupt a thread mid-turn.
|
||||
if (
|
||||
(action === "settle" || action === "archive") &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Auto-settled rows (inactivity / merged PR) are not archived;
|
||||
// unarchiving them would be rejected. Nothing to undo — no-op.
|
||||
if (action === "unsettle" && thread.archivedAt === null) {
|
||||
return false;
|
||||
}
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
action === "settle"
|
||||
? settleMutation
|
||||
: action === "unsettle"
|
||||
? unsettleMutation
|
||||
: action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// Archived threads leave the live shell stream, and the v2 list
|
||||
// renders them from the archived snapshot — keep it fresh for every
|
||||
// action that changes what that snapshot should contain (delete
|
||||
// included, or a deleted settled row lingers until some later
|
||||
// refresh).
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
onCompleted?.(action, thread);
|
||||
return true;
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
[
|
||||
archiveMutation,
|
||||
deleteMutation,
|
||||
onCompleted,
|
||||
settleMutation,
|
||||
unarchiveMutation,
|
||||
unsettleMutation,
|
||||
],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
@@ -111,6 +161,8 @@ function useConfirmDeleteThread(
|
||||
export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
|
||||
@@ -120,10 +172,20 @@ export function useThreadListActions(): {
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
const settleThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const unsettleThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void executeAction("unsettle", thread);
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
return { archiveThread, confirmDeleteThread, settleThread, unsettleThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
|
||||
@@ -56,7 +56,6 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { ThreadGitMenu } from "../threads/ThreadGitControls";
|
||||
import { useReviewCacheForThread } from "./reviewState";
|
||||
import {
|
||||
isNativeReviewDiffDrawEvent,
|
||||
type NativeReviewDiffViewHandle,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
@@ -72,10 +71,8 @@ import { resolveReviewAvailability } from "./reviewAvailability";
|
||||
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
|
||||
import { buildReviewSectionMenu } from "./review-section-menu";
|
||||
import type { ReviewSectionItem } from "./reviewModel";
|
||||
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
|
||||
|
||||
const REVIEW_HEADER_SPACING = 0;
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
|
||||
return (
|
||||
@@ -397,7 +394,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
});
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
|
||||
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
|
||||
const showcasedReviewDrawRef = useRef<string | null>(null);
|
||||
// Native pull-to-refresh on the diff surface (replaces the old Refresh menu item).
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullToRefresh = useCallback(async () => {
|
||||
@@ -439,25 +435,6 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
selectedRowIds: commentSelection.selectedRowIds,
|
||||
canHighlight: parsedDiff.kind === "files",
|
||||
});
|
||||
const showcaseReviewKey =
|
||||
SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
|
||||
? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}`
|
||||
: null;
|
||||
const handleNativeDebug = useCallback(
|
||||
(event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
nativeBridge.onDebug(event);
|
||||
if (
|
||||
showcaseReviewKey === null ||
|
||||
showcasedReviewDrawRef.current === showcaseReviewKey ||
|
||||
!isNativeReviewDiffDrawEvent(event.nativeEvent)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
showcasedReviewDrawRef.current = showcaseReviewKey;
|
||||
markNativeShowcaseReady("review");
|
||||
},
|
||||
[nativeBridge.onDebug, showcaseReviewKey],
|
||||
);
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(fileId: string | null) => {
|
||||
@@ -811,7 +788,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
tokensPatchJson={nativeBridge.tokensPatchJson}
|
||||
tokensResetKey={nativeBridge.tokensResetKey}
|
||||
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
|
||||
onDebug={handleNativeDebug}
|
||||
onDebug={nativeBridge.onDebug}
|
||||
onPressLine={commentSelection.onPressLine}
|
||||
onVisibleFileChange={handleVisibleFileChange}
|
||||
onToggleComment={nativeBridge.onToggleComment}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stac
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
@@ -15,15 +15,6 @@ import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
applyShowcaseLocalEnvironmentDisplayUrls,
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl,
|
||||
SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS,
|
||||
} from "../showcase/showcaseEnvironmentRows";
|
||||
import { markNativeShowcaseReady } from "../showcase/nativeShowcaseScene";
|
||||
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
export function SettingsEnvironmentsRouteScreen() {
|
||||
const {
|
||||
@@ -34,56 +25,18 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
} = useRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const environmentSections = splitEnvironmentSections({
|
||||
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
|
||||
connectedEnvironments,
|
||||
cloudEnvironments: null,
|
||||
});
|
||||
const localEnvironments = SHOWCASE_ENABLED
|
||||
? applyShowcaseLocalEnvironmentDisplayUrls(environmentSections.localEnvironments)
|
||||
: environmentSections.localEnvironments;
|
||||
const connectedCloudEnvironments = SHOWCASE_ENABLED
|
||||
? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS
|
||||
: environmentSections.connectedCloudEnvironments;
|
||||
const hasLocalEnvironments = localEnvironments.length > 0;
|
||||
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const headerIconColor = useThemeColor("--color-icon");
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
const timer = setTimeout(() => markNativeShowcaseReady("environments"), 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
const handleToggle = useCallback((environmentId: EnvironmentId) => {
|
||||
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
|
||||
}, []);
|
||||
const handleUpdateEnvironment = useCallback(
|
||||
(
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => {
|
||||
if (!SHOWCASE_ENABLED) return onUpdateEnvironment(environmentId, updates);
|
||||
const actualEnvironment = environmentSections.localEnvironments.find(
|
||||
(environment) => environment.environmentId === environmentId,
|
||||
);
|
||||
const presentedEnvironment = localEnvironments.find(
|
||||
(environment) => environment.environmentId === environmentId,
|
||||
);
|
||||
return onUpdateEnvironment(environmentId, {
|
||||
...updates,
|
||||
displayUrl:
|
||||
actualEnvironment && presentedEnvironment
|
||||
? resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: actualEnvironment.displayUrl,
|
||||
presentedDisplayUrl: presentedEnvironment.displayUrl,
|
||||
submittedDisplayUrl: updates.displayUrl,
|
||||
})
|
||||
: updates.displayUrl,
|
||||
});
|
||||
},
|
||||
[environmentSections.localEnvironments, localEnvironments, onUpdateEnvironment],
|
||||
);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -139,7 +92,7 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
onToggle={() => handleToggle(environment.environmentId)}
|
||||
onReconnect={onReconnectEnvironment}
|
||||
onRemove={onRemoveEnvironmentPress}
|
||||
onUpdate={handleUpdateEnvironment}
|
||||
onUpdate={onUpdateEnvironment}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
@@ -161,16 +114,10 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
|
||||
{hasCloudPublicConfig() ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
|
||||
@@ -123,6 +123,8 @@ function LocalSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -506,6 +508,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
@@ -514,6 +518,35 @@ function ConfiguredSettingsRouteScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Beta">
|
||||
<SettingsSwitchRow
|
||||
icon="sidebar.left"
|
||||
label="Thread List v2"
|
||||
value={threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
One flat thread list in creation order. Active work renders as cards; settled threads
|
||||
collapse to compact rows. Switch back any time.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { holdEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
getNativeShowcasePairingUrls,
|
||||
getNativeShowcaseScene,
|
||||
markNativeShowcaseReady,
|
||||
type ShowcaseScene,
|
||||
} from "./nativeShowcaseScene";
|
||||
import {
|
||||
buildShowcasePendingTasks,
|
||||
SHOWCASE_PENDING_TASK_DEFINITIONS,
|
||||
} from "./showcasePendingTasks";
|
||||
import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
const SHOWCASE_THREAD_ID = "remote-command-center";
|
||||
|
||||
function sceneFromPathname(pathname: string): ShowcaseScene | null {
|
||||
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
|
||||
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
|
||||
return "environments";
|
||||
}
|
||||
if (routePath.endsWith("/terminal")) return "terminal";
|
||||
if (routePath.endsWith("/review")) return "review";
|
||||
if (routePath.startsWith("/threads/")) return "thread";
|
||||
if (routePath === "/") return "threads";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ShowcaseCaptureCoordinator(props: { readonly pathname: string }) {
|
||||
const navigation = useNavigation();
|
||||
const { connectPairingUrl } = useConnectionController();
|
||||
const workspace = useWorkspaceState();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const attemptedPairingRef = useRef(new Set<string>());
|
||||
const seededPendingTaskIdsRef = useRef(new Set<string>());
|
||||
const [pairingUrls, setPairingUrls] = useState<ReadonlyArray<string>>([]);
|
||||
const [pendingTasksReady, setPendingTasksReady] = useState(false);
|
||||
const [requestedScene, setRequestedScene] = useState<ShowcaseScene | null>(null);
|
||||
const [readyScene, setReadyScene] = useState<ShowcaseScene | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length > 0) return;
|
||||
|
||||
const readPairingUrls = () => {
|
||||
const values = getNativeShowcasePairingUrls();
|
||||
if (values.length > 0) setPairingUrls(values);
|
||||
};
|
||||
readPairingUrls();
|
||||
const interval = setInterval(readPairingUrls, 250);
|
||||
return () => clearInterval(interval);
|
||||
}, [pairingUrls.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED) return;
|
||||
|
||||
const readRequestedScene = () => {
|
||||
const value = getNativeShowcaseScene();
|
||||
if (value) setRequestedScene(value);
|
||||
};
|
||||
readRequestedScene();
|
||||
const interval = setInterval(readRequestedScene, 250);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || pairingUrls.length === 0) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
await Promise.all(
|
||||
pairingUrls.map(async (pairingUrl) => {
|
||||
if (cancelled || attemptedPairingRef.current.has(pairingUrl)) return;
|
||||
const paired = await retryShowcaseOperation(
|
||||
async () => AsyncResult.isSuccess(await connectPairingUrl(pairingUrl)),
|
||||
{ isCancelled: () => cancelled },
|
||||
);
|
||||
if (paired) attemptedPairingRef.current.add(pairingUrl);
|
||||
}),
|
||||
);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connectPairingUrl, pairingUrls]);
|
||||
|
||||
const scene = sceneFromPathname(props.pathname);
|
||||
const hasServerFixture =
|
||||
workspace.state.hasReadyEnvironment &&
|
||||
workspace.environments.length >= 3 &&
|
||||
projects.length >= 3 &&
|
||||
threads.some((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
|
||||
const hasFixture = hasServerFixture && pendingTasksReady;
|
||||
const showcaseThread = threads.find((thread) => String(thread.id) === SHOWCASE_THREAD_ID);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || !hasServerFixture || pendingTasksReady) return;
|
||||
|
||||
const pendingTasks = buildShowcasePendingTasks(projects, Date.now());
|
||||
if (pendingTasks.length !== SHOWCASE_PENDING_TASK_DEFINITIONS.length) return;
|
||||
|
||||
let cancelled = false;
|
||||
for (const task of pendingTasks) holdEditingQueuedMessage(task.messageId);
|
||||
void (async () => {
|
||||
const results = await Promise.all(
|
||||
pendingTasks.map(async (task) => {
|
||||
const messageId = String(task.messageId);
|
||||
if (seededPendingTaskIdsRef.current.has(messageId)) return true;
|
||||
const seeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
await enqueueThreadOutboxMessage(task);
|
||||
return true;
|
||||
},
|
||||
{ isCancelled: () => cancelled },
|
||||
);
|
||||
if (seeded) seededPendingTaskIdsRef.current.add(messageId);
|
||||
return seeded;
|
||||
}),
|
||||
);
|
||||
if (!cancelled && results.every(Boolean)) setPendingTasksReady(true);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hasServerFixture, pendingTasksReady, projects]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!SHOWCASE_ENABLED || requestedScene === null || !hasFixture || !showcaseThread) return;
|
||||
if (scene === requestedScene) return;
|
||||
|
||||
const params = {
|
||||
environmentId: String(showcaseThread.environmentId),
|
||||
threadId: SHOWCASE_THREAD_ID,
|
||||
};
|
||||
if (requestedScene === "threads") {
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
routes.push({ name: "Thread", params });
|
||||
if (requestedScene === "terminal") {
|
||||
routes.push({
|
||||
name: "ThreadTerminal",
|
||||
params: { ...params, terminalId: "term-1" },
|
||||
});
|
||||
} else if (requestedScene === "review") {
|
||||
routes.push({ name: "ThreadReview", params });
|
||||
}
|
||||
}
|
||||
navigation.dispatch(
|
||||
CommonActions.reset({
|
||||
index: routes.length - 1,
|
||||
routes,
|
||||
}),
|
||||
);
|
||||
}, [hasFixture, navigation, requestedScene, scene, showcaseThread]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!SHOWCASE_ENABLED ||
|
||||
scene === null ||
|
||||
requestedScene === null ||
|
||||
scene !== requestedScene ||
|
||||
!hasFixture
|
||||
) {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
}
|
||||
// Review owns its readiness marker because route activation happens before
|
||||
// the VCS request is parsed and the native diff surface is mounted.
|
||||
if (scene === "review") {
|
||||
setReadyScene(null);
|
||||
return;
|
||||
}
|
||||
if (scene === "terminal") Keyboard.dismiss();
|
||||
|
||||
let renderFrame: number | null = null;
|
||||
let readyFrame: number | null = null;
|
||||
const settleTimer = setTimeout(() => {
|
||||
renderFrame = requestAnimationFrame(() => {
|
||||
readyFrame = requestAnimationFrame(() => {
|
||||
markNativeShowcaseReady(scene);
|
||||
setReadyScene(scene);
|
||||
});
|
||||
});
|
||||
}, 500);
|
||||
return () => {
|
||||
clearTimeout(settleTimer);
|
||||
if (renderFrame !== null) cancelAnimationFrame(renderFrame);
|
||||
if (readyFrame !== null) cancelAnimationFrame(readyFrame);
|
||||
};
|
||||
}, [hasFixture, requestedScene, scene]);
|
||||
|
||||
if (!SHOWCASE_ENABLED || readyScene === null) return null;
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
testID={`showcase-ready-${readyScene}`}
|
||||
style={{ position: "absolute", width: 1, height: 1, opacity: 0.01 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { requireOptionalNativeModule } from "expo";
|
||||
|
||||
export const SHOWCASE_SCENES = ["threads", "thread", "terminal", "review", "environments"] as const;
|
||||
export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
|
||||
|
||||
interface NativeShowcaseControls {
|
||||
readonly getShowcasePairingUrl?: () => string | null;
|
||||
readonly getShowcaseScene?: () => string | null;
|
||||
readonly prepareShowcaseCapture?: () => void;
|
||||
readonly markShowcaseReady?: (scene: ShowcaseScene) => void;
|
||||
}
|
||||
|
||||
function nativeShowcaseControls(): NativeShowcaseControls | null {
|
||||
return requireOptionalNativeModule<NativeShowcaseControls>("T3NativeControls");
|
||||
}
|
||||
|
||||
export function getNativeShowcasePairingUrls(): ReadonlyArray<string> {
|
||||
try {
|
||||
let raw = nativeShowcaseControls()?.getShowcasePairingUrl?.()?.trim();
|
||||
if (!raw) return [];
|
||||
if (raw.startsWith("json-uri:")) {
|
||||
try {
|
||||
raw = decodeURIComponent(raw.slice("json-uri:".length));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.filter(
|
||||
(candidate): candidate is string =>
|
||||
typeof candidate === "string" && candidate.trim().length > 0,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Older runners pass a single URL rather than a JSON array.
|
||||
}
|
||||
return [raw];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeShowcaseScene(): ShowcaseScene | null {
|
||||
try {
|
||||
const scene = nativeShowcaseControls()?.getShowcaseScene?.()?.trim();
|
||||
return SHOWCASE_SCENES.find((candidate) => candidate === scene) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareNativeShowcaseCapture(): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.prepareShowcaseCapture?.();
|
||||
} catch {
|
||||
// The harness still works when a development build predates this helper.
|
||||
}
|
||||
}
|
||||
|
||||
export function markNativeShowcaseReady(scene: ShowcaseScene): void {
|
||||
try {
|
||||
nativeShowcaseControls()?.markShowcaseReady?.(scene);
|
||||
} catch {
|
||||
// The readiness marker is capture-runner metadata, never app functionality.
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import {
|
||||
applyShowcaseLocalEnvironmentDisplayUrls,
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl,
|
||||
} from "./showcaseEnvironmentRows";
|
||||
|
||||
function environment(
|
||||
environmentId: string,
|
||||
environmentLabel: string,
|
||||
displayUrl = "http://127.0.0.1:3773/",
|
||||
): ConnectedEnvironmentSummary {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
environmentLabel,
|
||||
displayUrl,
|
||||
isRelayManaged: false,
|
||||
connectionState: "connected",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
};
|
||||
}
|
||||
|
||||
it("presents showcase transports as remote endpoints", () => {
|
||||
const environments = applyShowcaseLocalEnvironmentDisplayUrls([
|
||||
environment("runtime-id-1", "Moonbase Terminal"),
|
||||
environment("runtime-id-2", "Suspense Station"),
|
||||
environment("runtime-id-3", "Kernel Cabin"),
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
environments.map(({ displayUrl }) => displayUrl),
|
||||
[
|
||||
"https://moonbase.tail9f3a.ts.net/",
|
||||
"https://suspense-vps.hel1.t3.sh/",
|
||||
"http://100.82.16.5:3773/",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves environments outside the showcase fixture unchanged", () => {
|
||||
const original = environment(
|
||||
"runtime-id-4",
|
||||
"My Workstation",
|
||||
"https://workstation.example.test/",
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(applyShowcaseLocalEnvironmentDisplayUrls([original]), [original]);
|
||||
});
|
||||
|
||||
it("does not persist a cosmetic showcase URL when only the label is saved", () => {
|
||||
assert.equal(
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: "http://127.0.0.1:3773/",
|
||||
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
submittedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
}),
|
||||
"http://127.0.0.1:3773/",
|
||||
);
|
||||
assert.equal(
|
||||
resolveShowcaseEnvironmentUpdateDisplayUrl({
|
||||
actualDisplayUrl: "http://127.0.0.1:3773/",
|
||||
presentedDisplayUrl: "https://moonbase.tail9f3a.ts.net/",
|
||||
submittedDisplayUrl: "https://new-host.example.com/",
|
||||
}),
|
||||
"https://new-host.example.com/",
|
||||
);
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import type { RelayEnvironmentView } from "../connection/useConnectionController";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
|
||||
const SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS: Readonly<Record<string, string>> = {
|
||||
"Moonbase Terminal": "https://moonbase.tail9f3a.ts.net/",
|
||||
"Suspense Station": "https://suspense-vps.hel1.t3.sh/",
|
||||
"Kernel Cabin": "http://100.82.16.5:3773/",
|
||||
};
|
||||
|
||||
export function applyShowcaseLocalEnvironmentDisplayUrls(
|
||||
environments: ReadonlyArray<ConnectedEnvironmentSummary>,
|
||||
): ReadonlyArray<ConnectedEnvironmentSummary> {
|
||||
return environments.map((environment) => ({
|
||||
...environment,
|
||||
displayUrl:
|
||||
SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS[environment.environmentLabel] ??
|
||||
environment.displayUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveShowcaseEnvironmentUpdateDisplayUrl(input: {
|
||||
readonly actualDisplayUrl: string;
|
||||
readonly presentedDisplayUrl: string;
|
||||
readonly submittedDisplayUrl: string;
|
||||
}): string {
|
||||
return input.submittedDisplayUrl === input.presentedDisplayUrl
|
||||
? input.actualDisplayUrl
|
||||
: input.submittedDisplayUrl;
|
||||
}
|
||||
|
||||
const pocketPiId = EnvironmentId.make("showcase-pocket-pi");
|
||||
const pocketPiEndpoint = {
|
||||
httpBaseUrl: "https://pocket-pi.t3.sh",
|
||||
wsBaseUrl: "wss://pocket-pi.t3.sh",
|
||||
providerKind: "t3_relay" as const,
|
||||
};
|
||||
|
||||
export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray<ConnectedEnvironmentSummary> = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("showcase-aurora-gpu"),
|
||||
environmentLabel: "Aurora GPU Pod",
|
||||
displayUrl: "https://aurora-gpu.t3.sh",
|
||||
isRelayManaged: true,
|
||||
connectionState: "connected",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
},
|
||||
];
|
||||
|
||||
export const SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS: ReadonlyArray<RelayEnvironmentView> = [
|
||||
{
|
||||
environment: {
|
||||
environmentId: pocketPiId,
|
||||
label: "Pocket Pi",
|
||||
endpoint: pocketPiEndpoint,
|
||||
linkedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
availability: "online",
|
||||
status: {
|
||||
environmentId: pocketPiId,
|
||||
endpoint: pocketPiEndpoint,
|
||||
status: "online",
|
||||
checkedAt: "2026-07-16T08:41:00.000Z",
|
||||
},
|
||||
error: null,
|
||||
traceId: null,
|
||||
},
|
||||
];
|
||||
@@ -1,72 +0,0 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
buildShowcasePendingTasks,
|
||||
SHOWCASE_PENDING_TASK_DEFINITIONS,
|
||||
} from "./showcasePendingTasks";
|
||||
|
||||
const projects: ReadonlyArray<EnvironmentProject> = [
|
||||
{
|
||||
environmentId: EnvironmentId.make("moonbase-terminal"),
|
||||
id: ProjectId.make("t3code"),
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/workspace/t3code",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
scripts: [],
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
updatedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
{
|
||||
environmentId: EnvironmentId.make("suspense-station"),
|
||||
id: ProjectId.make("react"),
|
||||
title: "React",
|
||||
workspaceRoot: "/workspace/react",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
updatedAt: "2026-07-16T08:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
it("builds sendable-looking pending tasks against real showcase projects", () => {
|
||||
const tasks = buildShowcasePendingTasks(projects, Date.parse("2026-07-16T09:00:00.000Z"));
|
||||
|
||||
assert.equal(tasks.length, SHOWCASE_PENDING_TASK_DEFINITIONS.length);
|
||||
assert.deepStrictEqual(
|
||||
tasks.map((task) => ({
|
||||
environmentId: String(task.environmentId),
|
||||
projectId: task.creation ? String(task.creation.projectId) : undefined,
|
||||
title: task.creation?.projectTitle,
|
||||
branch: task.creation?.branch,
|
||||
createdAt: task.createdAt,
|
||||
})),
|
||||
[
|
||||
{
|
||||
environmentId: "moonbase-terminal",
|
||||
projectId: "t3code",
|
||||
title: "T3 Code",
|
||||
branch: "feat/offline-launchpad",
|
||||
createdAt: "2026-07-16T08:52:00.000Z",
|
||||
},
|
||||
{
|
||||
environmentId: "suspense-station",
|
||||
projectId: "react",
|
||||
title: "React",
|
||||
branch: "perf/tunnel-handoff",
|
||||
createdAt: "2026-07-16T08:33:00.000Z",
|
||||
},
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
tasks.every((task) => task.modelSelection !== undefined),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("waits until every referenced project has hydrated", () => {
|
||||
assert.equal(buildShowcasePendingTasks(projects.slice(0, 1), Date.now()).length, 1);
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
|
||||
|
||||
export const SHOWCASE_PENDING_TASK_DEFINITIONS = [
|
||||
{
|
||||
projectId: "t3code",
|
||||
id: "offline-launch-checklist",
|
||||
text: "Ship the offline launch checklist before touchdown ✈️",
|
||||
branch: "feat/offline-launchpad",
|
||||
minutesAgo: 8,
|
||||
},
|
||||
{
|
||||
projectId: "react",
|
||||
id: "train-tunnel-suspense",
|
||||
text: "Polish the Suspense handoff for the train tunnel 🚇",
|
||||
branch: "perf/tunnel-handoff",
|
||||
minutesAgo: 27,
|
||||
},
|
||||
] as const;
|
||||
|
||||
const FALLBACK_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
} as const;
|
||||
|
||||
export function buildShowcasePendingTasks(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
now: number,
|
||||
): ReadonlyArray<QueuedThreadMessage> {
|
||||
return SHOWCASE_PENDING_TASK_DEFINITIONS.flatMap((definition) => {
|
||||
const project = projects.find((candidate) => String(candidate.id) === definition.projectId);
|
||||
if (!project) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
environmentId: project.environmentId,
|
||||
threadId: ThreadId.make(`showcase-pending-${definition.id}`),
|
||||
messageId: MessageId.make(`showcase-pending-message-${definition.id}`),
|
||||
commandId: CommandId.make(`showcase-pending-command-${definition.id}`),
|
||||
text: definition.text,
|
||||
attachments: [],
|
||||
modelSelection: project.defaultModelSelection ?? FALLBACK_MODEL_SELECTION,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
creation: {
|
||||
projectId: project.id,
|
||||
projectTitle: project.title,
|
||||
projectCwd: project.workspaceRoot,
|
||||
workspaceMode: "local" as const,
|
||||
branch: definition.branch,
|
||||
worktreePath: project.workspaceRoot,
|
||||
},
|
||||
createdAt: new Date(now - definition.minutesAgo * 60_000).toISOString(),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
|
||||
it("retries a failed showcase operation until it succeeds", async () => {
|
||||
let attempts = 0;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
attempts += 1;
|
||||
return attempts === 3;
|
||||
},
|
||||
{ isCancelled: () => false, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, true);
|
||||
assert.equal(attempts, 3);
|
||||
});
|
||||
|
||||
it("recovers when a showcase operation attempt hangs", async () => {
|
||||
let attempts = 0;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
() => {
|
||||
attempts += 1;
|
||||
return attempts === 1 ? new Promise<boolean>(() => undefined) : Promise.resolve(true);
|
||||
},
|
||||
{ isCancelled: () => false, attemptTimeoutMs: 1, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, true);
|
||||
assert.equal(attempts, 2);
|
||||
});
|
||||
|
||||
it("stops retrying when the owning showcase effect is cancelled", async () => {
|
||||
let cancelled = false;
|
||||
const succeeded = await retryShowcaseOperation(
|
||||
async () => {
|
||||
cancelled = true;
|
||||
return false;
|
||||
},
|
||||
{ isCancelled: () => cancelled, retryDelayMs: 0 },
|
||||
);
|
||||
|
||||
assert.equal(succeeded, false);
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
export interface ShowcaseRetryOptions {
|
||||
readonly isCancelled: () => boolean;
|
||||
readonly attemptTimeoutMs?: number;
|
||||
readonly retryDelayMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_ATTEMPT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_RETRY_DELAY_MS = 500;
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function runAttemptWithTimeout(
|
||||
operation: () => Promise<boolean>,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation(),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timeout = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry transient showcase setup work until it succeeds or the owning effect unmounts. */
|
||||
export async function retryShowcaseOperation(
|
||||
operation: () => Promise<boolean>,
|
||||
options: ShowcaseRetryOptions,
|
||||
): Promise<boolean> {
|
||||
const attemptTimeoutMs = options.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;
|
||||
const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
||||
|
||||
while (!options.isCancelled()) {
|
||||
if (await runAttemptWithTimeout(operation, attemptTimeoutMs)) return true;
|
||||
if (!options.isCancelled()) await delay(retryDelayMs);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -37,7 +37,6 @@ interface TerminalSurfaceProps extends ViewProps {
|
||||
readonly buffer: string;
|
||||
readonly fontSize?: number;
|
||||
readonly isRunning: boolean;
|
||||
readonly autoFocus?: boolean;
|
||||
readonly keyboardFocusRequest?: number;
|
||||
readonly theme?: TerminalTheme;
|
||||
readonly onInput: (data: string) => void;
|
||||
@@ -146,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`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -216,7 +214,6 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
|
||||
<View style={props.style}>
|
||||
<NativeTerminalSurfaceView
|
||||
appearanceScheme={appearanceScheme}
|
||||
autoFocus={props.autoFocus ?? true}
|
||||
backgroundColor={theme.background}
|
||||
focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
|
||||
foregroundColor={theme.foreground}
|
||||
|
||||
@@ -70,7 +70,6 @@ import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiSt
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
const TERMINAL_ACCESSORY_HEIGHT = 52;
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
|
||||
type PendingModifier = "ctrl" | "meta";
|
||||
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
|
||||
@@ -1219,7 +1218,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
<>
|
||||
<View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
|
||||
<TerminalSurface
|
||||
autoFocus={!SHOWCASE_ENABLED}
|
||||
buffer={terminalSurfaceBuffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
|
||||
@@ -23,7 +23,6 @@ interface TerminalResizeEvent {
|
||||
|
||||
export interface NativeTerminalSurfaceProps extends ViewProps {
|
||||
readonly appearanceScheme?: "light" | "dark";
|
||||
readonly autoFocus?: boolean;
|
||||
readonly focusRequest?: number;
|
||||
readonly themeConfig?: string;
|
||||
readonly backgroundColor?: string;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { Platform, useColorScheme } from "react-native";
|
||||
|
||||
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
|
||||
const SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
@@ -35,11 +34,10 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerTitle: renderCompactBrandTitle,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: true,
|
||||
scrollEdgeEffects: SCROLL_EDGE_EFFECTS,
|
||||
title: "T3 Code",
|
||||
title: "Threads",
|
||||
unstable_navigationItemStyle: "editor",
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { memo, useCallback, useMemo, type ComponentProps, type ReactNode } from "react";
|
||||
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { resolveThreadListV2Status, type ThreadListV2Status } from "./threadListV2";
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Thread List v2 rows. The design language is the web sidebar v2 (status
|
||||
* edge strip, mono project labels, settled tail), but the card anatomy is
|
||||
* native iOS list-app, not the web's window chrome: a solid raised surface
|
||||
* (no outline), a leading favicon tile as the touch anchor, a trailing
|
||||
* chevron, and spring press feedback. Bordered translucent boxes with a
|
||||
* header row read as notifications — information, not buttons.
|
||||
*/
|
||||
|
||||
const MONO_FONT = Platform.select({
|
||||
ios: "Menlo",
|
||||
android: "monospace",
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
const EDGE_CLASS_BY_STATUS: Partial<Record<ThreadListV2Status, string>> = {
|
||||
approval: "bg-amber-500 dark:bg-amber-400",
|
||||
working: "bg-sky-500 dark:bg-sky-400",
|
||||
failed: "bg-red-500",
|
||||
};
|
||||
|
||||
const STATUS_WORD_BY_STATUS: Partial<
|
||||
Record<ThreadListV2Status, { label: string; className: string }>
|
||||
> = {
|
||||
approval: { label: "NEEDS APPROVAL", className: "text-amber-600 dark:text-amber-400" },
|
||||
working: { label: "WORKING", className: "text-sky-600 dark:text-sky-400" },
|
||||
failed: { label: "FAILED", className: "text-red-600 dark:text-red-400" },
|
||||
};
|
||||
|
||||
function threadTimeLabel(thread: EnvironmentThreadShell, status: ThreadListV2Status): string {
|
||||
if (status === "approval") {
|
||||
return `waiting ${relativeTime(thread.updatedAt)}`;
|
||||
}
|
||||
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
|
||||
}
|
||||
|
||||
const CARD_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const SLIM_MENU_ACTIONS: MenuAction[] = [
|
||||
{ id: "unsettle", title: "Un-settle", image: "arrow.uturn.backward" },
|
||||
{ id: "archive", title: "Archive", image: "archivebox" },
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
];
|
||||
|
||||
const PRESS_SPRING = { damping: 30, stiffness: 400 } as const;
|
||||
|
||||
/**
|
||||
* Pressable that springs down to 97% while touched — the "this is a real
|
||||
* object under your finger" signal every native list app ships.
|
||||
*
|
||||
* Accepts an injected `onLongPress` and forwards it to the inner Pressable:
|
||||
* on Android, ControlPillMenu opens its menu by cloning its immediate child
|
||||
* with an onLongPress prop, so this component must be that child and must
|
||||
* route the handler to something that actually handles presses.
|
||||
*/
|
||||
function PressableScaleCard(props: {
|
||||
readonly accessibilityHint: string;
|
||||
readonly accessibilityLabel: string;
|
||||
readonly onPress: () => void;
|
||||
readonly onLongPress?: () => void;
|
||||
readonly children: ReactNode;
|
||||
}) {
|
||||
const scale = useSharedValue(1);
|
||||
const animatedStyle = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
|
||||
|
||||
return (
|
||||
<Animated.View style={animatedStyle}>
|
||||
<Pressable
|
||||
accessibilityHint={props.accessibilityHint}
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
{...(props.onLongPress ? { onLongPress: props.onLongPress } : {})}
|
||||
onPressIn={() => {
|
||||
scale.value = withSpring(0.97, PRESS_SPRING);
|
||||
}}
|
||||
onPressOut={() => {
|
||||
scale.value = withSpring(1, PRESS_SPRING);
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
export const ThreadListV2SettledDivider = memo(function ThreadListV2SettledDivider() {
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
return (
|
||||
<View className="mb-2 mt-4 flex-row items-center gap-2.5 px-5">
|
||||
<Text
|
||||
className="text-2xs font-t3-bold uppercase text-foreground-tertiary"
|
||||
style={{ fontFamily: MONO_FONT, letterSpacing: 1.8 }}
|
||||
>
|
||||
Settled
|
||||
</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: separatorColor }} />
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
merged/closed work (mirrors web's onChangeRequestState). */
|
||||
readonly onChangeRequestState?: (
|
||||
threadKey: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
) => void;
|
||||
readonly projectCwd?: string | null;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
}) {
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const {
|
||||
thread,
|
||||
variant,
|
||||
onSelectThread,
|
||||
onArchiveThread,
|
||||
onDeleteThread,
|
||||
onSettleThread,
|
||||
onUnsettleThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
useEffect(() => {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusEdge = EDGE_CLASS_BY_STATUS[status];
|
||||
const statusWord = STATUS_WORD_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread, status);
|
||||
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
},
|
||||
[handleArchive, handleDelete, handleSettle, handleUnsettle],
|
||||
);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Un-settle only
|
||||
// exists when there is an archive to undo; an auto-settled slim row
|
||||
// (inactivity / merged PR, archivedAt null) offers Settle, which archives
|
||||
// it — the explicit "keep it settled" the row can actually deliver.
|
||||
const canUnsettle = variant === "slim" && thread.archivedAt !== null;
|
||||
const primaryAction = useMemo(
|
||||
() =>
|
||||
canUnsettle
|
||||
? {
|
||||
accessibilityLabel: `Un-settle ${thread.title}`,
|
||||
icon: "arrow.uturn.backward" as const,
|
||||
label: "Un-settle",
|
||||
onPress: handleUnsettle,
|
||||
}
|
||||
: {
|
||||
accessibilityLabel: `Settle ${thread.title}`,
|
||||
icon: "checkmark" as const,
|
||||
label: "Settle",
|
||||
onPress: handleSettle,
|
||||
},
|
||||
[canUnsettle, handleSettle, handleUnsettle, thread.title],
|
||||
);
|
||||
|
||||
const rowContent = (close: () => void) =>
|
||||
variant === "card" ? (
|
||||
// PressableScaleCard must be the ROOT here: ControlPillMenu injects
|
||||
// its Android long-press by cloning this element.
|
||||
<PressableScaleCard
|
||||
accessibilityHint="Opens the thread. Swipe left to settle."
|
||||
accessibilityLabel={thread.title}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
>
|
||||
<View className="bg-screen px-4 py-1.5">
|
||||
{/* Solid raised card: bg-card with no border reads as an object,
|
||||
not a notification banner. */}
|
||||
<View
|
||||
className="flex-row items-center overflow-hidden bg-card"
|
||||
style={{ borderRadius: 18, borderCurve: "continuous", minHeight: 84 }}
|
||||
>
|
||||
{statusEdge ? <View className={cn("h-full w-1", statusEdge)} /> : null}
|
||||
{/* Favicon tile: the leading touch anchor, app-icon style. */}
|
||||
<View
|
||||
className="ml-3 mr-3 items-center justify-center bg-subtle"
|
||||
style={{ width: 38, height: 38, borderRadius: 10, borderCurve: "continuous" }}
|
||||
>
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={22}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="flex-1 py-3 pr-2">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="flex-1 text-2xs font-t3-bold uppercase text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: MONO_FONT, letterSpacing: 1.2 }}
|
||||
>
|
||||
{props.project?.title ?? ""}
|
||||
</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-2xs tabular-nums",
|
||||
status === "approval"
|
||||
? "text-amber-600 dark:text-amber-400"
|
||||
: "text-foreground-tertiary",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{timeLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="mt-0.5 text-lg font-t3-bold text-foreground" numberOfLines={2}>
|
||||
{thread.title}
|
||||
</Text>
|
||||
{statusWord || thread.branch || (status === "failed" && thread.session?.lastError) ? (
|
||||
<View className="mt-0.5 flex-row items-center gap-2">
|
||||
{statusWord ? (
|
||||
<Text
|
||||
className={cn("text-sm font-t3-bold", statusWord.className)}
|
||||
style={{ fontFamily: MONO_FONT, letterSpacing: 0.7 }}
|
||||
>
|
||||
{statusWord.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className="flex-1 text-sm text-red-600/80 dark:text-red-400/80"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch ? (
|
||||
<Text
|
||||
className="flex-1 text-sm text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{/* Trailing chevron: the universal "this navigates" affordance. */}
|
||||
<View className="pr-3.5">
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</PressableScaleCard>
|
||||
) : (
|
||||
<Pressable
|
||||
accessibilityHint="Opens the thread. Swipe left to un-settle."
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-screen"
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
{/* Settled history recedes: dimmed favicon + muted title. */}
|
||||
<View className="min-h-[48px] flex-row items-center gap-3 px-5 py-2.5">
|
||||
{props.project ? (
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={18}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="flex-1 text-lg text-foreground-muted" numberOfLines={1}>
|
||||
{thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-sm tabular-nums text-foreground-tertiary"
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.showSettledDivider ? <ThreadListV2SettledDivider /> : null}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={screenColor}
|
||||
enableTrackpadSwipe
|
||||
// Full swipe commits the advertised lifecycle action (Settle /
|
||||
// Un-settle), never the destructive delete.
|
||||
fullSwipeAction="primary"
|
||||
fullSwipeWidth={windowWidth - 32}
|
||||
onDelete={handleDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={primaryAction}
|
||||
resetKey={`${thread.environmentId}:${thread.id}`}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={thread.title}
|
||||
>
|
||||
{(close) => (
|
||||
<ControlPillMenu
|
||||
actions={canUnsettle ? SLIM_MENU_ACTIONS : CARD_MENU_ACTIONS}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
>
|
||||
{rowContent(close)}
|
||||
</ControlPillMenu>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
});
|
||||
expect(resolveThreadListV2Status(thread)).toBe("approval");
|
||||
});
|
||||
|
||||
it("resolves ready for quiescent threads", () => {
|
||||
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
|
||||
"ready",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortThreadsForListV2", () => {
|
||||
it("orders by creation time, newest first, ignoring activity", () => {
|
||||
const sorted = sortThreadsForListV2([
|
||||
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
|
||||
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
|
||||
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
|
||||
]);
|
||||
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("partitions archived (settled) threads into a slim tail with one divider", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled"),
|
||||
title: "Settled",
|
||||
archivedAt: NOW,
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("settled-2"),
|
||||
title: "Settled 2",
|
||||
archivedAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["active", "card"],
|
||||
["settled", "slim"],
|
||||
["settled-2", "slim"],
|
||||
]);
|
||||
expect(items.map((item) => item.showSettledDivider)).toEqual([false, true, false]);
|
||||
expect(items.map((item) => item.isLast)).toEqual([false, false, true]);
|
||||
});
|
||||
|
||||
it("keeps cards in creation order while settled sorts by recency", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.make("older-created"),
|
||||
title: "Older",
|
||||
createdAt: "2026-06-01T08:00:00.000Z",
|
||||
updatedAt: NOW, // recent activity must NOT promote it
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.make("newer-created"),
|
||||
title: "Newer",
|
||||
createdAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
|
||||
});
|
||||
|
||||
it("keeps archived threads in the tail and filters by search query", () => {
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("match"), title: "Fix login bug" }),
|
||||
makeThread({ id: ThreadId.make("miss"), title: "Greeting" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("archived"),
|
||||
title: "Fix login again",
|
||||
archivedAt: NOW,
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "login",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
|
||||
["match", "card"],
|
||||
["archived", "slim"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items settled paging", () => {
|
||||
it("caps the settled tail at settledLimit and reports the hidden count", () => {
|
||||
const threads = [
|
||||
makeThread({ id: ThreadId.make("active"), title: "Active" }),
|
||||
...Array.from({ length: 4 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(`settled-${index}`),
|
||||
title: `Settled ${index}`,
|
||||
archivedAt: NOW,
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
const layout = buildThreadListV2Items({
|
||||
threads,
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
settledLimit: 2,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(layout.hiddenSettledCount).toBe(2);
|
||||
expect(layout.items.filter((item) => item.variant === "slim")).toHaveLength(2);
|
||||
// Most recent settled first — the hidden ones are the oldest.
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([
|
||||
"active",
|
||||
"settled-3",
|
||||
"settled-2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "working" | "failed" | "ready";
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "session">,
|
||||
): ThreadListV2Status {
|
||||
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. Mirrors web's
|
||||
* sortThreadsForSidebarV2.
|
||||
*/
|
||||
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
|
||||
threads: readonly T[],
|
||||
): T[] {
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
|
||||
// change-by-copy array methods.
|
||||
return [...threads].sort(
|
||||
(left, right) =>
|
||||
Date.parse(right.createdAt) - Date.parse(left.createdAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
}
|
||||
|
||||
export interface ThreadListV2Item {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly variant: "card" | "slim";
|
||||
/** First settled row after the card block draws the SETTLED divider. */
|
||||
readonly showSettledDivider: boolean;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadListV2Layout {
|
||||
readonly items: ThreadListV2Item[];
|
||||
/** Settled threads beyond the render limit (behind "Show more"). */
|
||||
readonly hiddenSettledCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partitions visible threads into the active card block (creation order) and
|
||||
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
|
||||
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
|
||||
* the default is fixed here rather than user-configurable.
|
||||
*/
|
||||
export function buildThreadListV2Items(input: {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
|
||||
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
|
||||
readonly autoSettleAfterDays?: number;
|
||||
/** Max settled rows to render; the rest are counted, not built. */
|
||||
readonly settledLimit?: number;
|
||||
/** Injectable for tests; defaults to now. */
|
||||
readonly now?: string;
|
||||
}): ThreadListV2Layout {
|
||||
const now = input.now ?? new Date().toISOString();
|
||||
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
|
||||
const active: EnvironmentThreadShell[] = [];
|
||||
const settled: EnvironmentThreadShell[] = [];
|
||||
for (const thread of input.threads) {
|
||||
// Archived threads stay in the list: in the client-only settled model,
|
||||
// archive IS settle, so they render as the settled tail.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
|
||||
const changeRequestState =
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
if (effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
}
|
||||
}
|
||||
|
||||
const orderedActive = sortThreadsForListV2(active);
|
||||
const orderedSettled = [...settled].sort(
|
||||
(left, right) =>
|
||||
Date.parse(right.latestUserMessageAt ?? right.updatedAt) -
|
||||
Date.parse(left.latestUserMessageAt ?? left.updatedAt),
|
||||
);
|
||||
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
|
||||
const visibleSettled =
|
||||
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of orderedActive) {
|
||||
items.push({ thread, variant: "card", showSettledDivider: false, isLast: false });
|
||||
}
|
||||
for (const [index, thread] of visibleSettled.entries()) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "slim",
|
||||
showSettledDivider: index === 0,
|
||||
isLast: false,
|
||||
});
|
||||
}
|
||||
const last = items.at(-1);
|
||||
if (last) {
|
||||
items[items.length - 1] = { ...last, isLast: true };
|
||||
}
|
||||
return { items, hiddenSettledCount: orderedSettled.length - visibleSettled.length };
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -22,6 +22,12 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
|
||||
@@ -71,6 +77,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -97,6 +104,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
|
||||