merge: update PR 2829 with latest main

27 commits from main, including the ⌘P file picker / ⇧⌘F content search
(#4855), thread content search (#4959), sidebar title regeneration
(#4810), image-paste compression (#4967), and the docs restructure
(#4807). Notable resolutions beyond keep-both:

- Thread content search is ported to the v2 surface: searchThreads joins
  ORCHESTRATION_V2_WS_METHODS/rpc/auth scopes, and the SQL now UNIONs
  orchestration_v2_projection_messages so current threads are searchable,
  not just legacy-projected ones.
- Title regeneration's server half lived in the v1 ProviderCommandReactor
  this branch deletes, so the capability is deliberately not advertised:
  clients hide the action, the contract/UI code stays intact, and the
  input field is accepted as a documented no-op.
  TODO(orchestration-v2): port regeneration to the v2 runtime.
- Main's 035_ProjectionThreadTitleRegeneration migration collided with
  this branch's 035-043 range; renumbered to 044.
- Mobile activity grouping keeps this branch's runId/prominence semantics
  while adopting main's O(1) trailing-group optimization (prominence
  tracked in a flag instead of a per-append scan).
- v1-only startup tests from main (heartbeat/auto-bootstrap against the
  deleted reactor-era services) are dropped; their v2 equivalents already
  cover the ordered startup phases.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 committed 2026-07-30 17:29:43 +02:00
commit 3f8a05150b
209 files changed
+10065 -2942

No files matched your search

+18 -9
View File
@@ -28,7 +28,7 @@ T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
**Mobile** is a React native app for both iOS and Android. The mobile app allows for connecting to any T3 Code server to control work remotely. It is still in early access (Testflight), but it is pretty close to shipping globally.
**Mobile** is a React Native app for both iOS and Android, available on the App Store and Google Play. The mobile app allows for connecting to any T3 Code server to control work remotely.
## A note from Theo
@@ -59,7 +59,7 @@ We need to be on the same page with terminology. When communicating, use this la
## The three ways to hurt yourself
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
2. **Touching the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Read-only inspection is fine. Never start a server against it, never open it read-write, never clean it up.
2. **Writing to the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Reading it and copying from it are fine, and a good way to get real test data (see Test data). Never start a server against it, never open it read-write, never clean it up.
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
## Hit every surface
@@ -72,7 +72,7 @@ The most common defect in this repo is a change that works on the path you teste
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
- **Docs.** `docs/` mirrors this structure. Behavior changes that a user would notice belong in `docs/user/`; architecture changes in `docs/architecture/`; new vocabulary in `docs/reference/encyclopedia.md`.
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
## Dev servers
@@ -85,10 +85,19 @@ The most common defect in this repo is a change that works on the path you teste
## Test data
An empty database is a bad test. Seed your worktree's `.t3` instead of pointing at live state:
An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state:
- Copy from `~/.t3/userdata` (the developer's real data, the most realistic test set) or `~/.t3/dev`. Worktree state lives at `<worktree>/.t3/userdata`.
- Snapshot the database with `VACUUM INTO`, which is safe even while a server has the source open and yields one consistent file:
```bash
mkdir -p .t3/userdata
rm -f .t3/userdata/state.sqlite* # VACUUM INTO refuses to overwrite
bun -e "new (require('bun:sqlite').Database)(process.env.HOME + '/.t3/userdata/state.sqlite', { readonly: true }).run(\"VACUUM INTO '.t3/userdata/state.sqlite'\")"
```
A plain `cp` is only safe when no server has the source open, and must bring the `-wal` and `-shm` siblings along. A live file copy is a corrupt copy.
- Copy from `~/.t3/dev`, never from `~/.t3/userdata`.
- Copy `state.sqlite` together with its `-wal` and `-shm` siblings, and only while no server has the source open. A live copy is a corrupt copy.
- Bring `secrets` and `settings.json` only if the flow under test needs them.
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
@@ -114,13 +123,13 @@ An empty database is a bad test. Seed your worktree's `.t3` instead of pointing
Clients send typed WebSocket requests. The server turns them into _commands_, a pure _decider_ turns commands into persisted _events_, and a _projector_ derives the read model the UI renders. Provider CLIs run as subprocesses; per-provider _adapters_ translate their native protocols into orchestration events. Side effects run in queue-backed _reactors_ that emit _receipts_ when milestones land. Each turn ends with a _checkpoint_, a hidden git ref, so the app can diff and restore.
Full glossary with file links: `docs/reference/encyclopedia.md`
Full glossary with file links: `docs/internals/glossary.md`
## Where code lives
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` and `docs/operations/effect-fn-checklist.md` before writing Effect code.
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
- `packages/contracts` - Effect/Schema contracts. Schema only, no runtime logic.
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
- `packages/client-runtime` - client code shared by web and mobile.
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
+15 -12
View File
@@ -1,6 +1,6 @@
# T3 Code
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app, [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
@@ -17,13 +17,13 @@ We wanted something performant, remote-ready, and truly open. If we ever go the
>
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `agent login`
> - Grok Build: install [Grok Build CLI](https://x.ai/cli) and run `grok login`
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
### Try it out (install-free)
The easiest way to test T3 Code is to run the server in your terminal:
The easiest way to test T3 Code is to run the server in your terminal (requires Node.js 22.16+, 23.11+, or 24.10+):
```bash
npx t3@latest
@@ -61,17 +61,20 @@ We are very very early in this project. Expect bugs.
We are (mostly) not accepting contributions yet. Small fixes may be considered. Big features will not be.
There's no public docs site yet, checkout the miscellaneous markdown files in [docs](./docs).
## Documentation
- [Getting started](./docs/getting-started/quick-start.md)
- [Remote access](./docs/user/remote-access.md)
- [Keeping T3 Code in sync](./docs/user/server-updates.md)
- [Architecture overview](./docs/architecture/overview.md)
- [Provider guides](./docs/providers/codex.md)
- [Operations](./docs/operations/ci.md)
- [Reference](./docs/reference/encyclopedia.md)
Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
- Linux: [run T3 Code as a background service](./docs/user/background-service.md)
Building from source? Start at [docs/internals/overview.md](./docs/internals/overview.md).
## If you REALLY want to contribute still.... read this first
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.30",
"version": "0.0.31",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+8 -1
View File
@@ -1,5 +1,10 @@
---
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
interface Props {
title?: string;
@@ -69,6 +74,8 @@ const {
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
<a href="/terms-of-service">Terms</a>
<a href="/privacy-policy">Privacy</a>
<a href="/security-policy">Security</a>
+6
View File
@@ -1,5 +1,11 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const IOS_APP_STORE_URL =
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
export const ANDROID_PLAY_STORE_URL =
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
export const MARKETING_STATS = {
githubStars: "14k+",
users: "100,000",
+21 -1
View File
@@ -1,6 +1,7 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -57,6 +58,24 @@ import { RELEASES_URL } from "../lib/releases";
</a>
</div>
</section>
<!-- Mobile -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18.5h2"/></svg>
<h2 class="platform-name">Mobile</h2>
</div>
<div class="download-cards">
<a class="download-card" href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">iPhone &amp; iPad</span>
<span class="card-format">App Store</span>
</a>
<a class="download-card" href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">
<span class="card-arch">Android</span>
<span class="card-format">Google Play</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
@@ -73,7 +92,8 @@ import { RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
try {
const release = await fetchLatestRelease();
+34 -1
View File
@@ -1,6 +1,11 @@
---
import Layout from "../layouts/Layout.astro";
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
import {
ANDROID_PLAY_STORE_URL,
GITHUB_REPOSITORY_URL,
IOS_APP_STORE_URL,
MARKETING_STATS,
} from "../lib/site";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -66,6 +71,12 @@ const mobileEndorsementRows = [
<span>Steal our code (legally)</span>
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
</a>
<p class="hero-mobile-line">
Also on your phone:
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS</a>
<span aria-hidden="true">·</span>
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android</a>
</p>
</div>
<div class="hero-preview">
@@ -578,6 +589,28 @@ const mobileEndorsementRows = [
opacity: 1;
}
.hero-mobile-line {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--fg-dim);
font-size: 13px;
letter-spacing: -0.005em;
}
.hero-mobile-line a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.18s ease, text-decoration-color 0.18s ease;
}
.hero-mobile-line a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* Download button icons (platform-aware) */
.dl-icon {
display: none;
@@ -141,7 +141,7 @@ private final class ComposerTextView: UITextView {
replace(textRange, withText: "")
}
private func loadImages(from providers: [NSItemProvider]) {
func loadImages(from providers: [NSItemProvider]) {
let group = DispatchGroup()
let lock = NSLock()
var images = [UIImage?](repeating: nil, count: providers.count)
@@ -282,7 +282,7 @@ private final class ComposerTextView: UITextView {
}
}
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropDelegate {
private let textView = ComposerTextView()
private let placeholderLabel = UILabel()
private var value = ""
@@ -326,6 +326,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
clipsToBounds = false
textView.delegate = self
textView.textDropDelegate = self
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
@@ -500,6 +501,41 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
return true
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
proposalForDrop drop: UITextDropRequest
) -> UITextDropProposal {
guard droppedImageProviders(in: drop) != nil else {
return drop.suggestedProposal
}
// The composer owns image drops so UIKit does not insert NSTextAttachments
// that the controlled plain-text value cannot represent.
let proposal = UITextDropProposal(operation: .copy)
proposal.dropAction = .insert
proposal.dropPerformer = .delegate
return proposal
}
public func textDroppableView(
_ textDroppableView: UIView & UITextDroppable,
willPerformDrop drop: UITextDropRequest
) {
guard let imageProviders = droppedImageProviders(in: drop) else {
return
}
textView.loadImages(from: imageProviders)
}
private func droppedImageProviders(in drop: UITextDropRequest) -> [NSItemProvider]? {
let providers = drop.dropSession.items.map(\.itemProvider)
guard !providers.isEmpty,
providers.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) else {
return nil
}
return providers
}
public func textViewDidBeginEditing(_ textView: UITextView) {
onComposerFocus()
}
+1 -1
View File
@@ -49,7 +49,7 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "3.2.0",
"@legendapp/list": "3.3.3",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
+10 -1
View File
@@ -284,6 +284,15 @@ function workspacePathFromState(state: NavigationState): string {
return path.startsWith("/") ? path : `/${path}`;
}
// The drain hook subscribes to the outbox, all thread shells, projects, and
// connection statuses. Hosting it in a null-rendering leaf keeps those
// updates from re-rendering RootStackLayout (and with it every screen) on
// each enqueue, shell change, or reconnect.
function ThreadOutboxDrainWorker() {
useThreadOutboxDrain();
return null;
}
function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
@@ -292,7 +301,6 @@ function RootStackLayout(props: {
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.
@@ -320,6 +328,7 @@ function RootStackLayout(props: {
return (
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
@@ -0,0 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
import {
MOBILE_BACKGROUND_RECONNECT_AFTER_MS,
mobileApplicationActiveWakeup,
} from "./app-state-wakeups";
describe("mobileApplicationActiveWakeup", () => {
it("uses a fast probe after a short interruption", () => {
expect(mobileApplicationActiveWakeup(null, 20_000)).toBe("application-active-probe");
expect(
mobileApplicationActiveWakeup(20_000, 20_000 + MOBILE_BACKGROUND_RECONNECT_AFTER_MS - 1),
).toBe("application-active-probe");
});
it("replaces the session after a meaningful background suspension", () => {
expect(
mobileApplicationActiveWakeup(20_000, 20_000 + MOBILE_BACKGROUND_RECONNECT_AFTER_MS),
).toBe("application-active-reconnect");
});
});
@@ -0,0 +1,18 @@
import type { Wakeups } from "@t3tools/client-runtime/connection";
export const MOBILE_BACKGROUND_RECONNECT_AFTER_MS = 10_000;
export type MobileApplicationActiveWakeup = Extract<
Wakeups.ConnectionWakeup,
"application-active-probe" | "application-active-reconnect"
>;
export function mobileApplicationActiveWakeup(
backgroundedAtMs: number | null,
activeAtMs: number,
): MobileApplicationActiveWakeup {
return backgroundedAtMs !== null &&
activeAtMs - backgroundedAtMs >= MOBILE_BACKGROUND_RECONNECT_AFTER_MS
? "application-active-reconnect"
: "application-active-probe";
}
+39 -12
View File
@@ -30,6 +30,7 @@ import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -54,27 +55,53 @@ const connectivityLayer = Connectivity.layer({
),
changes: Stream.callback((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
Network.addNetworkStateListener((state) => {
Effect.sync(() => {
let active = true;
const networkSubscription = Network.addNetworkStateListener((state) => {
Queue.offerUnsafe(queue, networkStatus(state));
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
});
const appStateSubscription = AppState.addEventListener("change", (state) => {
if (state !== "active") {
return;
}
void Network.getNetworkStateAsync()
.then((current) => {
if (active) {
Queue.offerUnsafe(queue, networkStatus(current));
}
})
.catch(() => undefined);
});
return {
close: () => {
active = false;
networkSubscription.remove();
appStateSubscription.remove();
},
};
}),
({ close }) => Effect.sync(close),
).pipe(Effect.asVoid),
),
});
const wakeupsLayer = Wakeups.layer({
changes: Stream.merge(
Stream.callback<"application-active">((queue) =>
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
AppState.addEventListener("change", (state) => {
if (state === "active") {
Queue.offerUnsafe(queue, "application-active");
Effect.sync(() => {
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
return AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
}
}),
),
if (state === "active") {
Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
backgroundedAtMs = null;
}
});
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
@@ -134,7 +134,14 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
case "RelayEnvironmentLinkProofInvalidError":
return `Relay rejected the environment link proof (${error.reason}).`;
case "RelayEnvironmentConnectNotAuthorizedError":
return "Relay rejected the environment connection request.";
// "Not authorized" covers non-auth causes too; surface the reason so a
// missing link doesn't read as a credential problem.
if (error.reason === "environment_link_not_found") {
return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";
}
return error.reason
? `Relay rejected the environment connection request (${error.reason}).`
: "Relay rejected the environment connection request.";
case "RelayEnvironmentEndpointUnavailableError":
return `Relay could not reach the environment endpoint (${error.reason}).`;
case "RelayEnvironmentEndpointTimedOutError":
@@ -11,6 +11,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
import { HomeScreen } from "./HomeScreen";
import { HomeHeader } from "./HomeHeader";
@@ -25,28 +26,35 @@ export function HomeRouteScreen() {
const { layout } = useAdaptiveWorkspaceLayout();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useNavigation();
const [searchQuery, setSearchQuery] = useState("");
useEffect(() => {
void checkForAppUpdateOnLaunch();
}, []);
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
useThreadListActions();
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
const environments = useMemo(() => {
const connectionStateByEnvironmentId = new Map(
workspaceEnvironments.map(
(environment) => [environment.environmentId, environment.connectionState] as const,
),
[savedConnectionsById],
);
);
return Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
connectionState:
connectionStateByEnvironmentId.get(connection.environmentId) ?? "available",
})),
Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
);
}, [savedConnectionsById, workspaceEnvironments]);
const availableEnvironmentIds = useMemo(
() => new Set(environments.map((environment) => environment.environmentId)),
[environments],
+118 -34
View File
@@ -7,6 +7,10 @@ import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -22,11 +26,12 @@ 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 { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -72,7 +77,9 @@ interface HomeScreenProps {
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
readonly environments: ReadonlyArray<
HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
@@ -189,6 +196,35 @@ export function HomeScreen(props: HomeScreenProps) {
const listRef = useRef<LegendListRef | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const searchEnvironmentIds = useMemo(
() =>
props.selectedEnvironmentId === null
? props.environments
.filter((environment) => environment.connectionState === "connected")
.map((environment) => environment.environmentId)
: props.environments.some(
(environment) =>
environment.environmentId === props.selectedEnvironmentId &&
environment.connectionState === "connected",
)
? [props.selectedEnvironmentId]
: [],
[props.environments, props.selectedEnvironmentId],
);
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
const threadSearchMatchByKey = useMemo(() => {
const matches = new Map<string, EnvironmentThreadSearchMatch>();
for (const match of threadSearch.matches) {
if (match.source === "user" || match.source === "assistant") {
matches.set(threadSearchMatchKey(match), match);
}
}
return matches;
}, [threadSearch.matches]);
const matchedThreadKeys = useMemo(
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
[threadSearch.matches],
);
const effectiveGroupDisplayStates = useMemo(() => {
const next = new Map(groupDisplayStates);
if (!AsyncResult.isSuccess(preferencesResult)) {
@@ -318,6 +354,7 @@ export function HomeScreen(props: HomeScreenProps) {
pendingTasks: scopedPendingTasks,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
matchedThreadKeys,
projectSortOrder: props.projectSortOrder,
threadSortOrder: props.threadSortOrder,
projectGroupingMode: props.projectGroupingMode,
@@ -328,6 +365,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
matchedThreadKeys,
scopedPendingTasks,
scopedProjects,
scopedThreads,
@@ -516,6 +554,7 @@ export function HomeScreen(props: HomeScreenProps) {
environmentId: props.selectedEnvironmentId,
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -533,6 +572,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.selectedEnvironmentId,
props.threads,
matchedThreadKeys,
threadListV2Enabled,
v2ScopedProjectGroup,
]);
@@ -629,6 +669,13 @@ export function HomeScreen(props: HomeScreenProps) {
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
@@ -660,14 +707,45 @@ export function HomeScreen(props: HomeScreenProps) {
props.savedConnectionsById,
serverConfigs,
settlementEnvironmentIds,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
props.searchQuery,
],
);
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
// FlatList treats a changed extraData identity as "re-render every visible
// row", so an inline object literal would invalidate all rows on every
// HomeScreen render.
const v2ExtraData = useMemo(
() => ({
projectByKey,
projectCwdByKey,
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
threadSearchMatchByKey,
}),
[
projectByKey,
projectCwdByKey,
props.searchQuery,
props.savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
v2ProjectTitleByProjectKey,
],
);
const extraData = useMemo(
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
[props.savedConnectionsById, projectCwdByKey],
() => ({
projectCwdByKey,
savedConnectionsById: props.savedConnectionsById,
searchQuery: props.searchQuery,
threadSearchMatchByKey,
}),
[projectCwdByKey, props.savedConnectionsById, props.searchQuery, threadSearchMatchByKey],
);
const renderItem = useCallback(
@@ -720,6 +798,13 @@ export function HomeScreen(props: HomeScreenProps) {
null
}
isLast={item.isLast}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onSelectThread={props.onSelectThread}
@@ -750,7 +835,9 @@ export function HomeScreen(props: HomeScreenProps) {
props.onNewThreadInProject,
props.onSelectPendingTask,
props.onSelectThread,
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
updateGroupDisplay,
],
);
@@ -843,7 +930,7 @@ export function HomeScreen(props: HomeScreenProps) {
const v2ListHeader = listHeader;
const listEmpty = !hasResults ? (
hasSearchQuery ? (
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : selectedProjectScope !== null ? (
<EmptyState
@@ -866,31 +953,34 @@ export function HomeScreen(props: HomeScreenProps) {
// threads yet" over an inbox that is merely all-snoozed reads as data
// loss.
const v2SnoozedCount = threadListV2Layout.snoozedCount;
const v2ListEmpty = hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
const v2ListEmpty =
hasSearchQuery && threadSearch.isPending && v2SnoozedCount === 0 ? null : hasSearchQuery ? (
v2SnoozedCount > 0 ? (
// The snoozed threads already passed this search filter: "No
// results" would claim nothing matched when matches are merely
// parked.
<EmptyState
title={
v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`
}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 matching thread snoozed" : `All matching threads snoozed`}
detail={`Threads matching "${props.searchQuery}" are snoozed and return when their wake time passes.`}
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
)
) : v2SnoozedCount > 0 ? (
<EmptyState
title={v2SnoozedCount === 1 ? "1 thread snoozed" : `${v2SnoozedCount} threads snoozed`}
detail="Snoozed threads return when their wake time passes."
/>
) : v2ScopedProjectGroup !== null ? (
<EmptyState
title={`No threads in ${v2ScopedProjectGroup.title}`}
detail="Choose another project or create a new task."
/>
) : (
listEmpty
);
listEmpty
);
if (threadListV2Enabled) {
return (
@@ -900,13 +990,7 @@ export function HomeScreen(props: HomeScreenProps) {
data={threadListV2Items}
renderItem={renderV2Item}
keyExtractor={v2KeyExtractor}
extraData={{
projectByKey,
projectCwdByKey,
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
serverConfigs,
savedConnectionsById: props.savedConnectionsById,
}}
extraData={v2ExtraData}
ListHeaderComponent={v2ListHeader}
ListFooterComponent={
threadListV2Layout.hiddenSettledCount > 0 ? (
@@ -2,6 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -658,6 +659,33 @@ describe("buildHomeThreadGroups", () => {
);
});
it("includes a thread matched by message content", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const thread = makeThread({
environmentId,
id: ThreadId.make("thread-content"),
projectId: project.id,
title: "Unrelated title",
});
const groups = buildGroups([project], [thread], {
searchQuery: "relay reconnect",
matchedThreadKeys: new Set([
threadSearchMatchKey({
environmentId,
threadId: thread.id,
}),
]),
});
expect(groups[0]?.threads.map((candidate) => candidate.id)).toEqual(["thread-content"]);
});
it("targets quick new threads at the group member with the newest thread", () => {
const laptopEnv = EnvironmentId.make("environment-laptop");
const desktopEnv = EnvironmentId.make("environment-desktop");
@@ -12,6 +12,7 @@ import {
sortThreads,
toSortableTimestamp,
} from "@t3tools/client-runtime/state/thread-sort";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type {
EnvironmentId,
ScopedProjectRef,
@@ -254,6 +255,7 @@ export function buildHomeThreadGroups(input: {
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
@@ -350,7 +352,16 @@ export function buildHomeThreadGroups(input: {
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
: group.threads.filter(
(thread) =>
thread.title.toLocaleLowerCase().includes(query) ||
input.matchedThreadKeys?.has(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
) === true,
);
const matchingPendingTasks = groupMatches
? group.pendingTasks
: group.pendingTasks.filter((pendingTask) =>
@@ -0,0 +1,41 @@
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
const ENVIRONMENT_A = EnvironmentId.make("environment-a");
const ENVIRONMENT_B = EnvironmentId.make("environment-b");
function environment(environmentId: EnvironmentId, connectionState: EnvironmentConnectionPhase) {
return { environmentId, connectionState };
}
describe("resolveAddProjectEnvironment", () => {
it("does not redirect an explicit unavailable environment to another environment", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
ENVIRONMENT_A,
),
).toBeNull();
});
it("resolves an explicit connected environment", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "connected"), environment(ENVIRONMENT_B, "connected")],
ENVIRONMENT_A,
)?.environmentId,
).toBe(ENVIRONMENT_A);
});
it("defaults to the first connected environment when no environment is requested", () => {
expect(
resolveAddProjectEnvironment(
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
null,
)?.environmentId,
).toBe(ENVIRONMENT_B);
});
});
@@ -0,0 +1,26 @@
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
export function resolveAddProjectEnvironment<
T extends {
readonly environmentId: EnvironmentId;
readonly connectionState: EnvironmentConnectionPhase;
},
>(environmentOptions: ReadonlyArray<T>, requestedEnvironmentId: EnvironmentId | null): T | null {
if (requestedEnvironmentId !== null) {
return (
environmentOptions.find(
(environment) =>
environment.environmentId === requestedEnvironmentId &&
canCreateProjectInEnvironment(environment.connectionState),
) ?? null
);
}
return (
environmentOptions.find((environment) =>
canCreateProjectInEnvironment(environment.connectionState),
) ?? null
);
}
@@ -4,12 +4,17 @@ import {
addProjectRemoteSourceProvider,
buildAddProjectRemoteSourceReadiness,
buildProjectCreateCommand,
canCreateProjectInEnvironment,
findExistingAddProject,
getAddProjectInitialQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime/operations/projects";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import {
canPreloadBrowsePath,
createBrowseNavigationCoordinator,
@@ -24,7 +29,7 @@ import {
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { StackActions, useNavigation } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
@@ -46,15 +51,20 @@ import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import {
useRemoteConnectionStatus,
useRemoteEnvironmentRuntime,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly platform: string;
readonly baseDirectory: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
}
const environmentOptionOrder = Order.mapInput(
@@ -227,10 +237,13 @@ function ProjectPathInput(props: {
}
function useBrowsePathInput(environment: EnvironmentOption | null) {
const environmentId = environment?.environmentId ?? null;
const environmentBaseDirectory = environment?.baseDirectory ?? null;
const [pathInput, commitPathInput] = useState(() =>
getAddProjectInitialQuery(environment?.baseDirectory),
getAddProjectInitialQuery(environmentBaseDirectory),
);
const environmentRuntime = useRemoteEnvironmentRuntime(environment?.environmentId ?? null);
const previousEnvironmentIdRef = useRef(environmentId);
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
reportFailure: false,
reportDefect: false,
@@ -268,10 +281,11 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
);
useEffect(() => {
if (environment) {
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
previousEnvironmentIdRef.current = environmentId;
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
}
}, [environment, setPathInput]);
}, [environmentBaseDirectory, environmentId, setPathInput]);
useEffect(
() => () => {
@@ -286,19 +300,27 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const serverConfigByEnvironmentId = useServerConfigs();
const { savedConnectionsById } = useSavedRemoteConnections();
const { connectedEnvironments } = useRemoteConnectionStatus();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
const runtimeByEnvironmentId = new Map(
connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
);
const options = Object.values(savedConnectionsById).map((connection) => {
const config = serverConfigByEnvironmentId.get(connection.environmentId);
const runtime = runtimeByEnvironmentId.get(connection.environmentId);
return {
environmentId: connection.environmentId,
label: connection.environmentLabel,
platform: platformFromOs(config?.environment.platform.os ?? null),
baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
connectionState: runtime?.connectionState ?? "available",
connectionError: runtime?.connectionError ?? null,
connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
};
});
return Arr.sort(options, environmentOptionOrder);
}, [savedConnectionsById, serverConfigByEnvironmentId]);
}, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
}
function useSelectedEnvironment(): {
@@ -309,8 +331,14 @@ function useSelectedEnvironment(): {
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const environmentOptions = useEnvironmentOptions();
const selectedEnvironment =
environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
environmentOptions[0] ??
environmentOptions.find(
(environment) =>
environment.environmentId === selectedEnvironmentId &&
canCreateProjectInEnvironment(environment.connectionState),
) ??
environmentOptions.find((environment) =>
canCreateProjectInEnvironment(environment.connectionState),
) ??
null;
return {
@@ -325,9 +353,9 @@ function EmptyEnvironmentState() {
return (
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
<Text className="text-center text-lg font-t3-bold">No environments connected</Text>
<Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
<Text className="text-center text-sm leading-normal text-foreground-muted">
Add an environment before adding a project.
Start or reconnect an environment before adding a project.
</Text>
<Pressable
onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
@@ -407,17 +435,25 @@ export function AddProjectSourceScreen() {
return (
<AddProjectShell>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
{selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
{environmentOptions.length > 1 ? (
<>
<SectionTitle>Connected environments</SectionTitle>
<SectionTitle>Environments</SectionTitle>
<ListSection>
{environmentOptions.map((environment, index) => (
<ListRow
key={environment.environmentId}
title={environment.label}
subtitle={environment.environmentId}
subtitle={
canCreateProjectInEnvironment(environment.connectionState)
? environment.environmentId
: connectionStatusText({
phase: environment.connectionState,
error: environment.connectionError,
traceId: environment.connectionErrorTraceId,
})
}
icon={
<SymbolView
name="server.rack"
@@ -427,6 +463,7 @@ export function AddProjectSourceScreen() {
/>
}
selected={environment.environmentId === selectedEnvironment?.environmentId}
disabled={!canCreateProjectInEnvironment(environment.connectionState)}
isFirst={index === 0}
right={
environment.environmentId === selectedEnvironment?.environmentId ? (
@@ -500,7 +537,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
return useCallback(
async (workspaceRoot: string) => {
if (!environment) return;
if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
const existing = findExistingAddProject({
projects,
@@ -550,11 +587,7 @@ function useEnvironmentFromParam(
): EnvironmentOption | null {
const environmentOptions = useEnvironmentOptions();
const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
return (
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
environmentOptions[0] ??
null
);
return resolveAddProjectEnvironment(environmentOptions, environmentId);
}
export function AddProjectRepositoryScreen(props: {
@@ -618,26 +651,32 @@ export function AddProjectRepositoryScreen(props: {
return (
<AddProjectShell>
{error ? <ErrorBanner message={error} /> : null}
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
loading={isSubmitting}
/>
{environment ? (
<>
<TextInput
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
value={repositoryInput}
onChangeText={setRepositoryInput}
autoCapitalize="none"
autoCorrect={false}
placeholder={
source === "url"
? "https://github.com/org/repo.git"
: addProjectRemoteSourcePathHint(source)
}
returnKeyType="next"
onSubmitEditing={() => void lookupRepository()}
/>
<PrimaryActionButton
label={source === "url" ? "Continue" : "Lookup repository"}
disabled={isSubmitting || repositoryInput.trim().length === 0}
onPress={() => void lookupRepository()}
loading={isSubmitting}
/>
</>
) : (
<EmptyEnvironmentState />
)}
</AddProjectShell>
);
}
@@ -9,19 +9,10 @@ import { SymbolView } from "../../components/AppSymbol";
import * as Effect from "effect/Effect";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import {
ActivityIndicator,
Alert,
Linking,
Platform,
Pressable,
ScrollView,
View,
} from "react-native";
import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
reportAtomCommandResult,
settleAsyncResult,
@@ -47,6 +38,11 @@ import { runtime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -578,12 +574,11 @@ function BetaSettingsSection() {
);
}
type UpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
function AppSettingsSection() {
const icon = useThemeColor("--color-icon");
const [updateState, setUpdateState] = useState<UpdateCheckState>("idle");
const [updateState, setUpdateState] = useState<AppUpdateCheckState>("idle");
const updateInFlight = useRef(false);
const hiddenUpdateTapCount = useRef(0);
const version = Constants.expoConfig?.version ?? "0.0.0";
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
@@ -591,22 +586,11 @@ function AppSettingsSection() {
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
// Which JS is actually running: the bundle shipped in the binary, or an OTA
// update downloaded on top of it. Surfacing this makes "am I even on the
// right build?" answerable at a glance.
const bundleLabel = Updates.isEnabled
? Updates.isEmbeddedLaunch
? "Embedded"
: Updates.updateId
? `OTA ${Updates.updateId.slice(0, 7)}`
: null
: null;
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
// "Up to date" is a transient acknowledgement, not a state worth persisting —
// drop back to the bundle label so the row keeps answering "what am I running?".
// return the version row to its normal, deliberately quiet state.
useEffect(() => {
if (updateState !== "current") return;
const timer = setTimeout(() => setUpdateState("idle"), 3000);
@@ -619,12 +603,24 @@ function AppSettingsSection() {
if (updateInFlight.current) return;
updateInFlight.current = true;
try {
await runUpdateCheck(setUpdateState);
await runAppUpdateCheck({
onFailure: (message) => Alert.alert("Update failed", message),
onStateChange: setUpdateState,
});
} finally {
updateInFlight.current = false;
}
}, []);
const handleVersionPress = useCallback(() => {
if (!Updates.isEnabled || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate]);
const statusLabel =
updateState === "checking"
? "Checking…"
@@ -634,7 +630,7 @@ function AppSettingsSection() {
? "Restarting…"
: updateState === "current"
? "Up to date"
: bundleLabel;
: null;
const versionRow = (
<View className="flex-row items-center gap-4 p-4">
@@ -652,21 +648,6 @@ function AppSettingsSection() {
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
) : null}
</View>
{Updates.isEnabled ? (
<View className="w-[22px] items-center">
{busy ? (
<ActivityIndicator color={icon} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={18}
tintColor={icon}
type="monochrome"
weight="semibold"
/>
)}
</View>
) : null}
</View>
);
@@ -676,10 +657,10 @@ function AppSettingsSection() {
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{Updates.isEnabled ? (
<Pressable
accessibilityLabel="Check for updates"
accessibilityRole="button"
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
disabled={busy}
onPress={() => void checkForUpdate()}
onPress={handleVersionPress}
>
{versionRow}
</Pressable>
@@ -690,52 +671,6 @@ function AppSettingsSection() {
);
}
async function runUpdateCheck(setUpdateState: (state: UpdateCheckState) => void): Promise<void> {
setUpdateState("checking");
const check = await settlePromise(() => Updates.checkForUpdateAsync());
if (check._tag === "Failure") {
reportUpdateFailure(check, "Could not check for updates.");
setUpdateState("idle");
return;
}
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
// with isRollBackToEmbedded: true — there is nothing newer to install, but the
// running OTA still has to be dropped for the embedded bundle.
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
setUpdateState("current");
return;
}
setUpdateState("downloading");
const fetched = await settlePromise(() => Updates.fetchUpdateAsync());
if (fetched._tag === "Failure") {
reportUpdateFailure(fetched, "Could not download the update.");
setUpdateState("idle");
return;
}
// isNew is always false for a rollback, so it can't be the sole gate here either.
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
setUpdateState("current");
return;
}
setUpdateState("restarting");
// reloadAsync never resolves on success — the JS context is torn down — so
// reaching the failure branch below is the only way this returns.
const reloaded = await settlePromise(() => Updates.reloadAsync());
if (reloaded._tag === "Failure") {
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.");
setUpdateState("idle");
}
}
function reportUpdateFailure(result: AtomCommandResult<unknown, unknown>, fallback: string): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
Alert.alert("Update failed", error instanceof Error ? error.message : fallback);
}
function capitalize(value: string): string {
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
}
@@ -15,6 +15,7 @@ import {
type IncomingShareDestination,
type IncomingShareDraft,
} from "./incoming-share-model";
import { createIncomingSharePayloadReader } from "./incoming-share-native";
import { IncomingShareInbox } from "./incoming-share-inbox";
import {
loadIncomingShareDrafts,
@@ -48,6 +49,11 @@ function receiveSharingEnabled(): boolean {
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
}
const getIncomingSharePayloads = createIncomingSharePayloadReader({
platform: Platform.OS,
readPayloads: getSharedPayloads,
});
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
try {
return await getResolvedSharedPayloadsAsync();
@@ -121,7 +127,7 @@ const incomingShareInbox = new IncomingShareInbox({
loadDrafts: loadIncomingShareDrafts,
writeDraft: writeIncomingShareDraft,
removeDraft: removeIncomingShareDraft,
getPayloads: getSharedPayloads,
getPayloads: getIncomingSharePayloads,
clearPayloads: clearSharedPayloads,
buildDraft: async ({ payloads, id, createdAt }) => {
const cleanupUris = new Set<string>();
@@ -0,0 +1,46 @@
import { describe, expect, it, vi } from "@effect/vitest";
import type { SharePayload } from "expo-sharing";
import { createIncomingSharePayloadReader } from "./incoming-share-native";
const PAYLOAD: SharePayload = {
shareType: "text",
mimeType: "text/plain",
value: "Fix this",
};
describe("createIncomingSharePayloadReader", () => {
it("treats a missing iOS App Group as an unavailable inbox", () => {
const readPayloads = vi.fn((): ReadonlyArray<SharePayload> => {
throw Object.assign(new Error("Expo-sharing has failed to fetch the app group id"), {
code: "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID",
});
});
const read = createIncomingSharePayloadReader({ platform: "ios", readPayloads });
expect(read()).toEqual([]);
expect(read()).toEqual([]);
expect(readPayloads).toHaveBeenCalledTimes(1);
});
it("returns native payloads when receiving is available", () => {
const read = createIncomingSharePayloadReader({
platform: "ios",
readPayloads: () => [PAYLOAD],
});
expect(read()).toEqual([PAYLOAD]);
});
it("preserves other native errors", () => {
const error = new Error("native failure");
const read = createIncomingSharePayloadReader({
platform: "ios",
readPayloads: () => {
throw error;
},
});
expect(read).toThrow(error);
});
});
@@ -0,0 +1,37 @@
import type { SharePayload } from "expo-sharing";
const IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE = "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID";
function errorCode(error: unknown): string | null {
if (typeof error !== "object" || error === null || !("code" in error)) {
return null;
}
return typeof error.code === "string" ? error.code : null;
}
/**
* Normalizes the native "share into" capability to an empty inbox. Personal
* Team builds cannot include the App Group that expo-sharing reads from.
*/
export function createIncomingSharePayloadReader(input: {
readonly platform: string;
readonly readPayloads: () => ReadonlyArray<SharePayload>;
}): () => ReadonlyArray<SharePayload> {
let isUnavailable = false;
return () => {
if (isUnavailable) {
return [];
}
try {
return input.readPayloads();
} catch (error) {
if (input.platform === "ios" && errorCode(error) === IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE) {
isUnavailable = true;
return [];
}
throw error;
}
};
}
@@ -54,7 +54,14 @@ function useShortcutNavigation(): void {
}
function useRecentThreadShortcutSync(state: NavigationState): void {
const threadRef = useMemo(() => activeThreadRef(state), [state]);
// Launcher shortcuts are Android-only. A null ref on iOS keeps this hook
// (mounted in the root stack layout) from subscribing the root to the
// active thread's shell, which would re-render every screen on each
// title/status/session change.
const threadRef = useMemo(
() => (Platform.OS === "android" ? activeThreadRef(state) : null),
[state],
);
const threadShell = useThreadShell(threadRef);
// null until the persisted list loads; recording waits on it so the first
// thread opened after a cold start cannot clobber older entries.
@@ -946,7 +946,11 @@ export function NewTaskDraftScreen(props: {
const promptEditor = (
<ComposerEditor
ref={promptInputRef}
autoFocus={!isAndroid}
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
// forces the iOS keyboard bring-up during the formSheet present
// animation and stalls it. The runAfterInteractions effect above focuses
// the editor once the transition settles instead.
autoFocus={false}
editable={!isIncomingShareTransferPending}
multiline
scrollEnabled={isExpanded}
@@ -203,13 +203,17 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
title={screenTitle}
subtitle={incomingShareSubtitle}
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
actions={[
{
accessibilityLabel: "Add project",
icon: "plus",
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
},
]}
actions={
catalogState.hasReadyEnvironment
? [
{
accessibilityLabel: "Add project",
icon: "plus",
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
},
]
: []
}
/>
</>
) : (
@@ -229,11 +233,13 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
separateBackground
/>
) : null}
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
separateBackground
/>
{catalogState.hasReadyEnvironment ? (
<NativeHeaderToolbar.Button
icon="plus"
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
separateBackground
/>
) : null}
</NativeHeaderToolbar>
</>
)}
@@ -517,14 +517,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
// Sending a prompt starts agent work: arm the lock-screen card now, while
// the app is foregrounded and the activity token can be registered.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
try {
await onSendMessage();
// Sending a prompt starts agent work: arm the lock-screen card while the
// app is foregrounded and the activity token can be registered. Armed
// after the send so its preference read and native Activity start don't
// contend with the queued-message feedback on the tap frame.
armAgentAwarenessLiveActivityForLocalWork({
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
} finally {
inFlightThreadIdsRef.current.delete(threadKey);
}
+107 -6
View File
@@ -57,7 +57,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
FadeIn,
FadeInUp,
LinearTransition,
useSharedValue,
withTiming,
type LayoutAnimationsValues,
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -90,7 +92,9 @@ import { uuidv4 } from "../../lib/uuid";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
scaledTypographyLineHeight,
} from "../../lib/appearancePreferences";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
@@ -102,7 +106,12 @@ import {
type ThreadFeedLatestRun,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
ThreadWorkLog,
WORK_GROUP_TOGGLE_HEIGHT,
} from "./thread-work-log";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { appAtomRegistry } from "../../state/atom-registry";
@@ -126,8 +135,22 @@ function formatMessageTime(input: string): string {
}
// Rows shift when content above them grows (streaming text, work-log folds);
// animating the container position turns those jumps into slides.
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
// animating the container position turns those jumps into slides. Applied
// conditionally — see the gated transition in ThreadFeed: while browsing
// history the animation must NOT run, or every estimate→actual size
// correction plays as a visible slide against the instant scroll-offset
// compensation from maintainVisibleContentPosition.
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
// classNames. The fold row's min-h-11 (44px) stays taller than its single
// text-sm line at every supported base font size (26px at the 22pt maximum),
// so its height is a constant; a drifted value costs one correction on
// measure, not a persistent offset.
const TURN_FOLD_HEIGHT = 56; // min-h-11 (44) + mb-3 (12)
// The working row has no min-height clamp — its height follows the scaled
// text-xs line height (see workingRowHeight in ThreadFeed).
const WORKING_ROW_VERTICAL_EXTRAS = 24; // py-1 (8) + mb-4 (16)
// Entering animations must only play for rows born just now — LegendList
// remounts rows when they scroll back into view, and replaying an entrance for
@@ -1447,6 +1470,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
);
@@ -1558,6 +1582,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
},
[props.onHeaderMaterialVisibilityChange],
);
// True while the viewport sits within ~one screen of the list end — the
// only region where layout shifts should animate. Starts true because the
// list opens pinned to the end.
const nearListEnd = useSharedValue(true);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
// anchorTopInset, not topContentInset: under automatic insets the list
@@ -1565,9 +1594,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
nearListEnd.value =
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
},
[reportHeaderMaterialVisibility, anchorTopInset],
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
);
// Gated variant of the 180ms feed layout slide. Instant while browsing
// history: maintainVisibleContentPosition compensates the scroll offset in
// the same frame a row's measured size lands, so an instant reposition is
// invisible — animating it is exactly what made cold upward scrolls slide
// and jump. Near the end the slide stays on: streaming growth and sends
// shift rows at rest, where the animation is the thing preventing a hard
// visual snap.
const feedItemLayoutTransition = useMemo(() => {
return (values: LayoutAnimationsValues) => {
"worklet";
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
return {
initialValues: {
originX: values.currentOriginX,
originY: values.currentOriginY,
width: values.currentWidth,
height: values.currentHeight,
},
animations: {
originX: withTiming(values.targetOriginX, { duration }),
originY: withTiming(values.targetOriginY, { duration }),
width: withTiming(values.targetWidth, { duration }),
height: withTiming(values.targetHeight, { duration }),
},
};
};
}, [nearListEnd]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -1769,6 +1829,38 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
setExpandedImage({ uri, headers });
}, []);
// Rows whose height is known before they ever render. Without this, every
// row above the viewport is assumed to be estimatedItemSize tall, and
// scrolling up through unmeasured content corrects each row's height as it
// mounts — the feed visibly jumps. Fixed sizes make the small chrome rows
// exact; message rows stay undefined and use LegendList's per-type running
// average once one of their type has been measured. Text-driven heights
// follow the configurable base font size via scaledTypographyLineHeight.
const workingRowHeight =
WORKING_ROW_VERTICAL_EXTRAS +
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.label, appearance.baseFontSize);
const getFixedItemSize = useCallback(
(entry: ThreadFeedEntry) => {
switch (entry.type) {
case "run-fold":
return TURN_FOLD_HEIGHT;
case "work-toggle":
return WORK_GROUP_TOGGLE_HEIGHT;
case "working":
return workingRowHeight;
case "activity-group":
// Expanded rows append a variable detail block — fall back to
// measurement for those groups.
return entry.activities.some((activity) => expandedWorkRows[activity.id])
? undefined
: collapsedWorkLogHeight(entry.activities, appearance.baseFontSize);
default:
return undefined;
}
},
[expandedWorkRows, workingRowHeight, appearance.baseFontSize],
);
const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, {
@@ -1866,7 +1958,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
itemLayoutAnimation={feedItemLayoutTransition}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
@@ -1910,6 +2002,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
getItemType={(entry) =>
entry.type === "message" ? `message:${entry.message.role}` : entry.type
}
getFixedItemSize={getFixedItemSize}
// Measure rows well before they scroll into view so estimate→actual
// corrections land offscreen instead of under the user's finger.
drawDistance={500}
keyboardShouldPersistTaps="always"
keyboardDismissMode="none"
keyboardLiftBehavior="whenAtEnd"
@@ -1929,6 +2025,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// user overscroll back to the adjusted rest position.
scrollToOverflowEnabled
estimatedItemSize={180}
// Chat-style bottom alignment: when a thread is shorter than the
// viewport, pad above the content so messages rest just above the
// composer instead of under the header. No effect on threads that
// overflow the viewport (the padding clamps to zero).
alignItemsAtEnd
initialScrollAtEnd
onScroll={handleScroll}
scrollEventThrottle={16}
@@ -3,6 +3,10 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
@@ -24,6 +28,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -180,7 +185,7 @@ function ThreadNavigationSidebarPane(
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const [headerIsOverContent, setHeaderIsOverContent] = useState(false);
const searchInputRef = useRef<TextInput>(null);
@@ -209,6 +214,35 @@ function ThreadNavigationSidebarPane(
);
const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
useHomeListOptions(availableEnvironmentIds);
const searchEnvironmentIds = useMemo(
() =>
options.selectedEnvironmentId === null
? workspaceEnvironments
.filter((environment) => environment.connectionState === "connected")
.map((environment) => environment.environmentId)
: workspaceEnvironments.some(
(environment) =>
environment.environmentId === options.selectedEnvironmentId &&
environment.connectionState === "connected",
)
? [options.selectedEnvironmentId]
: [],
[options.selectedEnvironmentId, workspaceEnvironments],
);
const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
const threadSearchMatchByKey = useMemo(() => {
const matches = new Map<string, EnvironmentThreadSearchMatch>();
for (const match of threadSearch.matches) {
if (match.source === "user" || match.source === "assistant") {
matches.set(threadSearchMatchKey(match), match);
}
}
return matches;
}, [threadSearch.matches]);
const matchedThreadKeys = useMemo(
() => new Set(threadSearch.matches.map(threadSearchMatchKey)),
[threadSearch.matches],
);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const projectScopes = useMemo(
() =>
@@ -305,11 +339,19 @@ function ThreadNavigationSidebarPane(
pendingTasks: scopedPendingTasks,
environmentId: options.selectedEnvironmentId,
searchQuery: props.searchQuery,
matchedThreadKeys,
projectSortOrder: options.projectSortOrder,
threadSortOrder: options.threadSortOrder,
projectGroupingMode: options.projectGroupingMode,
}),
[options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
[
matchedThreadKeys,
options,
props.searchQuery,
scopedPendingTasks,
scopedProjects,
scopedThreads,
],
);
const [groupDisplayStates, setGroupDisplayStates] = useState<
ReadonlyMap<string, HomeGroupDisplayState>
@@ -432,6 +474,7 @@ function ThreadNavigationSidebarPane(
environmentId: options.selectedEnvironmentId,
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -445,6 +488,7 @@ function ThreadNavigationSidebarPane(
snoozeWakeTick,
options.selectedEnvironmentId,
props.searchQuery,
matchedThreadKeys,
settledVisibleCount,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -687,6 +731,7 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
}),
[
props.selectedThreadKey,
@@ -695,6 +740,7 @@ function ThreadNavigationSidebarPane(
projectTitleByProjectKey,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
],
);
const sidebarItemsAreEqual = useCallback(
@@ -797,6 +843,13 @@ function ThreadNavigationSidebarPane(
? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
: null
}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
pane="sidebar"
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
@@ -876,6 +929,13 @@ function ThreadNavigationSidebarPane(
null
}
isLast={item.isLast}
searchMatch={threadSearchMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
)}
searchQuery={props.searchQuery}
selected={
scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
}
@@ -914,10 +974,12 @@ function ThreadNavigationSidebarPane(
projectCwdByKey,
projectTitleByProjectKey,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
props.width,
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -977,13 +1039,15 @@ function ThreadNavigationSidebarPane(
{catalogState.isLoadingConnections
? "Loading threads…"
: props.searchQuery.trim().length > 0
? snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
? threadSearch.isPending && snoozedCount === 0
? "Searching thread messages…"
: snoozedCount > 0
? // Snoozed matches passed this same search filter — "No
// matching threads" would misreport them as nonexistent.
snoozedCount === 1
? "1 matching thread snoozed"
: "All matching threads snoozed"
: "No matching threads"
: snoozedCount > 0
? snoozedCount === 1
? "1 thread snoozed"
@@ -3,6 +3,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import type { MenuAction } from "@react-native-menu/menu";
import { SymbolView } from "../../components/AppSymbol";
import { memo, useCallback, useMemo, type ComponentProps } from "react";
@@ -21,6 +22,7 @@ import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
* Shared presentation for the thread lists: the compact (phone) Home list and
@@ -416,6 +418,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly projectCwd: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string;
readonly isLast: boolean;
/** Sidebar only: the thread currently open in the detail pane. */
readonly selected?: boolean;
@@ -569,6 +573,13 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
/>
</View>
</View>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
compact
match={props.searchMatch}
query={props.searchQuery ?? ""}
/>
) : null}
{subtitleRow}
</View>
</View>
@@ -623,6 +634,13 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
</Text>
</View>
</View>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
) : null}
{subtitleRow}
</View>
</Pressable>
@@ -2,6 +2,7 @@ import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, type ComponentProps } from "react";
import { Platform, Pressable, useWindowDimensions, View } from "react-native";
@@ -22,6 +23,7 @@ import {
threadHasUnseenCompletion,
type ThreadListV2Status,
} from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
@@ -247,6 +249,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
state: "open" | "closed" | "merged" | null,
) => void;
readonly projectCwd?: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
@@ -379,6 +383,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
>
{thread.title}
</Text>
{props.searchMatch ? (
<View className="mt-1">
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
</View>
) : null}
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.runtime?.lastError ? (
<Text
@@ -527,15 +540,24 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
/>
</View>
) : null}
<Text
className={cn(
"flex-1 text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.title}
</Text>
<View className="min-w-0 flex-1">
<Text
className={cn(
"text-base",
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
)}
numberOfLines={1}
>
{thread.title}
</Text>
{props.searchMatch ? (
<ThreadSearchMatchExcerpt
match={props.searchMatch}
query={props.searchQuery ?? ""}
selected={selected}
/>
) : null}
</View>
<Text
className={cn(
"text-sm tabular-nums",
@@ -0,0 +1,92 @@
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
function splitHighlightParts(text: string, query: string) {
const normalizedText = foldAsciiCase(text);
const normalizedQuery = foldAsciiCase(query.trim());
if (normalizedQuery.length === 0) {
return [{ text, highlighted: false, start: 0 }];
}
const parts: Array<{
readonly text: string;
readonly highlighted: boolean;
readonly start: number;
}> = [];
let cursor = 0;
while (cursor < text.length) {
const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);
if (matchIndex === -1) {
parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
break;
}
if (matchIndex > cursor) {
parts.push({
text: text.slice(cursor, matchIndex),
highlighted: false,
start: cursor,
});
}
parts.push({
text: text.slice(matchIndex, matchIndex + normalizedQuery.length),
highlighted: true,
start: matchIndex,
});
cursor = matchIndex + normalizedQuery.length;
}
return parts;
}
export function ThreadSearchMatchExcerpt(props: {
readonly match: EnvironmentThreadSearchMatch;
readonly query: string;
readonly selected?: boolean;
readonly compact?: boolean;
}) {
const isUser = props.match.source === "user";
const parts = splitHighlightParts(props.match.snippet, props.query);
return (
<Text
className={cn(
props.compact ? "text-sm" : "text-xs",
props.selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
)}
numberOfLines={1}
>
<Text
className={cn(
props.compact ? "text-sm font-t3-medium" : "text-xs font-t3-medium",
props.selected
? "text-user-bubble-foreground"
: isUser
? "text-blue-500 dark:text-blue-400"
: "text-emerald-600 dark:text-emerald-400",
)}
>
{isUser ? "You:" : "Agent:"}{" "}
</Text>
{parts.map((part) => (
<Text
className={cn(
props.compact ? "text-sm" : "text-xs",
part.highlighted && "font-t3-bold",
props.selected
? "text-user-bubble-foreground"
: part.highlighted
? "text-foreground"
: "text-foreground-muted",
)}
key={part.start}
>
{part.text}
</Text>
))}
</Text>
);
}
@@ -7,8 +7,10 @@ import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import Animated, { FadeIn } from "react-native-reanimated";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { ThreadActivityInspector } from "./ThreadActivityInspector";
@@ -166,6 +168,46 @@ function isFreshRow(createdAt: string): boolean {
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
}
// Tool-like activities with a neutral status carry no signal worth a row.
export function visibleWorkLogActivities(
activities: ReadonlyArray<ThreadFeedActivity>,
): ReadonlyArray<ThreadFeedActivity> {
return activities.filter((activity) => !(activity.toolLike && activity.status === "neutral"));
}
// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log
// rows are single-line (numberOfLines={1}) inside a min-height that stays
// taller than the text at every supported base font size (text-xs reaches
// 23px at the 22pt maximum, under the 32px min-h-8), so row height is
// deterministic. The "work log" label has no such clamp — its height follows
// the scaled text-2xs line height. Values mirror the classNames below — keep
// them in sync; a mismatch only costs a one-time correction on measure.
const WORK_ROW_HEIGHT = 32; // min-h-8
const WORK_ROW_GAP = 1; // gap-px
const WORK_LOG_HEADER_PADDING = 2; // pb-0.5 under the "work log" label
const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1
export const WORK_GROUP_TOGGLE_HEIGHT = 36; // min-h-8 (32) + mb-1 (4)
export function collapsedWorkLogHeight(
activities: ReadonlyArray<ThreadFeedActivity>,
baseFontSize: number,
): number {
const rows = visibleWorkLogActivities(activities);
if (rows.length === 0) {
return 0;
}
const onlyToolRows = rows.every((row) => row.toolLike);
const headerHeight =
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING;
return (
WORK_LOG_BOTTOM_MARGIN +
(onlyToolRows ? 0 : headerHeight) +
rows.length * WORK_ROW_HEIGHT +
(rows.length - 1) * WORK_ROW_GAP
);
}
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
@@ -181,7 +223,10 @@ export function ThreadWorkLog(props: {
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const rows = props.activities;
const rows = visibleWorkLogActivities(props.activities).map((activity) => ({
...activity,
detail: compactActivityDetail(activity.detail),
}));
if (rows.length === 0) {
return null;
@@ -1,4 +1,5 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import {
CommandId,
EnvironmentId,
@@ -307,6 +308,27 @@ describe("buildThreadListV2Items", () => {
]);
});
it("includes a thread matched by message content", () => {
const thread = makeThread({
id: ThreadId.make("content-match"),
title: "Unrelated title",
});
const { items } = buildThreadListV2Items({
threads: [thread],
environmentId: null,
searchQuery: "relay reconnect",
matchedThreadKeys: new Set([
threadSearchMatchKey({
environmentId,
threadId: thread.id,
}),
]),
now: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["content-match"]);
});
it("scopes the flat list to one project", () => {
const projectId = ProjectId.make("project-1");
const otherProjectId = ProjectId.make("project-2");
@@ -1,5 +1,6 @@
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -207,6 +208,7 @@ export function buildThreadListV2Items(input: {
readonly projectId: ProjectId;
}> | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
/** Environments whose server supports thread.settle/unsettle. Threads on
@@ -247,7 +249,18 @@ export function buildThreadListV2Items(input: {
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
continue;
}
if (query.length > 0 && !thread.title.toLocaleLowerCase().includes(query)) continue;
if (
query.length > 0 &&
!thread.title.toLocaleLowerCase().includes(query) &&
input.matchedThreadKeys?.has(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
) !== true
) {
continue;
}
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
@@ -0,0 +1,252 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
createAppUpdateLaunchCheck,
registerHiddenUpdateTap,
runAppUpdateCheck,
type AppUpdateCheckState,
type AppUpdateClient,
} from "./app-updates";
vi.mock("expo-updates", () => ({
isEnabled: true,
checkForUpdateAsync: vi.fn(),
fetchUpdateAsync: vi.fn(),
reloadAsync: vi.fn(),
}));
function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
return {
isEnabled: true,
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: false,
isRollBackToEmbedded: false,
})),
fetchUpdateAsync: vi.fn(async () => ({
isNew: true,
isRollBackToEmbedded: false,
})),
reloadAsync: vi.fn(async () => {}),
...overrides,
};
}
describe("runAppUpdateCheck", () => {
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: true,
isRollBackToEmbedded: false,
})),
});
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
expect(client.reloadAsync).toHaveBeenCalledOnce();
expect(states).toEqual(["checking", "downloading", "restarting"]);
});
it("restarts into the embedded bundle for a rollback directive", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
isAvailable: false,
isRollBackToEmbedded: true,
})),
fetchUpdateAsync: vi.fn(async () => ({
isNew: false,
isRollBackToEmbedded: true,
})),
});
await runAppUpdateCheck({ client });
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
expect(client.reloadAsync).toHaveBeenCalledOnce();
});
it("stops quietly when the running bundle is current", async () => {
const client = makeUpdateClient();
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
expect(client.fetchUpdateAsync).not.toHaveBeenCalled();
expect(client.reloadAsync).not.toHaveBeenCalled();
expect(states).toEqual(["checking", "current"]);
});
it("reports manual failures without continuing the update", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => {
throw new Error("offline");
}),
});
const failures: string[] = [];
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => states.push(state),
});
expect(client.fetchUpdateAsync).not.toHaveBeenCalled();
expect(failures).toEqual(["offline"]);
expect(states).toEqual(["checking", "idle"]);
reportError.mockRestore();
});
it("coalesces overlapping launch and manual checks", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((resolve) => {
resolveCheck = resolve;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const manualStates: AppUpdateCheckState[] = [];
const launchCheck = checkOnLaunch();
const manualCheck = runAppUpdateCheck({
client,
onStateChange: (state) => manualStates.push(state),
});
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(manualStates).toEqual(["checking"]);
resolveCheck({
isAvailable: false,
isRollBackToEmbedded: false,
});
await Promise.all([launchCheck, manualCheck]);
expect(manualStates).toEqual(["checking", "current"]);
await runAppUpdateCheck({ client });
expect(client.checkForUpdateAsync).toHaveBeenCalledTimes(2);
});
it("forwards failures to a manual check coalesced with the launch check", async () => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
let rejectCheck!: (error: Error) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((_resolve, reject) => {
rejectCheck = reject;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const failures: string[] = [];
const manualStates: AppUpdateCheckState[] = [];
const launchCheck = checkOnLaunch();
const manualCheck = runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => manualStates.push(state),
});
rejectCheck(new Error("offline"));
await Promise.all([launchCheck, manualCheck]);
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(failures).toEqual(["offline"]);
expect(manualStates).toEqual(["checking", "idle"]);
reportError.mockRestore();
});
it("publishes the in-flight check before a state callback can re-enter", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}) => void;
const checkResult = new Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>((resolve) => {
resolveCheck = resolve;
});
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(() => checkResult),
});
const reentrantStates: AppUpdateCheckState[] = [];
let reentrantCheck: Promise<void> | undefined;
let didReenter = false;
const initialCheck = runAppUpdateCheck({
client,
onStateChange: (state) => {
if (state !== "checking" || didReenter) return;
didReenter = true;
reentrantCheck = runAppUpdateCheck({
client,
onStateChange: (reentrantState) => reentrantStates.push(reentrantState),
});
},
});
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(reentrantCheck).toBeDefined();
expect(reentrantStates).toEqual(["checking"]);
resolveCheck({
isAvailable: false,
isRollBackToEmbedded: false,
});
await Promise.all([initialCheck, reentrantCheck]);
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
expect(reentrantStates).toEqual(["checking", "current"]);
});
});
describe("createAppUpdateLaunchCheck", () => {
it("checks at most once for each JavaScript launch", async () => {
const client = makeUpdateClient();
const checkOnLaunch = createAppUpdateLaunchCheck(client);
const first = checkOnLaunch();
const second = checkOnLaunch();
await first;
expect(second).toBeUndefined();
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
});
it("does nothing when Expo updates are disabled", () => {
const client = makeUpdateClient({ isEnabled: false });
const checkOnLaunch = createAppUpdateLaunchCheck(client);
expect(checkOnLaunch()).toBeUndefined();
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
});
describe("registerHiddenUpdateTap", () => {
it("unlocks the manual check on the fifth tap", () => {
let count = 0;
for (let tap = 1; tap <= 5; tap += 1) {
const result = registerHiddenUpdateTap(count);
expect(result.shouldCheck).toBe(tap === 5);
count = result.nextCount;
}
expect(count).toBe(0);
});
});
@@ -0,0 +1,228 @@
import * as Updates from "expo-updates";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
reportAtomCommandResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
export interface AppUpdateClient {
readonly isEnabled: boolean;
readonly checkForUpdateAsync: () => Promise<{
readonly isAvailable: boolean;
readonly isRollBackToEmbedded: boolean;
}>;
readonly fetchUpdateAsync: () => Promise<{
readonly isNew: boolean;
readonly isRollBackToEmbedded: boolean;
}>;
readonly reloadAsync: () => Promise<void>;
}
interface AppUpdateCheckOptions {
readonly client?: AppUpdateClient;
readonly onFailure?: (message: string) => void;
readonly onStateChange?: (state: AppUpdateCheckState) => void;
}
interface AppUpdateCheckProgress {
failure: string | undefined;
state: AppUpdateCheckState | undefined;
}
interface AppUpdateCheckInFlight {
readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
readonly progress: AppUpdateCheckProgress;
readonly promise: Promise<void>;
readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
}
interface Deferred {
readonly promise: Promise<void>;
readonly reject: (cause: unknown) => void;
readonly resolve: () => void;
}
const HIDDEN_UPDATE_TAP_COUNT = 5;
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
/**
* Keeps the manual update affordance discoverable only to someone deliberately
* tapping the version row five times.
*/
export function registerHiddenUpdateTap(count: number): {
readonly nextCount: number;
readonly shouldCheck: boolean;
} {
const nextCount = count + 1;
if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
return {
nextCount: 0,
shouldCheck: true,
};
}
return {
nextCount,
shouldCheck: false,
};
}
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!client.isEnabled) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
return;
}
const progress: AppUpdateCheckProgress = {
failure: undefined,
state: undefined,
};
const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
if (options.onFailure) failureListeners.add(options.onFailure);
if (options.onStateChange) stateListeners.add(options.onStateChange);
const deferred = createDeferred();
const inFlight: AppUpdateCheckInFlight = {
failureListeners,
progress,
promise: deferred.promise,
stateListeners,
};
// Publish the operation before any state listener can synchronously re-enter.
appUpdateCheckInFlight = inFlight;
const execution = performAppUpdateCheck(client, {
onFailure: (message) => {
progress.failure = message;
notifyListeners(failureListeners, message);
},
onStateChange: (state) => {
progress.state = state;
notifyListeners(stateListeners, state);
},
});
void execution.then(deferred.resolve, deferred.reject);
try {
await deferred.promise;
} finally {
if (appUpdateCheckInFlight === inFlight) {
appUpdateCheckInFlight = undefined;
}
}
}
function createDeferred(): Deferred {
let reject!: Deferred["reject"];
let resolve!: Deferred["resolve"];
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
resolve = () => resolvePromise();
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
// A listener can synchronously subscribe another caller. Snapshot so that
// caller receives only observeAppUpdateCheck's explicit current-value replay.
const snapshot = Array.from(listeners);
for (const listener of snapshot) listener(value);
}
async function observeAppUpdateCheck(
inFlight: AppUpdateCheckInFlight,
options: AppUpdateCheckOptions,
): Promise<void> {
const onFailure = options.onFailure;
const onStateChange = options.onStateChange;
if (onFailure) {
inFlight.failureListeners.add(onFailure);
if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
}
if (onStateChange) {
inFlight.stateListeners.add(onStateChange);
if (inFlight.progress.state) onStateChange(inFlight.progress.state);
}
try {
await inFlight.promise;
} finally {
if (onFailure) inFlight.failureListeners.delete(onFailure);
if (onStateChange) inFlight.stateListeners.delete(onStateChange);
}
}
async function performAppUpdateCheck(
client: AppUpdateClient,
options: AppUpdateCheckOptions,
): Promise<void> {
const setState = options.onStateChange ?? (() => {});
setState("checking");
const check = await settlePromise(() => client.checkForUpdateAsync());
if (check._tag === "Failure") {
reportUpdateFailure(check, "Could not check for updates.", options.onFailure);
setState("idle");
return;
}
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
// with isRollBackToEmbedded: true. The running OTA still has to be dropped.
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
setState("current");
return;
}
setState("downloading");
const fetched = await settlePromise(() => client.fetchUpdateAsync());
if (fetched._tag === "Failure") {
reportUpdateFailure(fetched, "Could not download the update.", options.onFailure);
setState("idle");
return;
}
// isNew is always false for a rollback, so it cannot be the sole gate.
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
setState("current");
return;
}
setState("restarting");
const reloaded = await settlePromise(() => client.reloadAsync());
if (reloaded._tag === "Failure") {
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
setState("idle");
}
}
function reportUpdateFailure(
result: AtomCommandResult<unknown, unknown>,
fallback: string,
onFailure: AppUpdateCheckOptions["onFailure"],
): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
onFailure?.(error instanceof Error ? error.message : fallback);
}
export function createAppUpdateLaunchCheck(
client: AppUpdateClient = Updates,
): () => Promise<void> | undefined {
let started = false;
return () => {
if (started || !client.isEnabled) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
}
export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
+16 -1
View File
@@ -198,12 +198,27 @@ export function resolveTextScaleVariables(baseFontSize: number): Record<string,
for (const [name, role] of Object.entries(TEXT_SCALE_VARIABLE_ROLES)) {
variables[name] = Math.max(8, Math.round(role.fontSize * scale));
variables[`${name}--line-height`] = Math.max(10, Math.round(role.lineHeight * scale));
variables[`${name}--line-height`] = scaledTypographyLineHeight(role, baseFontSize);
}
return variables;
}
/**
* The line height a MOBILE_TYPOGRAPHY role renders at under the given base
* font size — the same value resolveTextScaleVariables injects for the role's
* `--text-*--line-height` variable. For layout code that must predict
* text-driven heights (e.g. the thread feed's fixed item sizes) instead of
* measuring them.
*/
export function scaledTypographyLineHeight(
role: { readonly lineHeight: number },
baseFontSize: number,
): number {
const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE;
return Math.max(10, Math.round(role.lineHeight * scale));
}
export function resolveNativeMarkdownTypography(baseFontSize: number): NativeMarkdownTypography {
const fontSizes = resolveMarkdownFontSizes(baseFontSize);
return {
+18 -9
View File
@@ -385,31 +385,40 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
const grouped: ThreadFeedEntry[] = [];
// Mutable backing array for the trailing group so appending an activity is
// O(1) instead of re-copying the group (which made this loop quadratic on
// long tool runs). The array is only mutated while it is the trailing group.
let openGroupActivities: ThreadFeedActivity[] | null = null;
let openGroupRunId: string | null = null;
let openGroupHasProminent = false;
for (const entry of entries) {
if (isEmptyMessage(entry)) continue;
if (entry.type !== "activity") {
grouped.push(entry);
openGroupActivities = null;
continue;
}
const previous = grouped.at(-1);
if (
previous?.type === "activity-group" &&
previous.runId === entry.runId &&
openGroupActivities !== null &&
openGroupRunId === entry.runId &&
!entry.activity.prominent &&
!previous.activities.some((activity) => activity.prominent)
!openGroupHasProminent
) {
grouped[grouped.length - 1] = {
...previous,
activities: [...previous.activities, entry.activity],
};
openGroupActivities.push(entry.activity);
continue;
}
openGroupActivities = [entry.activity];
openGroupRunId = entry.runId;
openGroupHasProminent = entry.activity.prominent === true;
grouped.push({
type: "activity-group",
id: entry.id,
createdAt: entry.createdAt,
runId: entry.runId,
activities: [entry.activity],
activities: openGroupActivities,
});
}
return grouped;
+49 -1
View File
@@ -1,4 +1,12 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";
import {
createThreadSearchResultsAtomFamily,
makeThreadSearchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { useAtomValue } from "@effect/atom-react";
import * as Option from "effect/Option";
import { Atom } from "effect/unstable/reactivity";
import { useEffect, useMemo, useState } from "react";
import { orchestrationEnvironment } from "./orchestration";
@@ -13,7 +21,22 @@ import {
const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
const COMPOSER_PATH_SEARCH_LIMIT = 20;
const THREAD_SEARCH_DEBOUNCE_MS = 200;
const VCS_REF_LIST_LIMIT = 100;
const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
matches: EMPTY_THREAD_SEARCH_MATCHES,
isLoading: false,
}).pipe(Atom.withLabel("mobile:thread-search:empty"));
const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
getSearchAtom: (environmentId, query) =>
orchestrationEnvironment.threadSearch({
environmentId,
input: { query },
}),
labelPrefix: "mobile:thread-search",
});
export interface ComposerPathSearchTarget {
readonly environmentId: EnvironmentId | null;
@@ -36,6 +59,31 @@ function useDebouncedValue<A>(value: A, delayMs: number): A {
return debounced;
}
export function useThreadSearch(
environmentIds: ReadonlyArray<EnvironmentId>,
query: string,
): {
readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>;
readonly isPending: boolean;
} {
const normalizedQuery = query.trim();
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
const searchKey = useMemo(
() => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
[environmentIds, settledQuery],
);
const result = useAtomValue(
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
);
const isDebouncing = canSearch && normalizedQuery !== debouncedQuery;
return {
matches: isDebouncing ? EMPTY_THREAD_SEARCH_MATCHES : result.matches,
isPending: canSearch && (isDebouncing || result.isLoading),
};
}
export function useBranches(input: {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
+23 -6
View File
@@ -88,11 +88,23 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
return loadPromise;
};
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
serialize(async () => {
// The queued atom drives the composer's immediate "queued" feedback, so it
// is published synchronously; the durable write happens behind it and rolls
// the message back out if it fails (durability only matters for crash
// recovery, not for the in-session queue).
const enqueue = (message: QueuedThreadMessage): Promise<void> => {
setMessages([
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
message,
]);
return serialize(async () => {
try {
await options.storage.write(message);
} catch (cause) {
// Roll back by reference, not messageId: a retry enqueue with the same
// id may have optimistically replaced this attempt while the write was
// in flight, and its entry must survive this attempt's failure.
setMessages(currentMessages().filter((candidate) => candidate !== message));
throw new ThreadOutboxManagerError({
operation: "enqueue",
environmentId: message.environmentId,
@@ -101,11 +113,15 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
cause,
});
}
setMessages([
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
message,
]);
});
};
// Resolves once all pending mutations (including any in-flight enqueue
// write) have settled, reporting whether the message is still queued. The
// drain awaits this before dispatching so a message whose durable write
// later fails can never have been delivered first.
const confirmQueued = (message: QueuedThreadMessage): Promise<boolean> =>
serialize(async () => currentMessages().some((candidate) => candidate === message));
// Rewrites an already-queued message. A no-op when the message has been
// removed in the meantime (e.g. deleted or delivered), so a trailing editor
@@ -204,6 +220,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
serialize,
load,
enqueue,
confirmQueued,
update,
remove,
clearEnvironment,
+105
View File
@@ -294,6 +294,111 @@ describe("thread outbox", () => {
registry.dispose();
});
it("publishes an enqueued message before the durable write resolves", async () => {
const registry = AtomRegistry.make();
let releaseWrite!: () => void;
const writeBlocked = new Promise<void>((resolve) => {
releaseWrite = resolve;
});
const manager = createThreadOutboxManager({
registry,
storage: {
load: async () => [],
write: async () => writeBlocked,
remove: async () => undefined,
},
});
const message = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const enqueueing = manager.enqueue(message);
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
"environment-1:thread-1": [message],
});
releaseWrite();
await enqueueing;
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
"environment-1:thread-1": [message],
});
registry.dispose();
});
it("rolls an enqueued message back out when the durable write fails", async () => {
const registry = AtomRegistry.make();
const writeCause = new Error("disk full");
const manager = createThreadOutboxManager({
registry,
storage: {
load: async () => [],
write: async () => {
throw writeCause;
},
remove: async () => undefined,
},
});
const message = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
await expect(manager.enqueue(message)).rejects.toEqual(
new ThreadOutboxManagerError({
operation: "enqueue",
environmentId: message.environmentId,
threadId: message.threadId,
messageId: message.messageId,
cause: writeCause,
}),
);
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
registry.dispose();
});
it("keeps a same-id retry queued when the first attempt's write fails", async () => {
const registry = AtomRegistry.make();
let failNextWrite = true;
let releaseFirstWrite!: () => void;
const firstWriteBlocked = new Promise<void>((resolve) => {
releaseFirstWrite = resolve;
});
const manager = createThreadOutboxManager({
registry,
storage: {
load: async () => [],
write: async () => {
if (failNextWrite) {
failNextWrite = false;
await firstWriteBlocked;
throw new Error("disk full");
}
},
remove: async () => undefined,
},
});
const message = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const retried = { ...message, text: "retried" };
const first = manager.enqueue(message);
const second = manager.enqueue(retried);
releaseFirstWrite();
await expect(first).rejects.toBeInstanceOf(ThreadOutboxManagerError);
await second;
// The failed first attempt must not roll back the retry that replaced it.
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
"environment-1:thread-1": [retried],
});
await expect(manager.confirmQueued(retried)).resolves.toBe(true);
await expect(manager.confirmQueued(message)).resolves.toBe(false);
registry.dispose();
});
it("replaces an existing message when an enqueue retry uses the same id", async () => {
const registry = AtomRegistry.make();
const manager = createThreadOutboxManager({
+5
View File
@@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis
return threadOutboxManager.enqueue(message);
}
/** Waits for pending writes to settle; false if the message was rolled back. */
export function confirmThreadOutboxMessageQueued(message: QueuedThreadMessage): Promise<boolean> {
return threadOutboxManager.confirmQueued(message);
}
/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
return threadOutboxManager.update(message);
@@ -35,6 +35,7 @@ import {
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
mergeComposerDraftContent,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
@@ -167,27 +168,36 @@ export function useThreadComposerState() {
const metadata = makeQueuedMessageMetadata();
const messageId = MessageId.make(metadata.messageId);
try {
await enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId,
commandId: CommandId.make(metadata.commandId),
text,
attachments,
modelSelection: draft.modelSelection ?? thread.modelSelection,
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
interactionMode: draft.interactionMode ?? thread.interactionMode,
createdAt: metadata.createdAt,
});
clearComposerDraftContent(threadKey);
return messageId;
} catch (error) {
// Enqueue publishes the queued atom synchronously (the durable write
// happens behind it), so clearing the draft here gives send feedback on
// the tap frame instead of after file I/O. If the write fails the message
// is rolled out of the queue and the content is merged back into the
// draft, preserving anything typed since.
const enqueuePromise = enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId,
commandId: CommandId.make(metadata.commandId),
text,
attachments,
modelSelection: draft.modelSelection ?? thread.modelSelection,
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
interactionMode: draft.interactionMode ?? thread.interactionMode,
createdAt: metadata.createdAt,
});
clearComposerDraftContent(threadKey);
enqueuePromise.catch((error: unknown) => {
// Restore text via merge (idempotent) but attachments via the uncapped
// append: the merge path slots existing attachments first and truncates
// at the send limit, which would silently drop this message's images if
// the user attached new ones while the write was in flight.
void mergeComposerDraftContent(threadKey, { text, attachments: [] });
appendComposerDraftAttachments(threadKey, attachments);
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
return null;
}
});
return messageId;
}, [selectedThreadShell]);
const onChangeDraftMessage = useCallback(
@@ -22,7 +22,11 @@ import { toUploadChatImageAttachments } from "../lib/composerImages";
import { randomHex } from "../lib/uuid";
import { appAtomRegistry } from "./atom-registry";
import { useProjects, useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
confirmThreadOutboxMessageQueued,
ensureThreadOutboxLoaded,
removeThreadOutboxMessage,
} from "./thread-outbox";
import {
isQueuedThreadCreationSendable,
modelSelectionsEqual,
@@ -34,7 +38,7 @@ import {
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { environmentThreadShells, threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
import {
editingQueuedMessageIdsAtom,
@@ -351,8 +355,31 @@ export function useThreadOutboxDrain(): void {
return false;
},
);
const delivery =
deliveryAction === "remove"
// Enqueues publish optimistically before their durable write settles.
// Confirm the write landed (and the message wasn't rolled back) before
// sending, so a failed write can never chase an already-delivered turn.
const delivery = confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => {
if (!queued) {
// Rolled back by a failed write; nothing to deliver or retry.
return true;
}
// The guards evaluated before the confirmation await are stale by now:
// the thread may have gone busy, or the user may have opened this
// message in the editor. Re-read both and defer to the next drain pass
// (returning true skips the failure/backoff path) rather than sending
// a payload the user is editing or racing an active turn.
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
return true;
}
const freshThread = findThread(
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
nextQueuedMessage,
);
const freshThreadBusy = threadRuntimeIsActive(freshThread?.runtime);
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
return true;
}
return deliveryAction === "remove"
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
: creation !== undefined
? creationProjectCwd !== null
@@ -361,6 +388,7 @@ export function useThreadOutboxDrain(): void {
: thread !== undefined
? sendQueuedMessage(nextQueuedMessage, thread)
: Promise.resolve(false);
});
void delivery
.then((sent) => {
if (sent) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.30",
"version": "0.0.31",
"license": "MIT",
"repository": {
"type": "git",
+3
View File
@@ -24,6 +24,7 @@ export const RPC_REQUIRED_SCOPES = {
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope,
@@ -36,6 +37,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateServer]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpdateServerWithProgress]: AuthOrchestrationOperateScope,
[WS_METHODS.serverUpsertKeybinding]: AuthOrchestrationOperateScope,
[WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
@@ -63,6 +65,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
[WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
+11 -4
View File
@@ -46,6 +46,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ExternalLauncher from "../process/externalLauncher.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import { resolveCliCommand } from "./invocation.ts";
import {
bootServiceLayer,
offerServiceDuringOnboarding,
@@ -526,10 +527,11 @@ const connectLinkCommand = Command.make("link", {
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
const serveCommand = yield* resolveCliCommand("serve");
yield* Console.log(
flags.publishOnly
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`,
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
);
}
}),
@@ -691,10 +693,15 @@ export const connectCommand = Command.make("connect", {
// Connect itself already succeeded; a boot-service failure must not
// fail the command, just tell the user what happened and move on.
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
yield* Console.log(
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
);
return;
}
const serveCommand = yield* resolveCliCommand("serve");
yield* Console.log(
background
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
: "\nNext\n Start the server with `t3 serve` to make this machine reachable.",
`\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
);
}),
),
+74
View File
@@ -0,0 +1,74 @@
import { assert, it } from "@effect/vitest";
import { detectCliRunner, formatCliCommand, suggestedPackageSpec } from "./invocation.ts";
it("detects package runners from their cache entry paths", () => {
assert.equal(detectCliRunner("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"), "npx");
assert.equal(
detectCliRunner(
"C:\\Users\\theo\\AppData\\Local\\npm-cache\\_npx\\abc\\node_modules\\t3\\dist\\bin.mjs",
),
"npx",
);
assert.equal(
detectCliRunner("/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs"),
"pnpm dlx",
);
assert.equal(
detectCliRunner("/home/theo/.local/share/pnpm/.pnpm/dlx/abc/node_modules/t3/dist/bin.mjs"),
"pnpm dlx",
);
assert.equal(
detectCliRunner(
"C:\\Users\\theo\\AppData\\Local\\pnpm-cache\\dlx\\abc\\node_modules\\t3\\dist\\bin.mjs",
),
"pnpm dlx",
);
assert.equal(detectCliRunner("/home/theo/.bun/install/cache/[email protected]/dist/bin.mjs"), "bunx");
assert.equal(detectCliRunner("/tmp/bunx-1000-t3@latest/node_modules/t3/dist/bin.mjs"), "bunx");
assert.equal(
detectCliRunner(
"C:\\Users\\theo\\AppData\\Local\\Temp\\bunx-0-t3@latest\\node_modules\\t3\\dist\\bin.mjs",
),
"bunx",
);
});
it("treats stable installs as direct invocations", () => {
assert.isNull(detectCliRunner("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
assert.isNull(detectCliRunner("/home/theo/Code/work/t3code/apps/server/dist/bin.mjs"));
assert.isNull(detectCliRunner("/home/theo/.t3/runtime/0.0.31/node_modules/t3/dist/bin.mjs"));
assert.isNull(detectCliRunner(""));
});
it("re-suggests the nightly channel only for nightly builds", () => {
assert.equal(suggestedPackageSpec("0.0.31-nightly.20260729"), "t3@nightly");
assert.equal(suggestedPackageSpec("0.0.31"), "t3");
});
it("formats serve suggestions to match the launching command", () => {
assert.equal(
formatCliCommand({
subcommand: "serve",
entryPath: "/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs",
version: "0.0.31-nightly.20260729",
}),
"npx t3@nightly serve",
);
assert.equal(
formatCliCommand({
subcommand: "serve",
entryPath: "/tmp/bunx-1000-t3@latest/node_modules/t3/dist/bin.mjs",
version: "0.0.31",
}),
"bunx t3 serve",
);
assert.equal(
formatCliCommand({
subcommand: "serve",
entryPath: "/usr/local/lib/node_modules/t3/dist/bin.mjs",
version: "0.0.31-nightly.20260729",
}),
"t3 serve",
);
});
+75
View File
@@ -0,0 +1,75 @@
import * as Effect from "effect/Effect";
import { HostProcessArguments } from "@t3tools/shared/hostProcess";
import packageJson from "../../package.json" with { type: "json" };
export type CliRunner = "npx" | "pnpm dlx" | "bunx";
/**
* How the CLI was launched, judged by where its entry script lives. Each
* package runner executes out of a distinctive cache/temp layout:
*
* npx ~/.npm/_npx/<hash>/node_modules/...
* pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
* or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
* bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
*
* Global installs and repo checkouts match none of these and return null.
* Detection is best-effort; callers must fail closed to a plain `t3` command.
*/
export function detectCliRunner(entryPath: string): CliRunner | null {
const path = entryPath.replaceAll("\\", "/");
if (path.includes("/_npx/")) {
return "npx";
}
if (
path.includes("/pnpm/dlx/") ||
path.includes("/.pnpm/dlx/") ||
path.includes("/pnpm-cache/dlx/")
) {
return "pnpm dlx";
}
if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
return "bunx";
}
return null;
}
/**
* The `t3` package spec to suggest. The literal spec the user typed (e.g.
* `t3@nightly`) is resolved away before our process starts, so re-derive it
* from the running version: nightly builds re-suggest the nightly channel,
* anything else suggests the bare package.
*/
export function suggestedPackageSpec(version: string): string {
return version.includes("-nightly.") ? "t3@nightly" : "t3";
}
/**
* Render a `t3 <subcommand>` suggestion that matches how this process was
* launched, so copy/pasting it actually works: `npx t3 connect` suggests
* `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
* keeps the `@nightly` tag.
*/
export function formatCliCommand(input: {
readonly subcommand: string;
readonly entryPath: string;
readonly version: string;
}): string {
const runner = detectCliRunner(input.entryPath);
if (runner === null) {
return `t3 ${input.subcommand}`;
}
return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
}
/** `formatCliCommand` against this process's real entry path and version. */
export const resolveCliCommand = (subcommand: string) =>
Effect.map(HostProcessArguments, (processArguments) =>
formatCliCommand({
subcommand,
entryPath: processArguments[1] ?? "",
version: packageJson.version,
}),
);
+40 -5
View File
@@ -26,6 +26,33 @@ import * as SelfUpdate from "./selfUpdate.ts";
const NODE_PATH = "/usr/local/bin/node";
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
filePath: string,
expected: string,
) {
const fs = yield* FileSystem.FileSystem;
for (let iteration = 0; iteration < 1_000; iteration += 1) {
const contents = yield* fs.readFileString(filePath);
if (contents === expected) {
return;
}
// The rollback performs real filesystem I/O on a detached fiber, which
// advancing TestClock does not await.
yield* Effect.yieldNow;
}
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
});
const eventuallyTrue = Effect.fn("test.eventuallyTrue")(function* (predicate: () => boolean) {
for (let iteration = 0; iteration < 1_000; iteration += 1) {
if (predicate()) {
return;
}
yield* Effect.yieldNow;
}
return yield* Effect.die(new Error("Expected condition was not observed."));
});
interface RecordedCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -457,8 +484,12 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
it.effect("installs, preflights, and respawns a foreground server", () =>
Effect.gen(function* () {
const context = yield* makeContext();
const result = yield* context.service.update({ targetVersion: "0.0.29" });
const progress: Array<string> = [];
const result = yield* context.service.update({ targetVersion: "0.0.29" }, (stage) =>
Effect.sync(() => progress.push(stage)),
);
assert.deepEqual(result, { targetVersion: "0.0.29", method: "respawn" });
assert.deepEqual(progress, ["downloading", "installing"]);
assert.lengthOf(context.spawns, 1);
const concurrentError = yield* context.service
@@ -506,10 +537,12 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "systemctl", "systemctl"],
["npm", NODE_PATH, "systemctl"],
);
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
// Restart waits until after the update acknowledgement can flush.
yield* TestClock.adjust(Duration.seconds(10));
assert.deepEqual(context.commands[3], {
command: "systemctl",
args: ["--user", "restart", "t3code.service"],
@@ -542,9 +575,11 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
);
const previousUnit = yield* context.fs.readFileString(unitPath);
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(first.reason, "Restarting the systemd boot service failed");
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
const first = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
yield* TestClock.adjust(Duration.seconds(10));
yield* eventuallyFileString(unitPath, previousUnit);
yield* eventuallyTrue(() => context.commands.at(-1)?.args[1] === "daemon-reload");
assert.deepEqual(
context.commands.slice(-2).map((entry) => entry.args),
[
+42 -31
View File
@@ -6,6 +6,7 @@ import {
ServerSelfUpdateError,
type ServerSelfUpdateCapability,
type ServerSelfUpdateInput,
type ServerSelfUpdateProgressStage,
type ServerSelfUpdateResult,
} from "@t3tools/contracts";
import {
@@ -147,6 +148,7 @@ export class ServerSelfUpdate extends Context.Service<
{
readonly update: (
input: ServerSelfUpdateInput,
reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void, never, never>,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
}
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
@@ -227,7 +229,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input) {
)(function* (input, reportProgress = () => Effect.void) {
if (capability === "desktop-managed") {
return yield* failWith(
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
@@ -250,6 +252,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
}
return yield* Effect.gen(function* () {
yield* reportProgress("downloading");
const runtimePaths = yield* ensurePinnedRuntimeInstalled({
baseDir: serverConfig.baseDir,
version: targetVersion,
@@ -260,6 +263,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
);
yield* reportProgress("installing");
// A broken artifact (failed native build, incompatible node) must be
// caught while the current server is still alive to report it.
const preflight = yield* runner
@@ -349,38 +353,45 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
targetVersion,
});
// A successful systemd restart stops this process, so the RPC is
// interrupted and the reconnecting client observes the new version.
// A rejected restart returns while the old process is still alive;
// restore the previous unit and report that failure through the RPC.
yield* Effect.gen(function* () {
const restart = yield* runner
.run({
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
})
.pipe(
Effect.mapError((cause) =>
failWith("Could not restart the systemd boot service.", cause),
// Restart after the acknowledgement has had time to cross any relay
// hop. If systemd rejects the handoff, restore the previous unit while
// this process is still alive and log the failure for diagnostics.
yield* scheduleRestart(
Effect.gen(function* () {
const restart = yield* runner
.run({
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
})
.pipe(
Effect.mapError((cause) =>
failWith("Could not restart the systemd boot service.", cause),
),
);
if (restart.code !== 0) {
return yield* failWith(
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
);
}
}).pipe(
Effect.catch((restartError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.andThen(reloadSystemd()),
Effect.mapError((rollbackError) =>
failWith("Could not restore the previous systemd unit.", {
restartError,
rollbackError,
}),
),
Effect.andThen(Effect.fail(restartError)),
),
);
if (restart.code !== 0) {
return yield* failWith(
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
);
}
}).pipe(
Effect.catch((restartError) =>
writeUnitAtomically(unitPath, previousUnit).pipe(
Effect.andThen(reloadSystemd()),
Effect.mapError((rollbackError) =>
failWith("Could not restore the previous systemd unit.", {
restartError,
rollbackError,
}),
),
Effect.andThen(Effect.fail(restartError)),
),
Effect.catch((error) =>
Effect.logError("Server self-update could not restart the boot service.").pipe(
Effect.annotateLogs({ targetVersion, error: error.reason }),
),
),
Effect.ensuring(Ref.set(inFlight, false)),
),
);
} else {
@@ -69,6 +69,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(first.environmentId).toBe(second.environmentId);
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.threadTitleRegeneration).toBe(true);
}),
);
@@ -143,7 +143,14 @@ export const make = Effect.gen(function* () {
threadSettlement: true,
threadSnooze: true,
threadVisitedTracking: true,
// Deliberately not advertised: the v1 reactor that served regeneration is
// deleted here and the v2 orchestrator port has not landed yet. Clients
// hide the sidebar action when the capability is absent.
// TODO(orchestration-v2): port thread title regeneration to the v2 runtime.
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" || serverSelfUpdate === "respawn"
? { serverSelfUpdateProgress: true }
: {}),
},
};
+2
View File
@@ -198,6 +198,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
+13 -8
View File
@@ -547,19 +547,24 @@ const make = Effect.gen(function* () {
});
}
const nextConfig = [...customConfig, ...missingDefaults];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS_COUNT
? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
: nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
yield* Effect.logWarning("truncating keybindings config to max entries", {
// Startup backfill must never evict persisted user rules: append only
// the defaults that fit and skip the rest.
const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
const defaultsToAppend = missingDefaults.slice(0, availableSlots);
const skippedDefaults = missingDefaults.slice(availableSlots);
if (skippedDefaults.length > 0) {
yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
path: keybindingsConfigPath,
maxEntries: MAX_KEYBINDINGS_COUNT,
commands: skippedDefaults.map((rule) => rule.command),
});
}
if (defaultsToAppend.length === 0) {
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
yield* writeConfigAtomically(cappedConfig);
yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
}),
);
@@ -609,6 +609,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
pendingApprovalCount: 0,
pendingUserInputCount: 0,
@@ -627,6 +629,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
archivedAt: event.payload.archivedAt,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
@@ -721,6 +725,12 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.titleRegeneration !== undefined
? {
titleRegenerationRequestId: event.payload.titleRegeneration?.requestId ?? null,
titleRegenerationStartedAt: event.payload.titleRegeneration?.startedAt ?? null,
}
: {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
@@ -14,6 +14,7 @@ import {
OrchestrationCheckpointFile,
OrchestrationProposedPlanId,
OrchestrationReadModel,
OrchestrationThreadSearchSource,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
@@ -110,6 +111,17 @@ const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
threadCount: Schema.Number,
});
const ProjectionThreadSearchRequest = Schema.Struct({
pattern: Schema.String,
limit: Schema.Int,
});
const ProjectionThreadSearchRow = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
source: OrchestrationThreadSearchSource,
matchText: Schema.String,
messageCreatedAt: Schema.NullOr(IsoDateTime),
});
const WorkspaceRootLookupInput = Schema.Struct({
workspaceRoot: Schema.String,
});
@@ -159,6 +171,31 @@ function maxIso(left: string | null, right: string): string {
return left > right ? left : right;
}
function escapeLikePattern(value: string): string {
return value.replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_");
}
function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
function buildSearchSnippet(text: string, query: string): string {
const normalizedText = text.replace(/\s+/g, " ").trim();
if (normalizedText.length <= 240) {
return normalizedText;
}
const normalizedQuery = foldAsciiCase(query.replace(/\s+/g, " ").trim());
const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);
const bodyLength = 236;
const idealStart = Math.max(0, matchIndex - 72);
const start = Math.min(idealStart, normalizedText.length - bodyLength);
const end = Math.min(normalizedText.length, start + bodyLength);
return `${start > 0 ? "…" : ""}${normalizedText.slice(start, end)}${
end < normalizedText.length ? "…" : ""
}`;
}
function computeSnapshotSequence(
stateRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionStateDbRowSchema>>,
): number {
@@ -211,6 +248,15 @@ function mapLatestTurn(
};
}
function mapTitleRegeneration(row: Schema.Schema.Type<typeof ProjectionThreadDbRowSchema>) {
return row.titleRegenerationRequestId != null && row.titleRegenerationStartedAt != null
? {
requestId: row.titleRegenerationRequestId,
startedAt: row.titleRegenerationStartedAt,
}
: null;
}
function mapSessionRow(
row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,
): OrchestrationSession {
@@ -341,6 +387,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -373,6 +421,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -407,6 +457,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -673,6 +725,105 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const searchActiveThreadRows = SqlSchema.findAll({
Request: ProjectionThreadSearchRequest,
Result: ProjectionThreadSearchRow,
execute: ({ pattern, limit }) =>
sql`
WITH candidate AS (
SELECT
threads.thread_id AS thread_id,
threads.project_id AS project_id,
messages.role AS role,
messages.text AS match_text,
messages.created_at AS message_created_at,
messages.message_id AS message_id,
threads.updated_at AS thread_updated_at
FROM projection_thread_messages AS messages
INNER JOIN projection_threads AS threads
ON threads.thread_id = messages.thread_id
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND projects.deleted_at IS NULL
AND messages.is_streaming = 0
AND (
messages.role = 'user'
OR (
messages.role = 'assistant'
AND messages.message_id IN (
SELECT turns.assistant_message_id
FROM projection_turns AS turns
WHERE turns.assistant_message_id IS NOT NULL
)
)
)
AND messages.text LIKE ${pattern} ESCAPE '!'
UNION ALL
SELECT
v2_threads.thread_id AS thread_id,
v2_threads.project_id AS project_id,
v2_messages.role AS role,
json_extract(v2_messages.payload_json, '$.text') AS match_text,
v2_messages.created_at AS message_created_at,
v2_messages.message_id AS message_id,
v2_threads.updated_at AS thread_updated_at
FROM orchestration_v2_projection_messages AS v2_messages
INNER JOIN orchestration_v2_projection_threads AS v2_threads
ON v2_threads.thread_id = v2_messages.thread_id
INNER JOIN projection_projects AS projects
ON projects.project_id = v2_threads.project_id
WHERE v2_threads.deleted_at IS NULL
AND v2_threads.archived_at IS NULL
AND projects.deleted_at IS NULL
AND v2_messages.streaming = 0
AND v2_messages.role IN ('user', 'assistant')
AND json_extract(v2_messages.payload_json, '$.text') LIKE ${pattern} ESCAPE '!'
),
ranked AS (
SELECT
thread_id,
project_id,
CASE role
WHEN 'user' THEN 'user'
ELSE 'assistant'
END AS source,
match_text,
message_created_at,
CASE role
WHEN 'user' THEN 0
ELSE 1
END AS match_rank,
thread_updated_at,
ROW_NUMBER() OVER (
PARTITION BY thread_id
ORDER BY
CASE role
WHEN 'user' THEN 0
ELSE 1
END ASC,
message_created_at DESC,
message_id ASC
) AS thread_match_rank
FROM candidate
)
SELECT
thread_id AS "threadId",
project_id AS "projectId",
source,
match_text AS "matchText",
message_created_at AS "messageCreatedAt"
FROM ranked
WHERE thread_match_rank = 1
ORDER BY
match_rank ASC,
thread_updated_at DESC,
thread_id ASC
LIMIT ${limit}
`,
});
const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({
Request: WorkspaceRootLookupInput,
Result: ProjectionProjectLookupRowSchema,
@@ -773,6 +924,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -1208,6 +1361,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1410,6 +1564,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1541,6 +1696,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1696,6 +1852,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
@@ -1754,6 +1911,32 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
const searchThreads: ProjectionSnapshotQueryShape["searchThreads"] = Effect.fn(
"ProjectionSnapshotQuery.searchThreads",
)(function* (input) {
const escapedQuery = escapeLikePattern(input.query);
const rows = yield* searchActiveThreadRows({
pattern: `%${escapedQuery}%`,
limit: input.limit ?? 50,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.searchThreads:query",
"ProjectionSnapshotQuery.searchThreads:decodeRows",
),
),
);
return {
matches: rows.map((row) => ({
threadId: row.threadId,
projectId: row.projectId,
source: row.source,
snippet: buildSearchSnippet(row.matchText, input.query),
messageCreatedAt: row.messageCreatedAt,
})),
};
});
const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] =
(workspaceRoot) =>
getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(
@@ -1940,6 +2123,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
@@ -2038,6 +2222,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
@@ -2126,6 +2311,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getShellSnapshot,
getShellSnapshotWithoutEnrichment,
getArchivedShellSnapshot,
searchThreads,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
@@ -12,6 +12,8 @@ import type {
OrchestrationProject,
OrchestrationProjectShell,
OrchestrationReadModel,
OrchestrationSearchThreadsInput,
OrchestrationSearchThreadsResult,
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
@@ -103,6 +105,14 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Search active thread navigation metadata, user messages, and canonical
* assistant outputs without hydrating thread detail snapshots.
*/
readonly searchThreads: (
input: OrchestrationSearchThreadsInput,
) => Effect.Effect<OrchestrationSearchThreadsResult, ProjectionRepositoryError>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -0,0 +1,72 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const UPDATED_AT = "2026-01-01T00:00:00.000Z";
const readModel: OrchestrationReadModel = {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Manual title",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: UPDATED_AT,
updatedAt: UPDATED_AT,
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: UPDATED_AT,
};
it.layer(NodeServices.layer)("title regeneration decider", (it) => {
it.effect("preserves updatedAt for a stale completion", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: {
type: "thread.title.regeneration.complete",
commandId: CommandId.make("cmd-regeneration-complete"),
threadId: ThreadId.make("thread-1"),
requestId: CommandId.make("cmd-old-regeneration-request"),
title: "Generated title",
},
readModel,
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("thread.meta-updated");
if (event.type === "thread.meta-updated") {
expect(event.payload).toEqual({
threadId: ThreadId.make("thread-1"),
updatedAt: UPDATED_AT,
});
}
}),
);
});
+38
View File
@@ -654,6 +654,19 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.regenerateTitle === true
? {
regenerateTitle: true as const,
previousTitle: thread.title,
titleRegeneration: {
requestId: command.commandId,
startedAt: occurredAt,
},
}
: {}),
...(command.title !== undefined && thread.titleRegeneration != null
? { titleRegeneration: null }
: {}),
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
@@ -664,6 +677,31 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.title.regeneration.complete": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.meta-updated",
payload: {
threadId: command.threadId,
...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),
...(requestIsCurrent ? { titleRegeneration: null } : {}),
updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,
},
};
}
case "thread.runtime-mode.set": {
yield* requireThread({
readModel,
@@ -333,6 +333,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
archivedAt: payload.archivedAt,
titleRegeneration: null,
updatedAt: payload.updatedAt,
}),
})),
@@ -403,6 +404,9 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.titleRegeneration !== undefined
? { titleRegeneration: payload.titleRegeneration }
: {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
@@ -47,6 +47,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at,
snoozed_until,
snoozed_at,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
@@ -70,6 +72,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.settledAt},
${row.snoozedUntil},
${row.snoozedAt},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
${row.pendingApprovalCount},
${row.pendingUserInputCount},
@@ -93,6 +97,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at = excluded.settled_at,
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
@@ -123,6 +129,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -155,6 +163,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
@@ -56,6 +56,7 @@ import Migration0040 from "./Migrations/040_ApplicationEventSource.ts";
import Migration0041 from "./Migrations/041_OrchestrationV2EffectCancellation.ts";
import Migration0042 from "./Migrations/042_ScheduledTasks.ts";
import Migration0043 from "./Migrations/043_LegacyV1ImportState.ts";
import Migration0044 from "./Migrations/044_ProjectionThreadTitleRegeneration.ts";
/**
* Migration loader with all migrations defined inline.
@@ -111,6 +112,7 @@ export const migrationEntries = [
[41, "OrchestrationV2EffectCancellation", Migration0041],
[42, "ScheduledTasks", Migration0042],
[43, "LegacyV1ImportState", Migration0043],
[44, "ProjectionThreadTitleRegeneration", Migration0044],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -13,7 +13,7 @@ layer("035_036_OrchestrationV2", (it) => {
Effect.sync(() => {
assert.deepStrictEqual(
migrationEntries.map(([id]) => id),
Array.from({ length: 43 }, (_, index) => index + 1),
Array.from({ length: 44 }, (_, index) => index + 1),
);
}),
);
@@ -0,0 +1,27 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("044_ProjectionThreadTitleRegeneration", (it) => {
it.effect("adds pending title regeneration columns", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 43 });
yield* runMigrations({ toMigrationInclusive: 44 });
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
const names = new Set(columns.map((column) => column.name));
assert.ok(names.has("title_regeneration_request_id"));
assert.ok(names.has("title_regeneration_started_at"));
}),
);
});
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "title_regeneration_request_id")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN title_regeneration_request_id TEXT
`;
}
if (!columns.some((column) => column.name === "title_regeneration_started_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN title_regeneration_started_at TEXT
`;
}
});
@@ -7,6 +7,7 @@
* @module ProjectionThreadRepository
*/
import {
CommandId,
IsoDateTime,
ModelSelection,
NonNegativeInt,
@@ -40,6 +41,8 @@ export const ProjectionThread = Schema.Struct({
settledAt: Schema.NullOr(IsoDateTime),
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
+21 -1
View File
@@ -1,6 +1,8 @@
import { EnvironmentHttpApi } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
@@ -514,7 +516,25 @@ export const makeServerLayer = Layer.unwrap(
yield* Effect.forkScoped(
Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
Effect.retry({ times: 4 }),
// On reboot this races NIC/DNS bring-up, so back off exponentially
// (capped at 30s) instead of burning all retries in a second.
// Bounded overall so a permanently broken setup still surfaces the
// warning below. Bad-request/unauthorized/conflict are
// deterministic failures (malformed origin, not linked yet, linked
// to a different cloud account) that no amount of retrying
// converges.
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
error._tag !== "EnvironmentHttpUnauthorizedError" &&
error._tag !== "EnvironmentHttpConflictError",
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.upTo({ duration: "10 minutes" }),
),
}),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
@@ -1,10 +1,12 @@
import { assert, it } from "@effect/vitest";
import { DEFAULT_MODEL, ProviderInstanceId } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Ref from "effect/Ref";
import * as ServerConfig from "./config.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
it("uses the canonical Codex model for auto-bootstrap", () => {
@@ -95,3 +97,43 @@ it.effect("queues commands until startup signals readiness", () =>
}),
),
);
it.effect("enqueueCommand fails queued work when readiness fails", () =>
Effect.scoped(
Effect.gen(function* () {
const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
const failure = yield* Deferred.make<void, never>();
const queuedCommandFiber = yield* commandGate
.enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
.pipe(Effect.forkScoped);
yield* commandGate.failCommandReady(
new ServerRuntimeStartup.ServerRuntimeStartupError({
mode: "web",
host: "127.0.0.1",
port: 3773,
cause: new Error("test startup failure"),
}),
);
const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
assert.equal(error.message, "Server runtime startup failed before command readiness.");
}),
),
);
it.effect("resolveWelcomeBase derives cwd and project name from server config", () =>
Effect.gen(function* () {
const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe(
Effect.provideService(ServerConfig.ServerConfig, {
cwd: "/tmp/startup-project",
} as never),
);
assert.deepStrictEqual(welcome, {
cwd: "/tmp/startup-project",
projectName: "startup-project",
});
}),
);
@@ -342,6 +342,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
Effect.fn("ClaudeTextGeneration.generateThreadTitle")(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
previousTitle: input.previousTitle,
attachments: input.attachments,
});
@@ -384,6 +384,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
);
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
previousTitle: input.previousTitle,
attachments: input.attachments,
});
@@ -233,6 +233,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")((
Effect.fn("CursorTextGeneration.generateThreadTitle")(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
previousTitle: input.previousTitle,
attachments: input.attachments,
});
@@ -234,6 +234,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
Effect.fn("GrokTextGeneration.generateThreadTitle")(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
previousTitle: input.previousTitle,
attachments: input.attachments,
});
@@ -598,6 +598,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
Effect.fn("OpenCodeTextGeneration.generateThreadTitle")(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
previousTitle: input.previousTitle,
attachments: input.attachments,
});
const generated = yield* runOpenCodeJson({
@@ -62,6 +62,8 @@ export interface BranchNameGenerationResult {
export interface ThreadTitleGenerationInput {
cwd: string;
message: string;
/** Present when replacing an existing title from the current thread history. */
previousTitle?: string | undefined;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
@@ -107,9 +109,7 @@ export class TextGeneration extends Context.Service<
input: BranchNameGenerationInput,
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
/**
* Generate a concise thread title from a user's first message.
*/
/** Generate a concise thread title from a first message or thread history. */
readonly generateThreadTitle: (
input: ThreadTitleGenerationInput,
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
@@ -175,6 +175,48 @@ describe("buildThreadTitlePrompt", () => {
expect(result.prompt).toContain("image/png");
expect(result.prompt).toContain("67890 bytes");
});
it("regenerates from recent thread contents and identifies the previous title", () => {
const result = buildThreadTitlePrompt({
message: `USER:\nInvestigate reconnect regressions\n\nASSISTANT:\nThe remaining issue is stale session state`,
previousTitle: "Investigate reconnect regressions",
});
expect(result.prompt).toContain(
"The user requested a new title based on the contents of this thread.",
);
expect(result.prompt).toContain('The previous title was "Investigate reconnect regressions".');
expect(result.prompt).toContain("better represents the current state of the thread");
expect(result.prompt).toContain(
"Capture the thread's intent, not a PR number or other superficial detail.",
);
expect(result.prompt).toContain("Thread contents:");
expect(result.prompt).toContain("The remaining issue is stale session state");
});
it("keeps the latest thread contents when regeneration context is truncated", () => {
const result = buildThreadTitlePrompt({
message: `${"old context ".repeat(1_000)}\n\nASSISTANT:\nCurrent thread state`,
previousTitle: "Old title",
});
expect(result.prompt).toContain("[Earlier content truncated]");
expect(result.prompt).toContain("Current thread state");
expect(result.prompt).not.toContain("[truncated]");
});
it("does not truncate an already-marked regeneration context twice", () => {
const retainedContext = "x".repeat(7_998);
const result = buildThreadTitlePrompt({
message: `[Earlier content truncated]\n\n${retainedContext}`,
previousTitle: "Old title",
});
expect(result.prompt).toContain(
`Thread contents:\n[Earlier content truncated]\n\n${retainedContext}`,
);
expect(result.prompt.match(/\[Earlier content truncated\]/g)).toHaveLength(1);
});
});
describe("sanitizeThreadTitle", () => {
@@ -12,6 +12,8 @@ import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./TextGenerationUtils.ts";
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
const EARLIER_CONTENT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
const trimmed = instruction?.trim();
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
@@ -150,10 +152,23 @@ interface PromptFromMessageInput {
responseShape: string;
rules: ReadonlyArray<string>;
message: string;
messageLabel?: string | undefined;
preserveMessageEnd?: boolean | undefined;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
additionalInstructions?: string | undefined;
}
function preserveMessageEnd(message: string): string {
const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
const contents = alreadyTruncated
? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
: message;
if (!alreadyTruncated && contents.length <= 8_000) {
return contents;
}
return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
@@ -165,8 +180,10 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
"Rules:",
...input.rules.map((rule) => `- ${rule}`),
"",
"User message:",
limitSection(input.message, 8_000),
`${input.messageLabel ?? "User message"}:`,
input.preserveMessageEnd
? preserveMessageEnd(input.message)
: limitSection(input.message, 8_000),
...policyInstruction(input.additionalInstructions),
];
if (attachmentLines.length > 0) {
@@ -207,21 +224,44 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
export interface ThreadTitlePromptInput {
message: string;
previousTitle?: string | undefined;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
const isRegeneration = input.previousTitle !== undefined;
const prompt = buildPromptFromMessage({
instruction: "You write concise thread titles for coding conversations.",
instruction: isRegeneration
? [
"You write concise thread titles for coding conversations.",
"The user requested a new title based on the contents of this thread.",
`The previous title was ${JSON.stringify(input.previousTitle)}.`,
"Come up with a new title that better represents the current state of the thread.",
].join("\n")
: "You write concise thread titles for coding conversations.",
responseShape: "Return a JSON object with key: title.",
rules: [
"Title should summarize the user's request, not restate it verbatim.",
isRegeneration
? "Title should summarize the thread's current state, not just its initial request."
: "Title should summarize the user's request, not restate it verbatim.",
...(isRegeneration
? [
"Capture the thread's intent, not a PR number or other superficial detail.",
"Return a different title from the previous title.",
]
: []),
"Keep it short and specific (3-8 words).",
"Avoid quotes, filler, prefixes, and trailing punctuation.",
"If images are attached, use them as primary context for visual/UI issues.",
],
message: input.message,
...(isRegeneration
? {
messageLabel: "Thread contents",
preserveMessageEnd: true,
}
: {}),
attachments: input.attachments,
additionalInstructions: input.policy?.threadTitleInstructions,
});
@@ -72,7 +72,12 @@ const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv)
return result.stdout.trim();
});
const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) =>
const searchWorkspaceEntries = (input: {
cwd: string;
query: string;
limit: number;
kind?: "file" | "directory";
}) =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
return yield* workspaceEntries.search(input);
@@ -200,6 +205,62 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
}),
);
it.effect("applies the file filter before limiting search results", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" });
yield* writeTextFile(cwd, "src/index.ts");
yield* writeTextFile(cwd, "src/internal.ts");
const result = yield* searchWorkspaceEntries({
cwd,
query: "src",
limit: 1,
kind: "file",
});
expect(result.entries).toEqual([{ path: "src/index.ts", kind: "file" }]);
expect(result.truncated).toBe(true);
}),
);
it.effect("answers an empty file-filtered query with a bounded file listing", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-empty-query-" });
yield* writeTextFile(cwd, "src/index.ts");
yield* writeTextFile(cwd, "README.md");
const result = yield* searchWorkspaceEntries({
cwd,
query: "",
limit: 10,
kind: "file",
});
const paths = result.entries.map((entry) => entry.path);
expect(paths).toHaveLength(2);
expect(paths).toContain("src/index.ts");
expect(paths).toContain("README.md");
expect(result.entries.every((entry) => entry.kind === "file")).toBe(true);
}),
);
it.effect("returns only directories for the directory filter", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-directory-filter-" });
yield* writeTextFile(cwd, "src/index.ts");
const result = yield* searchWorkspaceEntries({
cwd,
query: "src",
limit: 10,
kind: "directory",
});
expect(result.entries).toEqual([{ path: "src", kind: "directory" }]);
expect(result.truncated).toBe(false);
}),
);
it.effect("excludes gitignored paths for git repositories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
@@ -292,6 +353,287 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
);
});
describe("searchContents", () => {
it.effect("returns content matches with file paths, line numbers, and ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
yield* writeTextFile(
cwd,
"src/shapes.ts",
"export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
);
yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "Square",
limit: 100,
caseSensitive: false,
wholeWord: true,
useRegex: false,
});
expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
["src/shapes.ts", 1],
["src/shapes.ts", 2],
]);
expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
expect(result.truncated).toBe(false);
}),
);
it.effect("honors case sensitivity and gitignore rules", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
yield* writeTextFile(cwd, "ignored.txt", "Square\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "Square",
limit: 100,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
}),
);
it.effect("filters whole-word matches by word boundaries without widening ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-whole-word-" });
yield* writeTextFile(cwd, "src/words.ts", "note notes denote\nfootnote note\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "note",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
// "notes", "denote", and "footnote" are word-adjacent and excluded;
// ranges cover exactly the query, never boundary characters.
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [{ start: 0, end: 4 }],
}),
expect.objectContaining({
path: "src/words.ts",
lineNumber: 2,
matchRanges: [{ start: 9, end: 13 }],
}),
]);
}),
);
it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo",
limit: 1,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 11,
matchRanges: [{ start: 0, end: 3 }],
}),
]);
}),
);
it.effect("treats astral-plane letters as whole word characters", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result.matches).toEqual([
expect.objectContaining({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [{ start: 6, end: 9 }],
}),
]);
}),
);
it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "-foo-",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
// Consuming-boundary regex would swallow the separating spaces and
// drop the middle occurrence; boundary post-filtering keeps all three.
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [
{ start: 0, end: 5 },
{ start: 6, end: 11 },
{ start: 12, end: 17 },
],
});
}),
);
it.effect("matches punctuation-edged regex queries as whole words", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-punctuation-" });
yield* writeTextFile(cwd, "src/words.ts", "foo- foo-\nafoo-b\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo-",
limit: 100,
caseSensitive: true,
wholeWord: true,
useRegex: true,
});
// wholeWord + useRegex must not silently drop non-word-edged patterns
// like "foo-", and "afoo-" is excluded because 'a'/'f' are both word
// characters at the match's left edge.
expect(result.matches).toHaveLength(1);
expect(result.matches[0]).toMatchObject({
path: "src/words.ts",
lineNumber: 1,
matchRanges: [
{ start: 0, end: 4 },
{ start: 5, end: 9 },
],
});
}),
);
it.effect("caps matches per file so one dense file cannot fill the page", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
yield* writeTextFile(cwd, "src/other.ts", "needle\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "needle",
limit: 500,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
const byPath = new Map<string, number>();
for (const match of result.matches) {
byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
}
expect(byPath.get("src/dense.ts")).toBe(100);
expect(byPath.get("src/other.ts")).toBe(1);
}),
);
it.effect("preserves regex escapes during case-insensitive searches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "\\SQUARE",
limit: 100,
caseSensitive: false,
wholeWord: false,
useRegex: true,
});
expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
}),
);
it.effect("preserves invalid regex errors during case-insensitive searches", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" });
yield* writeTextFile(cwd, "src/shapes.ts", "foobar\n");
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "foo)bar(",
limit: 100,
caseSensitive: false,
wholeWord: false,
useRegex: true,
});
expect(result.regexFallbackError).toBeDefined();
expect(result.matches).toEqual([]);
}),
);
it.effect("maps multi-byte lines to string-indexed ranges", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const result = yield* workspaceEntries.searchContents({
cwd,
query: "wörld",
limit: 100,
caseSensitive: true,
wholeWord: false,
useRegex: false,
});
expect(result.matches).toHaveLength(1);
const match = result.matches[0]!;
const range = match.matchRanges[0]!;
expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
}),
);
});
describe("browse", () => {
it.effect("returns matching directories and excludes files", () =>
Effect.gen(function* () {
+71 -34
View File
@@ -14,11 +14,14 @@ import type {
FilesystemBrowseResult,
ProjectListEntriesInput,
ProjectListEntriesResult,
ProjectSearchContentsInput,
ProjectSearchContentsResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
@@ -93,6 +96,9 @@ export class WorkspaceEntries extends Context.Service<
readonly search: (
input: ProjectSearchEntriesInput,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
readonly searchContents: (
input: ProjectSearchContentsInput,
) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
readonly refresh: (cwd: string) => Effect.Effect<void>;
}
>()("t3/workspace/WorkspaceEntries") {}
@@ -148,33 +154,37 @@ export const make = Effect.gen(function* () {
const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
Effect.orElseSucceed(() => cwd),
);
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
return;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
continue;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
variant,
cause,
});
yield* workspaceSearchIndexes.invalidate(indexKey);
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
});
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
);
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(indexKey)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
);
}
},
);
@@ -230,28 +240,55 @@ export const make = Effect.gen(function* () {
const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
const normalizedQuery = input.query
.trim()
.toLowerCase()
.replace(/^[@./]+/, "");
const normalizedQuery = normalizeSearchQuery(input.query, {
trimLeadingPattern: /^[@./]+/,
});
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.search(normalizedQuery, input.limit);
}).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
),
),
);
},
);
const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
"WorkspaceEntries.searchContents",
)(function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.searchContents(input);
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
),
),
);
});
const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
function* (input) {
const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.list();
}).pipe(Effect.provide(workspaceSearchIndexes.get(normalizedCwd)));
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
),
),
);
},
);
return WorkspaceEntries.of({ browse, list, refresh, search });
return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
});
export const layer = Layer.effect(WorkspaceEntries, make).pipe(
@@ -1,4 +1,4 @@
import { FileFinder } from "@ff-labs/fff-node";
import { FileFinder, type GrepCursor, type GrepOptions, type GrepResult } from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
@@ -51,6 +51,41 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
}),
);
it.effect("waits for the full content index warmup before returning", () =>
Effect.gen(function* () {
const waitForIndexReady = vi.fn(async () => ({ ok: true as const, value: true }));
const finder = {
destroy: vi.fn(),
waitForIndexReady,
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content"));
expect(waitForIndexReady).toHaveBeenCalledWith(15_000);
}),
);
it.effect("preserves a full-index warmup timeout as a structured error", () =>
Effect.gen(function* () {
const finder = {
destroy: vi.fn(),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const error = yield* Effect.flip(
Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content")),
);
expect(error).toMatchObject({
_tag: "WorkspaceSearchIndexScanTimedOut",
cwd: "/workspace/project",
timeout: "15 seconds",
});
}),
);
it.effect("preserves FileFinder destroy failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native destroy failed");
@@ -58,7 +93,7 @@ it.effect("preserves FileFinder destroy failures as structured defects", () =>
destroy: vi.fn(() => {
throw cause;
}),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
@@ -85,12 +120,16 @@ it.effect("preserves search and refresh failures with operation context", () =>
Effect.gen(function* () {
const searchCause = new Error("native search failed");
const refreshCause = new Error("native scan failed");
const contentSearchCause = new Error("native grep failed");
const finder = {
destroy: vi.fn(),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
mixedSearch: vi.fn(() => {
throw searchCause;
}),
grep: vi.fn(() => {
throw contentSearchCause;
}),
scanFiles: vi.fn(() => {
throw refreshCause;
}),
@@ -100,6 +139,15 @@ it.effect("preserves search and refresh failures with operation context", () =>
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
const query = "authorization: Bearer secret-token";
const searchError = yield* Effect.flip(searchIndex.search(query, 3));
const contentSearchError = yield* Effect.flip(
searchIndex.searchContents({
query,
limit: 3,
caseSensitive: false,
wholeWord: false,
useRegex: false,
}),
);
const refreshError = yield* Effect.flip(searchIndex.refresh());
expect(searchError).toMatchObject({
@@ -112,6 +160,16 @@ it.effect("preserves search and refresh failures with operation context", () =>
});
expect(searchError).not.toHaveProperty("query");
expect(searchError.message).not.toMatch(/Bearer|secret-token/);
expect(contentSearchError).toMatchObject({
_tag: "WorkspaceSearchIndexSearchFailed",
cwd: "/workspace/project",
queryLength: query.length,
pageSize: 3,
reason: "FileFinder.grep threw unexpectedly.",
cause: contentSearchCause,
});
expect(contentSearchError).not.toHaveProperty("query");
expect(contentSearchError.message).not.toMatch(/Bearer|secret-token/);
expect(refreshError).toMatchObject({
_tag: "WorkspaceSearchIndexRefreshFailed",
cwd: "/workspace/project",
@@ -127,7 +185,7 @@ it.effect("keeps returned search diagnostics out of the cause chain", () =>
Effect.gen(function* () {
const finder = {
destroy: vi.fn(),
isScanning: vi.fn(() => false),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
mixedSearch: vi.fn(() => ({ ok: false, error: "native query rejected" })),
scanFiles: vi.fn(() => ({ ok: false, error: "native refresh rejected" })),
} as unknown as FileFinder;
@@ -157,3 +215,80 @@ it.effect("keeps returned search diagnostics out of the cause chain", () =>
}),
),
);
it.effect("continues whole-word searches after a filtered grep page", () =>
Effect.scoped(
Effect.gen(function* () {
const nextCursor = {
__brand: "GrepCursor",
_offset: 1,
} as GrepCursor;
const grepResult = (
lineContent: string,
matchRanges: Array<[number, number]>,
cursor: GrepCursor | null,
): GrepResult => ({
items: [
{
relativePath: "src/words.ts",
fileName: "words.ts",
gitStatus: "unmodified",
size: lineContent.length,
modified: 0,
isBinary: false,
totalFrecencyScore: 0,
accessFrecencyScore: 0,
modificationFrecencyScore: 0,
lineNumber: 1,
col: 0,
byteOffset: 0,
lineContent,
matchRanges,
},
],
totalMatched: 1,
totalFilesSearched: 1,
totalFiles: 1,
filteredFileCount: 1,
nextCursor: cursor,
});
const grep = vi.fn((_query: string, options?: GrepOptions) =>
options?.cursor
? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
: {
ok: true as const,
value: grepResult("needleSuffix", [[0, 6]], nextCursor),
},
);
const finder = {
destroy: vi.fn(),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
grep,
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
const result = yield* searchIndex.searchContents({
query: "needle",
limit: 1,
caseSensitive: true,
wholeWord: true,
useRegex: false,
});
expect(result).toEqual({
matches: [
{
path: "src/words.ts",
lineNumber: 1,
lineContent: "needle",
matchRanges: [{ start: 0, end: 6 }],
},
],
truncated: false,
});
expect(grep).toHaveBeenCalledTimes(2);
expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
}),
),
);
+275 -40
View File
@@ -1,22 +1,36 @@
import { FileFinder, type MixedItem, type MixedSearchResult } from "@ff-labs/fff-node";
import {
type DirItem,
type DirSearchResult,
type FileItem,
FileFinder,
type GrepCursor,
type MixedItem,
type MixedSearchResult,
type Result,
type SearchResult,
} from "@ff-labs/fff-node";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as LayerMap from "effect/LayerMap";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import type {
ProjectEntry,
ProjectEntryKind,
ProjectListEntriesResult,
ProjectSearchContentsInput,
ProjectSearchContentsResult,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;
const WORKSPACE_INDEX_IDLE_TTL = "15 minutes";
const WORKSPACE_INDEX_SCAN_POLL_INTERVAL = "50 millis";
const CONTENT_SEARCH_TIME_BUDGET_MS = 250;
const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;
export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexCreateFailed>()(
"WorkspaceSearchIndexCreateFailed",
@@ -96,7 +110,11 @@ export class WorkspaceSearchIndex extends Context.Service<
readonly search: (
query: string,
limit: number,
kind?: ProjectEntryKind,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
readonly searchContents: (
input: Omit<ProjectSearchContentsInput, "cwd">,
) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;
readonly refresh: () => Effect.Effect<
void,
WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut
@@ -129,6 +147,43 @@ function toProjectEntry(item: MixedItem): ProjectEntry | null {
};
}
function toFileEntry(item: FileItem): ProjectEntry | null {
const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
return normalizedPath ? { path: normalizedPath, kind: "file" } : null;
}
function toDirectoryEntry(item: DirItem): ProjectEntry | null {
const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));
return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
}
function mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {
return {
entries: result.items
.flatMap((item) => {
const entry = toFileEntry(item);
return entry ? [entry] : [];
})
.slice(0, limit),
truncated: result.totalMatched > limit,
};
}
function mapDirectorySearchResult(
result: DirSearchResult,
limit: number,
): ProjectSearchEntriesResult {
const entries = result.items.flatMap((item) => {
const entry = toDirectoryEntry(item);
return entry ? [entry] : [];
});
const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;
return {
entries: entries.slice(0, limit),
truncated: result.totalMatched - rootDirectoryCount > limit,
};
}
function mapMixedSearchResult(
result: MixedSearchResult,
limit: number,
@@ -155,6 +210,74 @@ function mapMixedSearchResult(
};
}
const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u;
function codePointAt(line: string, index: number): string | undefined {
const codePoint = line.codePointAt(index);
return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);
}
function codePointBefore(line: string, index: number): string | undefined {
if (index <= 0) return undefined;
const previousCodeUnit = line.charCodeAt(index - 1);
const previousIndex =
previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;
return codePointAt(line, previousIndex);
}
function buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, "cwd">): {
readonly searchQuery: string;
readonly regexMode: boolean;
} {
if (input.caseSensitive) {
return { searchQuery: input.query, regexMode: input.useRegex };
}
// Plain mode relies on smart case: an all-lowercase needle matches
// case-insensitively. Regex mode needs an explicit inline flag instead.
return input.useRegex
? { searchQuery: `(?i)${input.query}`, regexMode: true }
: { searchQuery: input.query.toLowerCase(), regexMode: false };
}
function mapContentMatchRanges(
line: string,
byteRanges: ReadonlyArray<readonly [number, number]>,
): Array<{ readonly start: number; readonly end: number }> {
const lineBytes = Buffer.from(line);
const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;
return byteRanges.map(([startByte, endByte]) => ({
start: toStringIndex(startByte),
end: toStringIndex(endByte),
}));
}
/**
* Whole-word filtering happens after the grep rather than by wrapping the
* pattern in boundary regex: consuming boundaries such as `(?:^|\W)` swallow
* the separator between adjacent matches and widen the reported ranges, and
* `\b` cannot match punctuation-edged queries at all. Matching VS Code, a
* match edge is a word boundary when it touches the line edge, the
* neighbouring character is not a word character, or the match's own edge
* character is not a word character.
*/
function isWholeWordRange(
line: string,
range: { readonly start: number; readonly end: number },
): boolean {
if (range.end <= range.start) return false;
const isWord = (character: string | undefined) =>
character !== undefined && WORD_CHARACTER.test(character);
const leftIsBoundary =
range.start === 0 ||
!isWord(codePointBefore(line, range.start)) ||
!isWord(codePointAt(line, range.start));
const rightIsBoundary =
range.end >= line.length ||
!isWord(codePointAt(line, range.end)) ||
!isWord(codePointBefore(line, range.end));
return leftIsBoundary && rightIsBoundary;
}
function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {
const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));
for (const entry of entries) {
@@ -169,13 +292,19 @@ function withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEn
return [...entryByPath.values()];
}
const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (cwd: string) {
const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
cwd: string,
variant: WorkspaceSearchIndexVariant,
) {
const result = yield* Effect.try({
try: () =>
FileFinder.create({
basePath: cwd,
disableMmapCache: true,
disableContentIndexing: true,
// Content indexing costs scan CPU and memory, so only the on-demand
// content-search index pays for it; path-only consumers (file tree,
// composer path search, file picker) keep the lightweight index.
disableContentIndexing: variant !== "content",
aiMode: false,
enableFsRootScanning: true,
enableHomeDirScanning: true,
@@ -194,53 +323,65 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (c
});
});
const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unknown) => E) =>
Effect.try({
try: () => finder.isScanning(),
catch: onFailure,
}).pipe(
Effect.repeat({
while: (scanning) => scanning,
schedule: Schedule.spaced(WORKSPACE_INDEX_SCAN_POLL_INTERVAL),
}),
Effect.timeoutOrElse({
duration: WORKSPACE_INDEX_SCAN_TIMEOUT,
orElse: () =>
new WorkspaceSearchIndexScanTimedOut({ cwd, timeout: WORKSPACE_INDEX_SCAN_TIMEOUT }),
}),
Effect.withSpan("WorkspaceSearchIndex.waitForScan"),
);
const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
cwd: string,
finder: FileFinder,
onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
const result = yield* Effect.tryPromise({
try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),
catch: (cause) =>
onFailure({
reason: "FileFinder.waitForIndexReady rejected unexpectedly.",
cause,
}),
});
if (!result.ok) {
return yield* Effect.fail(onFailure({ reason: result.error }));
}
if (!result.value) {
return yield* new WorkspaceSearchIndexScanTimedOut({
cwd,
timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,
});
}
});
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
cwd: string,
variant: WorkspaceSearchIndexVariant = "paths",
) {
const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>
Effect.try({
try: () => finder.destroy(),
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
}).pipe(Effect.orDie),
);
yield* waitForScan(
yield* waitForIndexReady(
cwd,
finder,
(cause) =>
({ reason, cause }) =>
new WorkspaceSearchIndexCreateFailed({
cwd,
reason: "FileFinder.isScanning threw while creating the index.",
reason,
cause,
}),
);
const runMixedSearch = Effect.fn("WorkspaceSearchIndex.runMixedSearch")(function* (
const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* <A>(
query: string,
pageSize: number,
) {
operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch",
execute: () => Result<A>,
): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {
const result = yield* Effect.try({
try: () => finder.mixedSearch(query, { pageSize }),
try: execute,
catch: (cause) =>
new WorkspaceSearchIndexSearchFailed({
cwd,
queryLength: query.length,
pageSize,
reason: "FileFinder.mixedSearch threw unexpectedly.",
reason: `FileFinder.${operation} threw unexpectedly.`,
cause,
}),
});
@@ -273,13 +414,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
reason: result.error,
});
}
yield* waitForScan(
yield* waitForIndexReady(
cwd,
finder,
(cause) =>
({ reason, cause }) =>
new WorkspaceSearchIndexRefreshFailed({
cwd,
reason: "FileFinder.isScanning threw while refreshing the index.",
reason,
cause,
}),
);
@@ -287,7 +428,9 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")(
function* () {
const result = yield* runMixedSearch("", WORKSPACE_INDEX_PAGE_SIZE);
const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () =>
finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),
);
const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);
const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>
left.path.localeCompare(right.path),
@@ -302,20 +445,112 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: strin
const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
"WorkspaceSearchIndex.search",
)(function* (query, limit) {
const result = yield* runMixedSearch(query, Math.max(1, limit + 1));
)(function* (query, limit, kind) {
const pageSize = Math.max(1, limit + 1);
if (kind === "file") {
const result = yield* runSearch(query, pageSize, "fileSearch", () =>
finder.fileSearch(query, { pageSize }),
);
return mapFileSearchResult(result, limit);
}
if (kind === "directory") {
const result = yield* runSearch(query, pageSize, "directorySearch", () =>
finder.directorySearch(query, { pageSize }),
);
return mapDirectorySearchResult(result, limit);
}
const result = yield* runSearch(query, pageSize, "mixedSearch", () =>
finder.mixedSearch(query, { pageSize }),
);
return mapMixedSearchResult(result, limit);
});
return WorkspaceSearchIndex.of({ list, refresh, search });
const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn(
"WorkspaceSearchIndex.searchContents",
)(function* (input) {
const { searchQuery, regexMode } = buildContentSearchQuery(input);
const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;
// Grep cursors advance by file, so whole-word post-filtering needs enough
// raw candidates from the current file before moving to the next one.
const rawPageSize = input.wholeWord
? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)
: input.limit;
const matches: Array<ProjectSearchContentsResult["matches"][number]> = [];
let nextCursor: GrepCursor | null = null;
let regexFallbackError: string | undefined;
do {
const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));
const result = yield* runSearch(input.query, input.limit, "grep", () =>
finder.grep(searchQuery, {
mode: regexMode ? "regex" : "plain",
smartCase: !input.caseSensitive && !regexMode,
// A single dense file must not consume the whole result page.
maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),
pageSize: rawPageSize,
cursor: nextCursor,
timeBudgetMs: remainingTimeBudgetMs,
}),
);
for (const match of result.items) {
const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(
(range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),
);
if (matchRanges.length === 0) continue;
matches.push({
path: toPosixPath(match.relativePath),
lineNumber: match.lineNumber,
lineContent: match.lineContent,
matchRanges,
});
}
nextCursor = result.nextCursor;
regexFallbackError ??= result.regexFallbackError;
} while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);
return {
matches: matches.slice(0, input.limit),
truncated: matches.length > input.limit || nextCursor !== null,
...(regexFallbackError !== undefined ? { regexFallbackError } : {}),
};
});
return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });
});
export const WORKSPACE_SEARCH_INDEX_VARIANTS = ["paths", "content"] as const;
export type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];
/**
* Composite LayerMap key so the lightweight path index and the on-demand
* content-search index of the same workspace are separate resources with
* independent lifecycles. "\n" cannot appear in a filesystem path.
*/
export const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>
`${variant}\n${cwd}`;
function parseWorkspaceSearchIndexKey(key: string): {
readonly cwd: string;
readonly variant: WorkspaceSearchIndexVariant;
} {
const separatorIndex = key.indexOf("\n");
return {
variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,
cwd: key.slice(separatorIndex + 1),
};
}
/**
* A layer factory is required because every index is scoped to a concrete
* workspace root. WorkspaceSearchIndexMap owns memoization and idle cleanup;
* using a default cwd here would mix resources from different workspaces.
* workspace root and variant. WorkspaceSearchIndexMap owns memoization and
* idle cleanup; using a default cwd here would mix resources from different
* workspaces.
*/
export const layer = (cwd: string) => Layer.effect(WorkspaceSearchIndex, make(cwd));
export const layer = (key: string) => {
const { cwd, variant } = parseWorkspaceSearchIndexKey(key);
return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));
};
export class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(
"t3/workspace/WorkspaceSearchIndexMap",
+62
View File
@@ -23,6 +23,7 @@ import {
type GitManagerServiceError,
type MessageId,
OrchestrationGetFullThreadDiffError,
OrchestrationSearchThreadsError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_V2_WS_METHODS,
OrchestrationV2DispatchCommandError,
@@ -37,11 +38,14 @@ import {
type ProjectMutation,
ProjectListEntriesError,
ProjectReadFileError,
ProjectSearchContentsError,
ProjectSearchEntriesError,
ProjectWriteFileError,
ProjectMutationError,
RelayClientInstallFailedError,
type RelayClientInstallProgressEvent,
type ServerSelfUpdateError,
type ServerSelfUpdateProgressEvent,
type FilesystemBrowseFailure,
FilesystemBrowseError,
AssetWorkspaceContextNotFoundError,
@@ -1076,6 +1080,20 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_V2_WS_METHODS.searchThreads]: (input) =>
observeRpcEffect(
ORCHESTRATION_V2_WS_METHODS.searchThreads,
projectionSnapshotQuery.searchThreads(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationSearchThreadsError({
message: "Failed to search threads",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) =>
observeRpcEffect(
ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot,
@@ -1228,6 +1246,33 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverUpdateServerWithProgress]: (input) =>
observeRpcStream(
WS_METHODS.serverUpdateServerWithProgress,
Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) =>
serverSelfUpdate
.update(input, (stage) =>
Queue.offer(queue, {
type: "progress",
stage,
}).pipe(Effect.asVoid),
)
.pipe(
Effect.flatMap((result) =>
Queue.offer(queue, {
type: "complete",
result,
}),
),
Effect.catchTags({
ServerSelfUpdateError: (error) => Queue.fail(queue, error),
}),
Effect.andThen(Queue.end(queue)),
Effect.forkScoped,
),
),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
observeRpcEffect(
WS_METHODS.serverUpsertKeybinding,
@@ -1417,6 +1462,23 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsSearchContents]: (input) =>
observeRpcEffect(
WS_METHODS.projectsSearchContents,
workspaceEntries.searchContents(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchContentsError({
cwd: input.cwd,
queryLength: input.query.length,
limit: input.limit,
...projectEntriesFailureContext(cause),
cause,
}),
),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsListEntries]: (input) =>
observeRpcEffect(
WS_METHODS.projectsListEntries,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.30",
"version": "0.0.31",
"private": true,
"type": "module",
"scripts": {
+8 -1
View File
@@ -145,7 +145,14 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
case "RelayEnvironmentLinkProofInvalidError":
return `Relay rejected the environment link proof (${error.reason}).`;
case "RelayEnvironmentConnectNotAuthorizedError":
return "Relay rejected the environment connection request.";
// "Not authorized" covers non-auth causes too; surface the reason so a
// missing link doesn't read as a credential problem.
if (error.reason === "environment_link_not_found") {
return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";
}
return error.reason
? `Relay rejected the environment connection request (${error.reason}).`
: "Relay rejected the environment connection request.";
case "RelayEnvironmentEndpointUnavailableError":
return `Relay could not reach the environment endpoint (${error.reason}).`;
case "RelayEnvironmentEndpointTimedOutError":
+5 -47
View File
@@ -1,5 +1,4 @@
import { useAtomValue } from "@effect/atom-react";
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
import {
CheckIcon,
ChevronRightIcon,
@@ -57,6 +56,8 @@ import { useOpenInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
import { RenderErrorBoundary } from "./RenderErrorBoundary";
import { useTheme } from "../hooks/useTheme";
import { getClientSettings } from "../hooks/useSettings";
import {
@@ -91,27 +92,6 @@ import {
BrowserPreviewUnavailableError,
} from "../browser/openFileInPreview";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
{ hasError: boolean }
> {
constructor(props: { fallback: ReactNode; children: ReactNode }) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
override render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
interface ChatMarkdownProps {
text: string;
cwd: string | undefined;
@@ -147,7 +127,6 @@ const highlightedCodeCache = new LRUCache<string>(
MAX_HIGHLIGHT_CACHE_ENTRIES,
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
);
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
const firstLineEnd = markdown.indexOf("\n", listItemStart);
@@ -333,27 +312,6 @@ function estimateHighlightedSize(html: string, code: string): number {
return Math.max(html.length * 2, code.length * 3);
}
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
const cached = highlighterPromiseCache.get(language);
if (cached) return cached;
const promise = getSharedHighlighter({
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
langs: [language as SupportedLanguages],
preferredHighlighter: "shiki-js",
}).catch((err) => {
highlighterPromiseCache.delete(language);
if (language === "text") {
// "text" itself failed — Shiki cannot initialize at all, surface the error
throw err;
}
// Language not supported by Shiki — fall back to "text"
return getHighlighterPromise("text");
});
highlighterPromiseCache.set(language, promise);
return promise;
}
function readInitialWordWrapSetting(): boolean {
return getClientSettings().wordWrap;
}
@@ -743,7 +701,7 @@ function UncachedShikiCodeBlock({
cacheKey,
isStreaming,
}: UncachedShikiCodeBlockProps) {
const highlighter = use(getHighlighterPromise(language));
const highlighter = use(getSyntaxHighlighterPromise(language));
const highlightedHtml = useMemo(() => {
try {
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
@@ -1605,7 +1563,7 @@ function ChatMarkdown({
fenceTitle={fenceTitle}
theme={resolvedTheme}
>
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
<RenderErrorBoundary fallback={<pre {...props}>{children}</pre>}>
<Suspense fallback={<pre {...props}>{children}</pre>}>
<SuspenseShikiCodeBlock
className={codeBlock.className}
@@ -1614,7 +1572,7 @@ function ChatMarkdown({
isStreaming={isStreaming}
/>
</Suspense>
</CodeHighlightErrorBoundary>
</RenderErrorBoundary>
</MarkdownCodeBlock>
);
},
+117 -57
View File
@@ -318,7 +318,7 @@ import {
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ServerUpdateAction } from "./ServerUpdateAction";
import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction";
import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
@@ -2059,79 +2059,138 @@ function ChatViewContent(props: ChatViewProps) {
}, [setDismissedVersionMismatchKey, versionMismatchDismissKey]);
const versionMismatchEnvironmentId =
versionMismatch && activeThread ? activeThread.environmentId : null;
const serverUpdateEnvironmentId = activeThread?.environmentId ?? null;
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
const serverUpdateState = useAtomValue(
serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),
);
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const items: ComposerBannerStackItem[] = [];
if (activeEnvironmentUnavailableState) {
const connection = activeEnvironmentUnavailableState.connection;
const isReconnecting =
connection.phase === "connecting" || connection.phase === "reconnecting";
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: connection.phase === "error" ? "error" : "warning",
icon: <WifiOffIcon />,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(connection)}`,
description:
connection.error ??
"Reconnect this environment before sending messages or running actions.",
actions: (
<>
<Button
size="xs"
disabled={isReconnecting}
onClick={() =>
void handleReconnectActiveEnvironment(
activeEnvironmentUnavailableState.environmentId,
)
}
>
{isReconnecting ? "Reconnecting..." : "Reconnect"}
</Button>
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
const updateRunning = serverUpdateState.status === "running";
const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;
const environmentReconnecting =
unavailableConnection !== null &&
(unavailableConnection.phase === "connecting" ||
unavailableConnection.phase === "reconnecting");
// Reconnecting to a version-skewed server with no update in flight
// usually means the server is restarting mid-update and a refresh wiped
// the in-memory update state. Fold the reconnect and version banners
// into one calm line instead of stacking "Failed to connect" on
// "versions differ". A failed update never folds: its error and retry
// action must stay visible.
const reconnectingThroughVersionSkew =
serverUpdateState.status === "idle" && environmentReconnecting && versionMismatch !== null;
// While an update runs, transient connect blips are expected (the server
// restarts) and the update banner already shows progress. Hard failure
// phases still surface so the Reconnect action stays reachable.
const suppressUnavailableBanner = updateRunning && environmentReconnecting;
if (activeEnvironmentUnavailableState && unavailableConnection && !suppressUnavailableBanner) {
if (reconnectingThroughVersionSkew) {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: "default",
icon: (
<span
className="size-1.5 animate-status-pulse rounded-full bg-foreground"
aria-hidden="true"
/>
),
title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`,
description: "It may be finishing an update. One moment.",
});
} else {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: unavailableConnection.phase === "error" ? "error" : "warning",
icon: <WifiOffIcon />,
title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(unavailableConnection)}`,
description:
unavailableConnection.error ??
"Reconnect this environment before sending messages or running actions.",
actions: (
<>
<Button
size="xs"
disabled={environmentReconnecting}
onClick={() =>
void handleReconnectActiveEnvironment(
activeEnvironmentUnavailableState.environmentId,
)
}
>
{environmentReconnecting ? "Reconnecting..." : "Reconnect"}
</Button>
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
}
}
if (
showVersionMismatchBanner &&
versionMismatch &&
versionMismatchDismissKey &&
versionMismatchEnvironmentId
serverUpdateEnvironmentId &&
!reconnectingThroughVersionSkew &&
(serverUpdateState.status !== "idle" ||
(showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey))
) {
const updateInProgress = serverUpdateState.status === "running";
const updateFailed = serverUpdateState.status === "failed";
items.push({
id: `version-mismatch:${versionMismatchDismissKey}`,
variant: "warning",
icon: <TriangleAlertIcon />,
title: "Client and server versions differ",
description: (
<>
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
{versionMismatch.serverVersion}.{" "}
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
</>
id: `server-version:${serverUpdateEnvironmentId}`,
variant: updateFailed ? "error" : updateInProgress ? "default" : "warning",
icon: updateInProgress ? (
<span
className="size-1.5 animate-status-pulse rounded-full bg-foreground"
aria-hidden="true"
/>
) : (
<TriangleAlertIcon />
),
title:
updateInProgress || updateFailed
? `${updateFailed ? "Could not update" : "Updating"} ${versionMismatchServerLabel}`
: "Client and server versions differ",
description:
updateInProgress || updateFailed ? (
<ServerUpdateProgress
fromVersion={serverUpdateState.fromVersion}
state={serverUpdateState}
/>
) : versionMismatch ? (
<>
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
{versionMismatch.serverVersion}.{" "}
{serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)}
</>
) : null,
// The desktop-managed guidance is already the description; the action
// slot would only repeat it.
actions:
updateInProgress ||
!versionMismatch ||
versionMismatchSelfUpdate === "desktop-managed" ? undefined : (
<ServerUpdateAction
environmentId={versionMismatchEnvironmentId}
environmentId={serverUpdateEnvironmentId}
serverLabel={versionMismatchServerLabel}
selfUpdate={versionMismatchSelfUpdate}
targetVersion={versionMismatch.clientVersion}
{...(updateFailed ? { label: "Retry update" } : {})}
/>
),
dismissLabel: "Dismiss version mismatch warning",
onDismiss: () => {
dismissVersionMismatch(versionMismatchDismissKey);
setDismissedVersionMismatchKey(versionMismatchDismissKey);
},
...(updateInProgress || updateFailed || !versionMismatchDismissKey
? {}
: {
dismissLabel: "Dismiss version mismatch warning",
onDismiss: () => {
dismissVersionMismatch(versionMismatchDismissKey);
setDismissedVersionMismatchKey(versionMismatchDismissKey);
},
}),
});
}
return items;
@@ -2141,9 +2200,10 @@ function ChatViewContent(props: ChatViewProps) {
navigate,
setDismissedVersionMismatchKey,
showVersionMismatchBanner,
serverUpdateState,
versionMismatch,
versionMismatchDismissKey,
versionMismatchEnvironmentId,
serverUpdateEnvironmentId,
versionMismatchSelfUpdate,
versionMismatchServerLabel,
]);
@@ -7,9 +7,81 @@ import {
buildThreadActionItems,
enumerateCommandPaletteItems,
filterCommandPaletteGroups,
reduceCommandPaletteUiState,
type CommandPaletteGroup,
} from "./CommandPalette.logic";
describe("reduceCommandPaletteUiState", () => {
const closedState = { open: false, mode: "command", openIntent: null } as const;
it("toggles each overlay mode open and closed", () => {
const filesOpen = reduceCommandPaletteUiState(closedState, {
_tag: "ToggleMode",
mode: "files",
});
expect(filesOpen).toEqual({ open: true, mode: "files", openIntent: null });
const contentOpen = reduceCommandPaletteUiState(filesOpen, {
_tag: "ToggleMode",
mode: "content",
});
expect(contentOpen).toEqual({ open: true, mode: "content", openIntent: null });
expect(
reduceCommandPaletteUiState(contentOpen, { _tag: "ToggleMode", mode: "content" }),
).toEqual({ open: false, mode: "command", openIntent: null });
});
it("switches between open modes without closing", () => {
const filesOpen = reduceCommandPaletteUiState(closedState, {
_tag: "ToggleMode",
mode: "files",
});
expect(reduceCommandPaletteUiState(filesOpen, { _tag: "ToggleMode", mode: "command" })).toEqual(
{
open: true,
mode: "command",
openIntent: null,
},
);
});
it("routes open intents to command mode", () => {
const filesOpen = reduceCommandPaletteUiState(closedState, {
_tag: "ToggleMode",
mode: "files",
});
expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenAddProject" })).toEqual({
open: true,
mode: "command",
openIntent: { kind: "add-project" },
});
expect(reduceCommandPaletteUiState(filesOpen, { _tag: "OpenNewThreadIn" })).toEqual({
open: true,
mode: "command",
openIntent: { kind: "new-thread-in" },
});
});
it("resets to command mode for dialog-driven opens and closes", () => {
const filesOpen = reduceCommandPaletteUiState(closedState, {
_tag: "ToggleMode",
mode: "files",
});
expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: false })).toEqual({
open: false,
mode: "command",
openIntent: null,
});
expect(reduceCommandPaletteUiState(filesOpen, { _tag: "SetOpen", open: true })).toEqual({
open: true,
mode: "command",
openIntent: null,
});
});
});
describe("enumerateCommandPaletteItems", () => {
it("assigns positional jump shortcuts to the first nine displayed items", () => {
const items = Array.from({ length: 10 }, (_, index) => ({
@@ -168,6 +240,29 @@ describe("buildThreadActionItems", () => {
expect(groups[0]?.items.map((item) => item.value)).toEqual(["thread:project-context-only"]);
});
it("keeps message excerpts searchable without replacing thread metadata", () => {
const [item] = buildThreadActionItems({
threads: [makeThread({ branch: "feat/search" })],
projectTitleById: new Map([[PROJECT_ID, "T3 Code"]]),
sortOrder: "updated_at",
icon: null,
getContentMatch: () => ({
source: "assistant",
snippet: "The relay reconnect is now bounded.",
query: "reconnect",
}),
runThread: async (_thread) => undefined,
});
expect(item?.searchTerms).toContain("The relay reconnect is now bounded.");
expect(item?.threadContentMatch).toEqual({
source: "assistant",
snippet: "The relay reconnect is now bounded.",
query: "reconnect",
});
expect(item?.description).toBe("T3 Code · #feat/search");
});
it("filters archived threads out of thread search items", () => {
const items = buildThreadActionItems({
threads: [
@@ -15,12 +15,68 @@ export const RECENT_THREAD_LIMIT = 12;
export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
export const ADDON_ICON_CLASS = "size-4";
/**
* The global search overlay hosts three mutually exclusive surfaces: the
* command palette (⌘K), the project file picker (⌘P), and project content
* search (⇧⌘F). One reducer owns open/mode state so the surfaces can never
* stack and re-triggering a mode's shortcut toggles it closed.
*/
export type SearchOverlayMode = "command" | "files" | "content";
export interface CommandPaletteOpenIntent {
readonly kind: "add-project" | "new-thread-in";
}
export interface CommandPaletteUiState {
readonly open: boolean;
readonly mode: SearchOverlayMode;
readonly openIntent: CommandPaletteOpenIntent | null;
}
export type CommandPaletteUiAction =
| { readonly _tag: "SetOpen"; readonly open: boolean }
| { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
| { readonly _tag: "OpenAddProject" }
| { readonly _tag: "OpenNewThreadIn" }
| { readonly _tag: "ClearOpenIntent" };
export function reduceCommandPaletteUiState(
state: CommandPaletteUiState,
action: CommandPaletteUiAction,
): CommandPaletteUiState {
switch (action._tag) {
case "SetOpen":
return {
open: action.open,
mode: "command",
openIntent: action.open ? state.openIntent : null,
};
case "ToggleMode":
return state.open && state.mode === action.mode
? { open: false, mode: "command", openIntent: null }
: { open: true, mode: action.mode, openIntent: null };
case "OpenAddProject":
return { open: true, mode: "command", openIntent: { kind: "add-project" } };
case "OpenNewThreadIn":
return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
case "ClearOpenIntent":
return state.openIntent ? { ...state, openIntent: null } : state;
}
}
export interface CommandPaletteThreadContentMatch {
readonly source: "user" | "assistant";
readonly snippet: string;
readonly query: string;
}
export interface CommandPaletteItem {
readonly kind: "action" | "submenu";
readonly value: string;
readonly searchTerms: ReadonlyArray<string>;
readonly title: ReactNode;
readonly description?: string;
readonly description?: ReactNode;
readonly threadContentMatch?: CommandPaletteThreadContentMatch;
readonly timestamp?: string;
readonly icon: ReactNode;
readonly disabled?: boolean;
@@ -114,6 +170,7 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
renderLeadingContent?: (thread: TThread) => ReactNode;
/** Optional content rendered inline after the title text per-thread. */
renderTrailingContent?: (thread: TThread) => ReactNode;
getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
limit?: number;
}): CommandPaletteActionItem[] {
@@ -140,12 +197,18 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
const leadingContent = input.renderLeadingContent?.(thread);
const trailingContent = input.renderTrailingContent?.(thread);
const contentMatch = input.getContentMatch?.(thread);
return Object.assign(
{
kind: "action" as const,
value: `thread:${thread.id}`,
searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``],
searchTerms: [
thread.title,
projectTitle ?? ``,
thread.branch ?? ``,
contentMatch?.snippet ?? ``,
],
title: thread.title,
description: descriptionParts.join(` · `),
timestamp: formatRelativeTimeLabel(
@@ -155,6 +218,7 @@ export function buildThreadActionItems<TThread extends BuildThreadActionItemsThr
},
leadingContent ? { titleLeadingContent: leadingContent } : {},
trailingContent ? { titleTrailingContent: trailingContent } : {},
contentMatch ? { threadContentMatch: contentMatch } : {},
{
run: async () => {
await input.runThread(thread);
+416 -285
View File
@@ -1,6 +1,9 @@
"use client";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import {
canPreloadBrowsePath,
createBrowseNavigationCoordinator,
@@ -25,16 +28,16 @@ import {
import { useNavigate, useParams } from "@tanstack/react-router";
import * as Option from "effect/Option";
import {
ArrowDownIcon,
ArrowLeftIcon,
ArrowUpIcon,
CornerLeftUpIcon,
FileSearchIcon,
FolderIcon,
FolderPlusIcon,
LinkIcon,
MessageSquareIcon,
SettingsIcon,
SquarePenIcon,
TextSearchIcon,
} from "lucide-react";
import {
useCallback,
@@ -64,6 +67,7 @@ import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import { useThreadSearch } from "../state/queries";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
@@ -77,7 +81,9 @@ import {
resolveProjectPathForDispatch,
} from "../lib/projectPaths";
import { onOpenCommandPalette } from "../commandPaletteBus";
import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
@@ -96,6 +102,7 @@ import {
buildThreadActionItems,
enumerateCommandPaletteItems,
type CommandPaletteActionItem,
type CommandPaletteOpenIntent,
type CommandPaletteSubmenuItem,
type CommandPaletteView,
filterCommandPaletteGroups,
@@ -103,24 +110,22 @@ import {
getCommandPaletteMode,
ITEM_ICON_CLASS,
RECENT_THREAD_LIMIT,
reduceCommandPaletteUiState,
type SearchOverlayMode,
} from "./CommandPalette.logic";
import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebar.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteContent } from "./CommandPaletteContent";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";
import { resolveDefaultProviderModelSelection } from "../providerInstances";
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
import {
Command,
CommandDialog,
CommandDialogPopup,
CommandFooter,
CommandInput,
CommandPanel,
} from "./ui/command";
import { CommandDialog, CommandDialogPopup } from "./ui/command";
import { Button } from "./ui/button";
import { Kbd, KbdGroup } from "./ui/kbd";
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -163,6 +168,8 @@ interface AddProjectEnvironmentOption {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly isPrimary: boolean;
readonly isConnected: boolean;
readonly status: string;
}
type AddProjectRemoteProviderKind = Extract<
@@ -340,50 +347,30 @@ function errorMessage(error: unknown): string {
return "An error occurred.";
}
interface CommandPaletteOpenIntent {
readonly kind: "add-project" | "new-thread-in";
}
const OVERLAY_MODE_BY_COMMAND = {
"commandPalette.toggle": "command",
"filePicker.toggle": "files",
"projectSearch.toggle": "content",
} as const satisfies Partial<Record<string, SearchOverlayMode>>;
interface CommandPaletteUiState {
readonly open: boolean;
readonly openIntent: CommandPaletteOpenIntent | null;
}
type CommandPaletteUiAction =
| { readonly _tag: "SetOpen"; readonly open: boolean }
| { readonly _tag: "Toggle" }
| { readonly _tag: "OpenAddProject" }
| { readonly _tag: "OpenNewThreadIn" }
| { readonly _tag: "ClearOpenIntent" };
function reduceCommandPaletteUiState(
state: CommandPaletteUiState,
action: CommandPaletteUiAction,
): CommandPaletteUiState {
switch (action._tag) {
case "SetOpen":
return {
open: action.open,
openIntent: action.open ? state.openIntent : null,
};
case "Toggle":
return { open: !state.open, openIntent: null };
case "OpenAddProject":
return { open: true, openIntent: { kind: "add-project" } };
case "OpenNewThreadIn":
return { open: true, openIntent: { kind: "new-thread-in" } };
case "ClearOpenIntent":
return state.openIntent ? { ...state, openIntent: null } : state;
}
function overlayModeForCommand(command: string | null): SearchOverlayMode | null {
if (command === null) return null;
return command in OVERLAY_MODE_BY_COMMAND
? OVERLAY_MODE_BY_COMMAND[command as keyof typeof OVERLAY_MODE_BY_COMMAND]
: null;
}
export function CommandPalette({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {
open: false,
mode: "command",
openIntent: null,
});
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
const toggleMode = useCallback(
(mode: SearchOverlayMode) => dispatch({ _tag: "ToggleMode", mode }),
[],
);
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
@@ -399,26 +386,48 @@ export function CommandPalette({ children }: { children: ReactNode }) {
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
const previewOpen = useRightPanelStore((state) =>
routeThreadRef
? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
: false,
);
useEffect(() => {
if (!state.open || state.mode === "command") return;
const onEscapeKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.isComposing || event.key !== "Escape") return;
event.preventDefault();
event.stopPropagation();
toggleMode("command");
};
window.addEventListener("keydown", onEscapeKeyDown, true);
return () => window.removeEventListener("keydown", onEscapeKeyDown, true);
}, [state.mode, state.open, toggleMode]);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.defaultPrevented) return;
// Resolve with the complete shortcut context so customized bindings
// using any documented `when` condition (e.g. previewFocus) work.
const command = resolveShortcutCommand(event, keybindings, {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
previewFocus: isPreviewFocused(),
previewOpen,
},
});
if (command !== "commandPalette.toggle") {
const mode = overlayModeForCommand(command);
if (mode === null) {
return;
}
event.preventDefault();
event.stopPropagation();
toggleOpen();
toggleMode(mode);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [keybindings, terminalOpen, toggleOpen]);
}, [keybindings, previewOpen, terminalOpen, toggleMode]);
useEffect(
() =>
@@ -436,12 +445,24 @@ export function CommandPalette({ children }: { children: ReactNode }) {
return (
<ComposerHandleContext value={composerHandleRef}>
<CommandDialog open={state.open} onOpenChange={setOpen}>
<CommandDialog
open={state.open}
onOpenChange={(open, eventDetails) => {
if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") {
eventDetails.cancel();
toggleMode("command");
return;
}
setOpen(open);
}}
>
{children}
<CommandPaletteDialog
open={state.open}
mode={state.mode}
openIntent={state.openIntent}
setOpen={setOpen}
openOverlayMode={toggleMode}
clearOpenIntent={clearOpenIntent}
/>
</CommandDialog>
@@ -451,31 +472,63 @@ export function CommandPalette({ children }: { children: ReactNode }) {
function CommandPaletteDialog(props: {
readonly open: boolean;
readonly mode: SearchOverlayMode;
readonly openIntent: CommandPaletteOpenIntent | null;
readonly setOpen: (open: boolean) => void;
readonly openOverlayMode: (mode: SearchOverlayMode) => void;
readonly clearOpenIntent: () => void;
}) {
const composerHandleRef = useComposerHandleContext();
if (!props.open) {
return null;
}
return (
<OpenCommandPaletteDialog
openIntent={props.openIntent}
setOpen={props.setOpen}
clearOpenIntent={props.clearOpenIntent}
/>
<CommandDialogPopup
aria-label={
props.mode === "files"
? "File picker"
: props.mode === "content"
? "Search project contents"
: "Command palette"
}
className={cn("overflow-hidden p-0", props.mode === "content" && "h-105")}
data-command-palette="true"
data-palette-mode={props.mode}
data-testid="command-palette"
finalFocus={() => {
composerHandleRef?.current?.focusAtEnd();
return false;
}}
onBackdropPointerDown={() => {
props.setOpen(false);
}}
>
{props.mode === "files" ? (
<ProjectFilePicker setOpen={props.setOpen} />
) : props.mode === "content" ? (
<ProjectContentSearchDialog onOpenChange={props.setOpen} />
) : (
<OpenCommandPaletteDialog
openIntent={props.openIntent}
setOpen={props.setOpen}
openOverlayMode={props.openOverlayMode}
clearOpenIntent={props.clearOpenIntent}
/>
)}
</CommandDialogPopup>
);
}
function OpenCommandPaletteDialog(props: {
readonly openIntent: CommandPaletteOpenIntent | null;
readonly setOpen: (open: boolean) => void;
readonly openOverlayMode: (mode: SearchOverlayMode) => void;
readonly clearOpenIntent: () => void;
}) {
const navigate = useNavigate();
const { clearOpenIntent, openIntent, setOpen } = props;
const composerHandleRef = useComposerHandleContext();
const { clearOpenIntent, openIntent, openOverlayMode, setOpen } = props;
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const isActionsOnly = deferredQuery.startsWith(">");
@@ -506,6 +559,26 @@ function OpenCommandPaletteDialog(props: {
const providers = useAtomValue(primaryServerProvidersAtom);
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
const environmentIds = useMemo(
() =>
environments
.filter((environment) => environment.connection.phase === "connected")
.map((environment) => environment.environmentId),
[environments],
);
const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : "";
const threadSearch = useThreadSearch(environmentIds, threadSearchQuery);
const threadContentMatchByKey = useMemo(
() =>
new Map(
threadSearch.matches.flatMap((match) =>
match.source === "user" || match.source === "assistant"
? [[threadSearchMatchKey(match), match] as const]
: [],
),
),
[threadSearch.matches],
);
const [browseGeneration, setBrowseGeneration] = useState(0);
const browseNavigationRef = useRef<ReturnType<typeof createBrowseNavigationCoordinator> | null>(
null,
@@ -620,6 +693,8 @@ function OpenCommandPaletteDialog(props: {
runtimeLabel: environment.label,
}),
isPrimary,
isConnected: canCreateProjectInEnvironment(environment.connection.phase),
status: connectionStatusText(environment.connection),
};
});
@@ -632,10 +707,14 @@ function OpenCommandPaletteDialog(props: {
return options;
}, [environments]);
const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null;
const defaultAddProjectEnvironmentId =
addProjectEnvironmentOptions.find((option) => option.isConnected)?.environmentId ?? null;
const wslAddProjectEnvironmentOption = useMemo(
() =>
addProjectEnvironmentOptions.find((option) => {
if (!option.isConnected) {
return false;
}
const environment = environments.find(
(candidate) => candidate.environmentId === option.environmentId,
);
@@ -906,6 +985,21 @@ function OpenCommandPaletteDialog(props: {
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
renderTrailingContent: (thread) => <ThreadRowTrailingStatus thread={thread} />,
getContentMatch: (thread) => {
const match = threadContentMatchByKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
);
return match && (match.source === "user" || match.source === "assistant")
? {
source: match.source,
snippet: match.snippet,
query: threadSearchQuery,
}
: undefined;
},
runThread: async (thread) => {
await navigate({
to: "/$environmentId/$threadId",
@@ -913,7 +1007,15 @@ function OpenCommandPaletteDialog(props: {
});
},
}),
[activeThreadId, clientSettings.sidebarThreadSortOrder, navigate, projectTitleById, threads],
[
activeThreadId,
clientSettings.sidebarThreadSortOrder,
navigate,
projectTitleById,
threadContentMatchByKey,
threadSearchQuery,
threads,
],
);
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
@@ -1108,6 +1210,19 @@ function OpenCommandPaletteDialog(props: {
const startAddProjectSourceSelection = useCallback(
(environmentId: EnvironmentId): void => {
const environment = environments.find(
(candidate) => candidate.environmentId === environmentId,
);
if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Environment unavailable",
description: `${environment?.label ?? "The selected environment"} is not connected.`,
}),
);
return;
}
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
pushPaletteView({
@@ -1123,6 +1238,7 @@ function OpenCommandPaletteDialog(props: {
[
browseEnvironmentId,
buildAddProjectSourceGroups,
environments,
pushPaletteView,
sourceControlDiscovery.data,
],
@@ -1134,7 +1250,12 @@ function OpenCommandPaletteDialog(props: {
value: `action:add-project:environment:${option.environmentId}`,
searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
title: option.label,
description: option.isPrimary ? "This device" : option.environmentId,
description: option.isConnected
? option.isPrimary
? "This device"
: option.environmentId
: option.status,
disabled: !option.isConnected,
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
@@ -1155,7 +1276,7 @@ function OpenCommandPaletteDialog(props: {
);
const openAddProjectFlow = useCallback(() => {
if (addProjectEnvironmentOptions.length > 1) {
if (addProjectEnvironmentOptions.length > 1 || defaultAddProjectEnvironmentId === null) {
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
@@ -1272,6 +1393,32 @@ function OpenCommandPaletteDialog(props: {
});
}
actionItems.push({
kind: "action",
value: "action:open-file-picker",
searchTerms: ["go to file", "open file", "file picker", "find file", "quick open"],
title: "Go to file",
icon: <FileSearchIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
shortcutCommand: "filePicker.toggle",
run: async () => {
openOverlayMode("files");
},
});
actionItems.push({
kind: "action",
value: "action:search-project-contents",
searchTerms: ["search project", "find in files", "grep", "content search", "text search"],
title: "Search project contents",
icon: <TextSearchIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
shortcutCommand: "projectSearch.toggle",
run: async () => {
openOverlayMode("content");
},
});
actionItems.push({
kind: "action",
value: "action:add-project",
@@ -1294,6 +1441,7 @@ function OpenCommandPaletteDialog(props: {
"environment",
],
title: "Add project",
disabled: defaultAddProjectEnvironmentId === null,
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
@@ -1355,6 +1503,19 @@ function OpenCommandPaletteDialog(props: {
readonly platform: string;
readonly currentProjectCwd: string | null;
}) => {
const environment = environments.find(
(candidate) => candidate.environmentId === input.environmentId,
);
if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Environment unavailable",
description: `${environment?.label ?? "The selected environment"} is not connected.`,
}),
);
return;
}
const rawCwd = input.rawCwd;
if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
@@ -1507,6 +1668,16 @@ function OpenCommandPaletteDialog(props: {
if (!addProjectCloneFlow) {
return;
}
if (!canCreateProjectInEnvironment(browseEnvironment?.connection.phase)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Environment unavailable",
description: `${browseEnvironment?.label ?? "The selected environment"} is not connected.`,
}),
);
return;
}
if (addProjectCloneFlow.step === "repository") {
const rawRepository = query.trim();
@@ -1711,7 +1882,10 @@ function OpenCommandPaletteDialog(props: {
getCommandPaletteInputPlaceholder(paletteMode);
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
const canSubmitBrowsePath =
isBrowsing &&
!relativePathNeedsActiveProject &&
canCreateProjectInEnvironment(browseEnvironment?.connection.phase);
const willCreateProjectPath =
canSubmitBrowsePath &&
!isBrowsePending &&
@@ -1738,6 +1912,7 @@ function OpenCommandPaletteDialog(props: {
const canSubmitRemoteProjectFlow =
addProjectCloneFlow?.step === "repository" &&
query.trim().length > 0 &&
canCreateProjectInEnvironment(browseEnvironment?.connection.phase) &&
!isRemoteProjectPending;
const fileManagerName = getLocalFileManagerName(navigator.platform);
const canOpenProjectFromFileManager =
@@ -1960,233 +2135,189 @@ function OpenCommandPaletteDialog(props: {
primaryEnvironmentId,
]);
return (
<CommandDialogPopup
aria-label="Command palette"
className="overflow-hidden p-0"
data-command-palette="true"
data-testid="command-palette"
finalFocus={() => {
composerHandleRef?.current?.focusAtEnd();
return false;
}}
onBackdropPointerDown={() => {
setOpen(false);
const inputAccessory =
addProjectCloneFlow?.step === "repository" ? (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
disabled={!canSubmitRemoteProjectFlow}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
void submitAddProjectCloneFlow();
}}
/>
}
>
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>Enter</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">{remoteProjectButtonLabel ?? "Continue"} (Enter)</TooltipPopup>
</Tooltip>
) : isBrowsing ? (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className={cn(
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
!canCreateProjectInEnvironment(browseEnvironment?.connection.phase) ||
relativePathNeedsActiveProject ||
(isCloneDestinationStep && isRemoteProjectPending)
}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
if (relativePathNeedsActiveProject) {
return;
}
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
}}
/>
}
>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{submitActionLabel} ({addShortcutLabel})
</TooltipPopup>
</Tooltip>
) : null;
const footerActionLabel =
addProjectCloneFlow?.step === "repository"
? (remoteProjectButtonLabel ?? "Continue")
: !canSubmitBrowsePath || hasHighlightedBrowseItem
? "Select"
: undefined;
const footerTrailing = canOpenProjectFromFileManager ? (
<Button
variant="ghost"
size="xs"
className="h-auto px-2 text-muted-foreground text-xs hover:bg-transparent hover:text-foreground"
disabled={isPickingProjectFolder}
onClick={() => {
void handleOpenProjectFromFileManager();
}}
>
<Command
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
aria-label="Command palette"
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
}}
onValueChange={handleQueryChange}
value={query}
>
<div className="relative">
<CommandInput
className={
addProjectCloneFlow?.step === "repository"
? "pe-32"
: isBrowsing
? willCreateProjectPath
? "pe-36"
: "pe-16"
: undefined
{`Open in ${fileManagerName}`}
</Button>
) : null;
return (
<CommandPaletteContent
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
aria-label="Command palette"
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
footerActionLabel={footerActionLabel}
footerTrailing={footerTrailing}
inputAccessory={inputAccessory}
inputProps={{
className:
addProjectCloneFlow?.step === "repository"
? "pe-32"
: isBrowsing
? willCreateProjectPath
? "pe-36"
: "pe-16"
: undefined,
placeholder: inputPlaceholder,
wrapperClassName: isSubmenu
? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto"
: undefined,
...(isSubmenu
? {
startAddon: (
<button
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
>
<ArrowLeftIcon />
</button>
),
}
placeholder={inputPlaceholder}
wrapperClassName={
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
}
{...(isSubmenu
? {
startAddon: (
<button
type="button"
className="flex cursor-pointer items-center"
aria-label="Back"
onClick={popView}
>
<ArrowLeftIcon />
</button>
),
}
: isBrowsing && !isSubmenu
? {
startAddon: <FolderPlusIcon />,
}
: {})}
onKeyDown={handleKeyDown}
/>
{addProjectCloneFlow?.step === "repository" ? (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
disabled={!canSubmitRemoteProjectFlow}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
void submitAddProjectCloneFlow();
}}
/>
}
>
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>Enter</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{remoteProjectButtonLabel ?? "Continue"} (Enter)
</TooltipPopup>
</Tooltip>
) : isBrowsing ? (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
tabIndex={-1}
className={cn(
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
relativePathNeedsActiveProject ||
(isCloneDestinationStep && isRemoteProjectPending)
}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
if (relativePathNeedsActiveProject) {
return;
}
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
}}
/>
}
>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{submitActionLabel} ({addShortcutLabel})
</TooltipPopup>
</Tooltip>
) : null}
</div>
<CommandPanel className="max-h-[min(28rem,70vh)]">
{remoteProjectContext ? (
<div className="p-2 pb-0">
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
Repository
</div>
<div className="flex min-h-8 items-center gap-2 rounded-sm px-2 py-1.5">
{remoteProjectContext.icon}
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-foreground text-sm">
{remoteProjectContext.title}
</span>
<span className="truncate text-muted-foreground/85 text-xs">
{remoteProjectContext.description}
</span>
</span>
</div>
</div>
) : null}
<CommandPaletteResults
groups={displayedGroups}
highlightedItemValue={highlightedItemValue}
isActionsOnly={isActionsOnly}
keybindings={keybindings}
onExecuteItem={executeItem}
{...(addProjectCloneFlow?.step === "repository"
? {
emptyStateMessage:
addProjectCloneFlow.source === "url"
? "Enter a Git clone URL and press Enter to continue."
: "Enter a repository path and press Enter to look it up.",
}
: addProjectCloneFlow?.step === "confirm"
? { emptyStateMessage: "Choose a destination path and press Enter to clone." }
: relativePathNeedsActiveProject
? { emptyStateMessage: "Relative paths require an active project." }
: willCreateProjectPath
? {
emptyStateMessage:
"Press Enter to create this folder and add it as a project.",
}
: {})}
/>
</CommandPanel>
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
<div className="flex items-center gap-3">
<KbdGroup className="items-center gap-1.5">
<Kbd>
<ArrowUpIcon />
</Kbd>
<Kbd>
<ArrowDownIcon />
</Kbd>
<span>Navigate</span>
</KbdGroup>
{addProjectCloneFlow?.step === "repository" ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span>{remoteProjectButtonLabel ?? "Continue"}</span>
</KbdGroup>
) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span>Select</span>
</KbdGroup>
) : null}
{isSubmenu ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Backspace</Kbd>
<span>Back</span>
</KbdGroup>
) : null}
<KbdGroup className="items-center gap-1.5">
<Kbd>Esc</Kbd>
<span>Close</span>
</KbdGroup>
: isBrowsing
? { startAddon: <FolderPlusIcon /> }
: {}),
onKeyDown: handleKeyDown,
}}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
}}
onValueChange={handleQueryChange}
panelClassName="max-h-[min(28rem,70vh)]"
showBackHint={isSubmenu}
value={query}
>
{remoteProjectContext ? (
<div className="p-2 pb-0">
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Repository</div>
<div className="flex min-h-8 items-center gap-2 rounded-sm px-2 py-1.5">
{remoteProjectContext.icon}
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-foreground text-sm">{remoteProjectContext.title}</span>
<span className="truncate text-muted-foreground/85 text-xs">
{remoteProjectContext.description}
</span>
</span>
</div>
{canOpenProjectFromFileManager ? (
<Button
variant="ghost"
size="xs"
className="h-auto px-2 text-muted-foreground text-xs hover:bg-transparent hover:text-foreground"
disabled={isPickingProjectFolder}
onClick={() => {
void handleOpenProjectFromFileManager();
}}
>
{`Open in ${fileManagerName}`}
</Button>
) : null}
</CommandFooter>
</Command>
</CommandDialogPopup>
</div>
) : null}
<CommandPaletteResults
groups={displayedGroups}
highlightedItemValue={highlightedItemValue}
isActionsOnly={isActionsOnly}
keybindings={keybindings}
onExecuteItem={executeItem}
{...(addProjectCloneFlow?.step === "repository"
? {
emptyStateMessage:
addProjectCloneFlow.source === "url"
? "Enter a Git clone URL and press Enter to continue."
: "Enter a repository path and press Enter to look it up.",
}
: addProjectCloneFlow?.step === "confirm"
? { emptyStateMessage: "Choose a destination path and press Enter to clone." }
: relativePathNeedsActiveProject
? { emptyStateMessage: "Relative paths require an active project." }
: willCreateProjectPath
? {
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
}
: threadSearch.isPending
? { emptyStateMessage: "Searching thread messages…" }
: {})}
/>
</CommandPaletteContent>
);
}
@@ -0,0 +1,77 @@
import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
import type { ComponentProps, ReactNode } from "react";
import { Command, CommandFooter, CommandInput, CommandPanel } from "./ui/command";
import { Kbd, KbdGroup } from "./ui/kbd";
type CommandPaletteContentProps = Omit<ComponentProps<typeof Command>, "children"> & {
readonly children: ReactNode;
readonly escapeLabel?: ReactNode;
readonly footerActionLabel?: ReactNode;
readonly footerTrailing?: ReactNode;
readonly inputAccessory?: ReactNode;
readonly inputProps: ComponentProps<typeof CommandInput>;
readonly panelClassName?: string;
readonly showBackHint?: boolean;
readonly testId?: string;
};
/**
* Shared command palette chrome. Palette modes provide their query behavior,
* results, and optional input accessory while retaining one input, panel, and
* keyboard-hint gutter.
*/
export function CommandPaletteContent({
children,
escapeLabel = "Close",
footerActionLabel,
footerTrailing,
inputAccessory,
inputProps,
panelClassName,
showBackHint,
testId,
...commandProps
}: CommandPaletteContentProps) {
return (
<div className="contents" data-testid={testId}>
<Command {...commandProps}>
<div className="relative">
<CommandInput {...inputProps} />
{inputAccessory}
</div>
<CommandPanel className={panelClassName}>{children}</CommandPanel>
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
<div className="flex items-center gap-3">
<KbdGroup className="items-center gap-1.5">
<Kbd>
<ArrowUpIcon />
</Kbd>
<Kbd>
<ArrowDownIcon />
</Kbd>
<span>Navigate</span>
</KbdGroup>
{footerActionLabel !== undefined ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span>{footerActionLabel}</span>
</KbdGroup>
) : null}
{showBackHint ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Backspace</Kbd>
<span>Back</span>
</KbdGroup>
) : null}
<KbdGroup className="items-center gap-1.5">
<Kbd>Esc</Kbd>
<span>{escapeLabel}</span>
</KbdGroup>
</div>
{footerTrailing}
</CommandFooter>
</Command>
</div>
);
}
@@ -16,6 +16,69 @@ import {
} from "./ui/command";
import { cn } from "~/lib/utils";
function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
function HighlightedSearchText(props: { text: string; query: string }) {
const query = props.query.trim();
if (query.length === 0) return props.text;
const normalizedText = foldAsciiCase(props.text);
const normalizedQuery = foldAsciiCase(query);
const parts: Array<{
readonly text: string;
readonly highlighted: boolean;
readonly start: number;
}> = [];
let cursor = 0;
while (cursor < props.text.length) {
const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);
if (matchIndex === -1) {
parts.push({ text: props.text.slice(cursor), highlighted: false, start: cursor });
break;
}
if (matchIndex > cursor) {
parts.push({
text: props.text.slice(cursor, matchIndex),
highlighted: false,
start: cursor,
});
}
parts.push({
text: props.text.slice(matchIndex, matchIndex + query.length),
highlighted: true,
start: matchIndex,
});
cursor = matchIndex + query.length;
}
return parts.map((part) =>
part.highlighted ? (
<mark className="bg-transparent font-semibold text-foreground" key={part.start}>
{part.text}
</mark>
) : (
part.text
),
);
}
function ThreadContentMatch(props: {
match: NonNullable<CommandPaletteActionItem["threadContentMatch"]>;
}) {
const isUser = props.match.source === "user";
return (
<span className="truncate text-xs text-muted-foreground/85">
<span className={isUser ? "text-blue-400" : "text-emerald-400"}>
{isUser ? "You:" : "Agent:"}
</span>{" "}
<HighlightedSearchText text={props.match.snippet} query={props.match.query} />
</span>
);
}
interface CommandPaletteResultsProps {
emptyStateMessage?: string;
groups: ReadonlyArray<CommandPaletteGroup>;
@@ -69,15 +132,20 @@ function DisabledCommandPaletteResultRow(props: {
return (
<div className="flex min-h-8 select-none items-center gap-2 rounded-sm px-2 py-1.5 text-base opacity-64 sm:min-h-7 sm:text-sm">
{props.item.icon}
{props.item.description ? (
{props.item.description || props.item.threadContentMatch ? (
<span className="flex min-w-0 flex-1 flex-col">
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
<span className="truncate text-muted-foreground/85 text-xs">
{props.item.description}
</span>
{props.item.threadContentMatch ? (
<ThreadContentMatch match={props.item.threadContentMatch} />
) : null}
{props.item.description ? (
<span className="truncate text-muted-foreground/70 text-xs">
{props.item.description}
</span>
) : null}
</span>
) : (
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
@@ -115,15 +183,20 @@ function CommandPaletteResultRow(props: {
}}
>
{props.item.icon}
{props.item.description ? (
{props.item.description || props.item.threadContentMatch ? (
<span className="flex min-w-0 flex-1 flex-col">
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
<span className="truncate text-muted-foreground/85 text-xs">
{props.item.description}
</span>
{props.item.threadContentMatch ? (
<ThreadContentMatch match={props.item.threadContentMatch} />
) : null}
{props.item.description ? (
<span className="truncate text-muted-foreground/70 text-xs">
{props.item.description}
</span>
) : null}
</span>
) : (
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
@@ -0,0 +1,16 @@
import { Component, type ReactNode } from "react";
export class RenderErrorBoundary extends Component<
{ readonly children: ReactNode; readonly fallback: ReactNode },
{ readonly failed: boolean }
> {
override state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
override render() {
return this.state.failed ? this.props.fallback : this.props.children;
}
}
@@ -1,71 +1,15 @@
import type { Dispatch, ReactElement, SetStateAction } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { ReactElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
updateServer: vi.fn(),
toast: vi.fn(),
}));
const hooks = vi.hoisted(() => {
let cursor = 0;
let slots: unknown[] = [];
const nextIndex = () => cursor++;
return {
beginRender() {
cursor = 0;
},
reset() {
cursor = 0;
slots = [];
},
useEffect() {
nextIndex();
},
useMemoCache(size: number): unknown[] {
const index = nextIndex();
if (!slots[index]) {
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
}
return slots[index] as unknown[];
},
useRef<T>(initialValue: T): { current: T } {
const index = nextIndex();
if (!slots[index]) {
slots[index] = { current: initialValue };
}
return slots[index] as { current: T };
},
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
const index = nextIndex();
if (index >= slots.length) {
slots[index] =
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
}
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
const previous = slots[index] as T;
slots[index] =
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
};
return [slots[index] as T, setValue];
},
};
});
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
return {
...actual,
useEffect: hooks.useEffect,
useRef: hooks.useRef,
useState: hooks.useState,
};
});
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
vi.mock("~/hooks/useCopyToClipboard", () => ({
useCopyToClipboard: () => ({ copyToClipboard: vi.fn() }),
}));
@@ -79,120 +23,126 @@ vi.mock("./ui/toast", () => ({
toastManager: { add: testState.toast },
}));
import { ServerUpdateAction } from "./ServerUpdateAction";
import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction";
type ActionElement = ReactElement<{
readonly disabled?: boolean;
readonly onClick?: () => void;
}>;
function renderAction(): ActionElement {
hooks.beginRender();
return ServerUpdateAction({
environmentId: "env-test" as EnvironmentId,
serverLabel: "Test server",
selfUpdate: "boot-service",
targetVersion: "0.0.29",
targetVersion: "0.0.31",
}) as ActionElement;
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
async function flushPromises(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe("ServerUpdateAction", () => {
beforeEach(() => {
vi.useFakeTimers();
hooks.reset();
testState.updateServer.mockReset();
testState.toast.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("starts a fresh reconnect timeout after a long install succeeds", async () => {
const update =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValue(update.promise);
renderAction().props.onClick?.();
expect(renderAction().props.disabled).toBe(true);
await vi.advanceTimersByTimeAsync(11 * 60_000);
update.resolve(
AsyncResult.success({
targetVersion: "0.0.29",
method: "boot-service",
}),
);
await flushPromises();
// The click-based deadline would have fired by now. Success gets a fresh
// twelve-minute reconnect window, so the action remains disabled.
await vi.advanceTimersByTimeAsync(2 * 60_000);
expect(renderAction().props.disabled).toBe(true);
expect(testState.toast).not.toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update timed out" }),
it("reports success only after the shared update flow reconnects", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(renderAction().props.disabled).not.toBe(true);
expect(testState.toast).toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update timed out" }),
renderAction().props.onClick?.();
await flushPromises();
expect(testState.updateServer).toHaveBeenCalledWith({
environmentId: "env-test",
input: { targetVersion: "0.0.31" },
});
expect(testState.toast).toHaveBeenCalledWith({
type: "success",
title: "Test server updated",
description: "Reconnected on [email protected].",
});
});
it("reports one result when the update action is double-clicked", async () => {
let finishUpdate: (() => void) | undefined;
testState.updateServer.mockImplementation(
() =>
new Promise((resolve) => {
finishUpdate = () =>
resolve(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
}),
);
const action = renderAction();
action.props.onClick?.();
action.props.onClick?.();
expect(testState.updateServer).toHaveBeenCalledTimes(1);
finishUpdate?.();
await flushPromises();
expect(testState.toast).toHaveBeenCalledTimes(1);
});
it("does not let an expired request clear a newer retry", async () => {
const first = deferred<ReturnType<typeof AsyncResult.failure>>();
const retry =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValueOnce(first.promise).mockReturnValueOnce(retry.promise);
renderAction().props.onClick?.();
await vi.advanceTimersByTimeAsync(12 * 60_000);
expect(renderAction().props.disabled).not.toBe(true);
renderAction().props.onClick?.();
expect(renderAction().props.disabled).toBe(true);
first.resolve(AsyncResult.failure(Cause.fail(new Error("first request failed late"))));
await flushPromises();
expect(renderAction().props.disabled).toBe(true);
expect(testState.updateServer).toHaveBeenCalledTimes(2);
retry.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
await flushPromises();
expect(renderAction().props.disabled).toBe(true);
});
it("quietly releases the action when a restart RPC is interrupted", async () => {
it("quietly releases the action when the operation is interrupted", async () => {
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
renderAction().props.onClick?.();
await flushPromises();
expect(renderAction().props.disabled).not.toBe(true);
expect(testState.toast).not.toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update failed" }),
);
expect(testState.toast).not.toHaveBeenCalled();
});
});
describe("ServerUpdateProgress", () => {
it("renders the monochrome step rail with only the active step highlighted", () => {
const markup = renderToStaticMarkup(
<ServerUpdateProgress
fromVersion="0.0.30"
state={{
status: "running",
stage: "resuming",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
}}
/>,
);
expect(markup).toContain("0.0.30");
expect(markup).toContain("0.0.31");
expect(markup).toContain("Download");
expect(markup).toContain("Install");
expect(markup).toContain("Resuming");
// The wait state is monochrome and calm: no success/warning colors, no
// status sentence, one duty-cycled pulse on the active step.
expect(markup).not.toContain("text-success");
expect(markup).not.toContain("text-primary");
expect(markup).toContain("animate-status-pulse");
expect(markup).not.toContain("animate-spin");
});
it("keeps the failed stage visible with its retryable error", () => {
const markup = renderToStaticMarkup(
<ServerUpdateProgress
fromVersion="0.0.30"
state={{
status: "failed",
stage: "installing",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
message: "The package could not be verified.",
}}
/>,
);
expect(markup).toContain('role="alert"');
expect(markup).toContain("The package could not be verified.");
expect(markup).not.toContain("animate-status-pulse");
});
});
+120 -117
View File
@@ -1,55 +1,135 @@
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { CheckIcon } from "lucide-react";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { cn } from "~/lib/utils";
import { serverEnvironment } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
import { Button } from "./ui/button";
import { Spinner } from "./ui/spinner";
import { toastManager } from "./ui/toast";
/**
* The npm install on the server side is capped at 10 minutes; expire the
* spinner a bit beyond that so a dead transport never strands a disabled
* button, while a legitimately slow install is never cut off.
*/
const UPDATE_PENDING_EXPIRY_MS = 12 * 60_000;
const UPDATE_STEPS = [
{ stage: "downloading", label: "Download", activeLabel: "Downloading" },
{ stage: "installing", label: "Install", activeLabel: "Installing" },
{ stage: "resuming", label: "Resume", activeLabel: "Resuming" },
] as const;
const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
/**
* The call-to-action for a version-skewed server, matched to the update path
* it advertises: a one-click install-and-restart for servers that can update
* themselves, an update-the-desktop-app hint for desktop-managed backends
* (running `npx t3` there would start a second server, not update this one),
* and copying the manual relaunch command for everything else — so the skew
* warning always offers a way out.
* Monochrome step rail for an in-flight server update. The update is a
* wait, not a warning: done steps recede to gray, the active step is the
* only bright element and pulses. Failure keeps the rail but surfaces the
* error below it.
*/
export function ServerUpdateProgress({
fromVersion,
state,
}: {
readonly fromVersion: string;
readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
}) {
const currentIndex = UPDATE_STEPS.findIndex(({ stage }) => stage === state.stage);
return (
<div className="mt-1 min-w-0 space-y-2.5">
<p className="text-xs text-muted-foreground/70">
{fromVersion} <span aria-hidden="true">→</span> {state.targetVersion}
</p>
<ol className="flex min-w-0 items-center" aria-label="Server update progress">
{UPDATE_STEPS.map((step, index) => {
const complete = index < currentIndex;
const current = index === currentIndex;
const failed = current && state.status === "failed";
const running = current && state.status === "running";
return (
<li
key={step.stage}
className={cn(
"flex min-w-0 items-center text-xs font-medium",
index < UPDATE_STEPS.length - 1 ? "flex-1" : null,
complete
? "text-muted-foreground"
: failed
? "text-destructive"
: running
? "animate-status-pulse text-foreground"
: "text-muted-foreground/50",
)}
aria-current={running ? "step" : undefined}
>
{complete ? (
<CheckIcon
className="size-3.5 shrink-0 opacity-70"
strokeWidth={2.5}
aria-hidden="true"
/>
) : (
<span
className={cn(
"size-1.5 shrink-0 rounded-full",
failed
? "bg-destructive"
: running
? "bg-foreground"
: "border border-muted-foreground/40",
)}
aria-hidden="true"
/>
)}
<span className="ml-1.5 truncate">{running ? step.activeLabel : step.label}</span>
{index < UPDATE_STEPS.length - 1 ? (
<span
className={cn(
"mx-2 h-px min-w-3 flex-1",
complete ? "bg-muted-foreground/40" : "bg-border",
)}
aria-hidden="true"
/>
) : null}
</li>
);
})}
</ol>
{state.status === "failed" ? (
<p className="text-xs text-destructive" role="alert">
{state.message}
</p>
) : null}
</div>
);
}
/**
* Offers the update path advertised by a version-skewed server. Self-updates
* delegate their full lifecycle to client-runtime so this component can
* unmount during reconnect without losing operation state.
*/
export function ServerUpdateAction({
environmentId,
serverLabel,
selfUpdate,
targetVersion,
label = "Update server",
}: {
readonly environmentId: EnvironmentId;
readonly serverLabel: string;
readonly selfUpdate: ServerSelfUpdateCapability | null;
readonly targetVersion: string;
readonly label?: string;
}) {
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
reportFailure: false,
});
const [pending, setPending] = useState(false);
const inFlightRef = useRef(false);
const attemptRef = useRef(0);
const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
target: "update command",
onCopy: ({ command }) => {
@@ -68,107 +148,35 @@ export function ServerUpdateAction({
},
});
useEffect(
() => () => {
if (expiryRef.current !== null) {
clearTimeout(expiryRef.current);
expiryRef.current = null;
}
attemptRef.current += 1;
inFlightRef.current = false;
},
[],
);
const handleUpdate = () => {
// Synchronous re-entry guard: setPending is async, so a rapid
// double-click would otherwise dispatch two updates.
if (inFlightRef.current) {
const handleUpdate = async () => {
if (pendingUpdateEnvironmentIds.has(environmentId)) {
return;
}
inFlightRef.current = true;
const attempt = attemptRef.current + 1;
attemptRef.current = attempt;
const ownsAttempt = () => attemptRef.current === attempt;
setPending(true);
const armExpiry = () => {
const expiry = setTimeout(() => {
if (!ownsAttempt()) return;
expiryRef.current = null;
attemptRef.current += 1;
inFlightRef.current = false;
setPending(false);
toastManager.add({
type: "error",
title: "Server update timed out",
description: "The update may still be running on the server — check again in a minute.",
});
}, UPDATE_PENDING_EXPIRY_MS);
expiryRef.current = expiry;
return expiry;
};
let expiry = armExpiry();
let restartAccepted = false;
const keepPendingForRestart = () => {
restartAccepted = true;
if (expiryRef.current === expiry) {
clearTimeout(expiry);
expiry = armExpiry();
}
};
void Promise.resolve()
.then(() =>
updateServer({
environmentId,
input: { targetVersion },
}),
)
.then((result) => {
if (!ownsAttempt()) return;
if (result._tag === "Failure") {
// An interrupt may be the expected boot-service disconnect, but it
// can also be client-side cancellation before restart was accepted.
// Release the action quietly; version sync will remove it when a
// successful replacement reconnects.
if (isAtomCommandInterrupted(result)) {
return;
}
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(squashAtomCommandFailure(result)),
});
pendingUpdateEnvironmentIds.add(environmentId);
try {
const result = await updateServer({
environmentId,
input: { targetVersion },
});
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
keepPendingForRestart();
// Installation can legitimately consume most of the request window.
// Give restart/reconnect a fresh full window after the server accepts
// the handoff instead of expiring based on the original click time.
toastManager.add({
type: "success",
title: `Updating ${serverLabel}`,
description: `t3@${result.value.targetVersion} is installed — the server is restarting and will reconnect shortly.`,
});
})
.catch((error: unknown) => {
if (!ownsAttempt()) return;
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(error),
description: updateFailureMessage(squashAtomCommandFailure(result)),
});
})
.finally(() => {
// A successful RPC only acknowledges that restart is scheduled. Keep
// the action disabled until version sync unmounts it, or until the
// safety expiry reports that reconnection never arrived.
if (restartAccepted || !ownsAttempt() || expiryRef.current !== expiry) return;
expiryRef.current = null;
clearTimeout(expiry);
attemptRef.current += 1;
inFlightRef.current = false;
setPending(false);
return;
}
toastManager.add({
type: "success",
title: `${serverLabel} updated`,
description: `Reconnected on t3@${result.value.targetVersion}.`,
});
} finally {
pendingUpdateEnvironmentIds.delete(environmentId);
}
};
if (selfUpdate === "desktop-managed") {
@@ -188,14 +196,9 @@ export function ServerUpdateAction({
);
}
return pending ? (
<Button size="xs" disabled>
<Spinner className="size-3.5" />
Updating...
</Button>
) : (
return (
<Button size="xs" onClick={() => void handleUpdate()}>
Update server
{label}
</Button>
);
}
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
archiveSelectedThreadEntries,
buildBulkTitleRegenerationContextMenuItem,
buildMultiSelectThreadContextMenuItems,
createThreadJumpHintVisibilityController,
filterSidebarV2VisibleThreads,
@@ -148,6 +149,42 @@ describe("archiveSelectedThreadEntries", () => {
});
});
describe("buildBulkTitleRegenerationContextMenuItem", () => {
it("counts only threads that can start a new regeneration", () => {
expect(
buildBulkTitleRegenerationContextMenuItem({
supportedCount: 4,
actionableCount: 3,
}),
).toEqual({
id: "regenerate-title",
label: "Regenerate titles (3)",
});
});
it("shows a disabled progress item when every supported thread is pending", () => {
expect(
buildBulkTitleRegenerationContextMenuItem({
supportedCount: 2,
actionableCount: 0,
}),
).toEqual({
id: "regenerate-title",
label: "Regenerating… (2)",
disabled: true,
});
});
it("omits the action when no selected environment supports it", () => {
expect(
buildBulkTitleRegenerationContextMenuItem({
supportedCount: 0,
actionableCount: 0,
}),
).toBeNull();
});
});
describe("buildMultiSelectThreadContextMenuItems", () => {
it("offers bulk archive with the selected count", () => {
expect(
+19
View File
@@ -18,6 +18,7 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
type SidebarProject = {
id: string;
title: string;
@@ -122,6 +123,24 @@ export function getSidebarForkParentThreadId(
: thread.lineage.parentThreadId;
}
export function buildBulkTitleRegenerationContextMenuItem(input: {
supportedCount: number;
actionableCount: number;
}): ContextMenuItem<"regenerate-title"> | null {
if (input.supportedCount === 0) return null;
if (input.actionableCount === 0) {
return {
id: "regenerate-title",
label: `Regenerating… (${input.supportedCount})`,
disabled: true,
};
}
return {
id: "regenerate-title",
label: `Regenerate titles (${input.actionableCount})`,
};
}
export interface ThreadStatusPill {
label:
| "Working"
+187 -10
View File
@@ -32,6 +32,7 @@ import {
SearchIcon,
ServerIcon,
SquarePenIcon,
TerminalIcon,
Trash2Icon,
Undo2Icon,
} from "lucide-react";
@@ -105,6 +106,7 @@ import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat"
import type { SidebarThreadSummary } from "../types";
import { cn } from "~/lib/utils";
import {
buildBulkTitleRegenerationContextMenuItem,
formatWorkingDurationLabel,
filterSidebarV2VisibleThreads,
firstValidTimestampMs,
@@ -126,6 +128,8 @@ import {
prStatusIndicator,
resolveThreadPr,
settledPrHoverColorClass,
terminalStatusFromRunningIds,
type TerminalStatusIndicator,
} from "./ThreadStatusIndicators";
import {
resolveSnoozePresets,
@@ -138,6 +142,7 @@ import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";
import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils";
import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances";
import { primaryServerProvidersAtom } from "../state/server";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { CommandDialogTrigger } from "./ui/command";
import { Button } from "./ui/button";
@@ -222,6 +227,10 @@ function WorkingDuration(props: { startedAt: string | null }) {
);
}
function terminalProcessLabel(count: number): string {
return `${count} terminal ${count === 1 ? "process" : "processes"} running`;
}
function SidebarV2ThreadTooltip({
thread,
projectTitle,
@@ -231,6 +240,8 @@ function SidebarV2ThreadTooltip({
modelInstanceId,
modelLabel,
branchMismatch,
terminalStatus,
terminalProcessCount,
}: {
thread: SidebarThreadSummary;
projectTitle: string | null;
@@ -243,6 +254,8 @@ function SidebarV2ThreadTooltip({
threadBranch: string;
currentBranch: string;
} | null;
terminalStatus: TerminalStatusIndicator | null;
terminalProcessCount: number;
}) {
return (
<TooltipPopup
@@ -297,6 +310,17 @@ function SidebarV2ThreadTooltip({
<div className="min-w-0 truncate text-foreground/75">{modelLabel}</div>
</div>
) : null}
{terminalStatus ? (
<div className="flex min-w-0 items-center gap-2">
<TerminalIcon
aria-hidden
className={cn("size-3 shrink-0", terminalStatus.colorClass)}
/>
<div className="min-w-0 truncate text-foreground/75">
{terminalProcessLabel(terminalProcessCount)}
</div>
</div>
) : null}
{thread.runtime?.lastError ? (
<div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400">
<CircleAlertIcon className="size-3 shrink-0 stroke-current" />
@@ -423,10 +447,17 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
[thread.environmentId, thread.id],
);
const threadKey = scopedThreadKey(threadRef);
const isRegeneratingTitle = thread.titleRegeneration != null;
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: thread.environmentId,
threadId: thread.id,
});
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const terminalProcessCount = runningTerminalIds.length;
// Same semantics as v1 (never-visited counts as read): flipping the beta
// flag must not light up every historical thread as unread.
@@ -545,6 +576,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
modelInstanceId={modelInstanceId}
modelLabel={modelLabel}
branchMismatch={branchMismatch}
terminalStatus={terminalStatus}
terminalProcessCount={terminalProcessCount}
/>
);
@@ -693,7 +726,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : (
<span
className={cn(
"min-w-0 flex-1 text-sm",
"min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none",
shouldRecede ? "font-normal" : "font-medium",
variant === "card"
? cn(
@@ -714,6 +747,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
? "text-muted-foreground"
: "text-muted-foreground/70",
),
isRegeneratingTitle && "opacity-[0.55]",
)}
>
{thread.title}
@@ -738,6 +772,16 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
#{pr.number}
</button>
) : null;
const terminalStatusIcon = terminalStatus ? (
<span
role="img"
aria-label={terminalProcessLabel(terminalProcessCount)}
data-testid={`sidebar-v2-terminal-status-${thread.id}`}
className={cn("inline-flex shrink-0 items-center justify-center", terminalStatus.colorClass)}
>
<TerminalIcon className={cn("size-3.5", terminalStatus.pulse && "animate-status-pulse")} />
</span>
) : null;
if (variant === "slim") {
return (
@@ -752,6 +796,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
role="button"
tabIndex={0}
data-testid="sidebar-v2-row-slim"
aria-busy={isRegeneratingTitle || undefined}
className={cn(rowSurfaceClassName, "flex h-9 items-center gap-2.5 px-2.5")}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
@@ -777,6 +822,12 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
/>
</span>
{title}
{terminalStatusIcon}
{isRegeneratingTitle ? (
<span role="status" className="sr-only">
Regenerating title
</span>
) : null}
{/* The PR badge stays outside the hover-fading slot: it must
remain visible AND clickable while the row is hovered. Only
the time/jump label yields to the settle affordance. */}
@@ -861,6 +912,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
role="button"
tabIndex={0}
data-testid="sidebar-v2-row-card"
aria-busy={isRegeneratingTitle || undefined}
className={rowSurfaceClassName}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
@@ -893,9 +945,12 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
the hidden state out of flow lets the project label reclaim
space without either state overlapping it. */}
<span className="group/v2-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs">
{/* pointer-events-none: while hovered this label is absolute
+ opacity-0, which paints it ABOVE the in-flow settle/snooze
buttons; without it the invisible label eats their clicks. */}
<span
className={cn(
"self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity group-focus-within/v2-status-slot:absolute group-focus-within/v2-status-slot:right-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
"pointer-events-none self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity group-focus-within/v2-status-slot:absolute group-focus-within/v2-status-slot:right-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
snoozeMenuOpen && "absolute right-0 opacity-0",
)}
>
@@ -956,13 +1011,21 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : null}
</span>
</div>
<div className="mt-1 flex min-w-0">{title}</div>
<div className="mt-1 flex min-w-0">
{title}
{isRegeneratingTitle ? (
<span role="status" className="sr-only">
Regenerating title
</span>
) : null}
</div>
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground/75">
{thread.branch ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
) : (
<span className="flex-1" />
)}
{terminalStatusIcon}
{prBadge}
{diff ? (
<span className="shrink-0 font-mono">
@@ -1032,7 +1095,7 @@ export default function SidebarV2() {
reportFailure: false,
});
const updateSettings = useUpdateClientSettings();
const { copyToClipboard: copyProjectPath } = useCopyToClipboard<{ path: string }>({
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
onCopy: ({ path }) => {
toastManager.add({
type: "success",
@@ -1050,6 +1113,25 @@ export default function SidebarV2() {
);
},
});
const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
target: "branch name",
onCopy: ({ branch }) => {
toastManager.add({
type: "success",
title: "Branch copied",
description: branch,
});
},
onError: (error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to copy branch",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
},
});
const [projectActionsTarget, setProjectActionsTarget] = useState<SidebarProjectSnapshot | null>(
null,
);
@@ -1845,16 +1927,28 @@ export default function SidebarV2() {
const count = threadKeys.length;
// Snooze (N) is offered when every selected thread can actually take
// it — a mixed selection with blocked-on-you work would half-apply.
const selectionNow = new Date().toISOString();
const snoozableThreads = threadKeys.flatMap((threadKey) => {
const selectionNow = new Date();
const selectedThreads = threadKeys.flatMap((threadKey) => {
const thread = threadByKeyRef.current.get(threadKey);
return thread ? [thread] : [];
});
const canSnoozeSelection = snoozableThreads.every(
const canSnoozeSelection = selectedThreads.every(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true &&
canSnooze(thread, { now: selectionNow }),
canSnooze(thread, { now: selectionNow.toISOString() }),
);
const titleRegenerationThreads = selectedThreads.filter(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadTitleRegeneration === true,
);
const regeneratableTitleThreads = titleRegenerationThreads.filter(
(thread) => thread.titleRegeneration == null,
);
const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({
supportedCount: titleRegenerationThreads.length,
actionableCount: regeneratableTitleThreads.length,
});
const snoozePresets = resolveSnoozePresets(new Date());
const clicked = await settlePromise(() =>
api.contextMenu.show(
@@ -1872,6 +1966,7 @@ export default function SidebarV2() {
},
]
: []),
...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []),
{ id: "mark-unread", label: `Mark unread (${count})` },
{ id: "delete", label: `Delete (${count})`, destructive: true },
],
@@ -1887,7 +1982,7 @@ export default function SidebarV2() {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
const coSnoozingKeys = new Set(threadKeys);
for (const thread of snoozableThreads) {
for (const thread of selectedThreads) {
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
coSnoozingKeys,
});
@@ -1896,6 +1991,28 @@ export default function SidebarV2() {
}
return;
}
if (clicked.value === "regenerate-title") {
for (const thread of regeneratableTitleThreads) {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Success") continue;
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to regenerate thread titles",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
clearSelection();
return;
}
if (clicked.value === "settle") {
// Post-settle navigation must skip threads settling in this same
// batch — they are all leaving the card block together. Rows that
@@ -1968,6 +2085,7 @@ export default function SidebarV2() {
markThreadUnread,
removeFromSelection,
serverConfigs,
updateThreadMetadata,
],
);
@@ -1984,6 +2102,10 @@ export default function SidebarV2() {
}
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) return;
const threadWorkspacePath =
thread.worktreePath ??
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ??
null;
// Un-settle works on every settled row: for explicit settles it
// clears the override, for auto-settled rows it pins the thread
// active until real activity clears the pin. Environments without
@@ -1993,6 +2115,10 @@ export default function SidebarV2() {
true;
const supportsSnooze =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const supportsTitleRegeneration =
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadTitleRegeneration === true;
const isRegeneratingTitle = thread.titleRegeneration != null;
const isSettled = settledThreadKeysRef.current.has(threadKey);
const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
// Presets resolve at menu-open time (same as the popover).
@@ -2031,7 +2157,18 @@ export default function SidebarV2() {
]
: []),
{ id: "rename", label: "Rename thread" },
...(supportsTitleRegeneration
? [
{
id: "regenerate-title",
label: isRegeneratingTitle ? "Regenerating…" : "Regenerate title",
disabled: isRegeneratingTitle,
},
]
: []),
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy path", icon: "copy" },
...(thread.branch ? [{ id: "copy-branch", label: "Copy branch", icon: "copy" }] : []),
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
],
position,
@@ -2081,9 +2218,45 @@ export default function SidebarV2() {
case "rename":
startThreadRename(threadRef, thread.title);
return;
case "regenerate-title": {
if (isRegeneratingTitle) return;
const result = await updateThreadMetadata({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, regenerateTitle: true },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to regenerate thread title",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
case "mark-unread":
markThreadUnread(threadRef);
return;
case "copy-path":
if (!threadWorkspacePath) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Path unavailable",
description: "This thread does not have a workspace path to copy.",
}),
);
return;
}
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
return;
case "copy-branch":
if (thread.branch) {
copyBranchToClipboard(thread.branch, { branch: thread.branch });
}
return;
case "delete": {
if (confirmThreadDelete) {
const confirmed = await settlePromise(() =>
@@ -2121,11 +2294,15 @@ export default function SidebarV2() {
attemptUnsettle,
attemptUnsnooze,
confirmThreadDelete,
copyBranchToClipboard,
copyPathToClipboard,
deleteThread,
handleMultiSelectContextMenu,
markThreadUnread,
projectCwdByKey,
serverConfigs,
startThreadRename,
updateThreadMetadata,
],
);
@@ -2599,7 +2776,7 @@ export default function SidebarV2() {
aria-label="Copy project path"
title="Copy project path"
onClick={() =>
copyProjectPath(member.workspaceRoot, { path: member.workspaceRoot })
copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot })
}
>
<CopyIcon className="size-3.5" />
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more