Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e2309c1afc fix(terminal): address ghostty refresh review
Co-authored-by: codex <[email protected]>
2026-07-20 18:16:32 +02:00
Pixel Perfect 2bc4029e81 Keep scroll anchor stable at the scrollback cap and fix config order
- Once scrollback is full its length stops growing while writes keep
  evicting lines, so the preserved viewport drifted toward the tail;
  fall back to counting written newlines at the cap
- Parse config.ghostty before config so config wins conflicts, matching
  Ghostty's own load order
2026-07-20 18:05:01 +02:00
Pixel Perfect 4f4a2ede59 Address second-round review findings
- Preserve a scrolled-back viewport when session output arrives:
  ghostty-web snaps to the bottom on every write, so re-anchor the
  viewport by the number of lines the write pushed into scrollback
- Read both config and config.ghostty when they coexist in a Ghostty
  config directory instead of letting the first shadow the second
- Linkify mailto/ftp/ssh/git/tel/magnet/gemini/gopher/news URLs in the
  terminal and open non-http schemes with the OS handler, keeping the
  in-app preview flow for http(s)
2026-07-20 18:05:01 +02:00
Pixel Perfect 36d1cc6578 Re-run session sync after WASM init and merge Ghostty config files
- Bump a terminal epoch when the deferred WASM setup finishes so the
  session sync effect re-runs against the live terminal even when no
  session field changed during the load, completing the exited-at-mount
  handling
- Read config.ghostty as an alternate config file name and merge the
  XDG and macOS Application Support configs in Ghostty's load order
  instead of stopping at the first existing file
2026-07-20 18:05:01 +02:00
Pixel Perfect c1caaa3520 Handle init failure surfacing and empty XDG_CONFIG_HOME
- Attach a rejection handler to the terminal WASM init so a load
  failure logs, shows a message in the viewport, and clears on retry
  instead of leaving a blank pane and an unhandled rejection
- Treat an empty XDG_CONFIG_HOME as unset per the XDG spec instead of
  resolving the Ghostty config relative to the server cwd
2026-07-20 18:05:01 +02:00
Pixel Perfect 7266fafbf6 Address review findings on the ghostty-web terminal
- Retry WASM init on a later mount instead of caching a rejected
  promise until page reload
- Blur non-active terminals after open(): ghostty-web focuses
  unconditionally, letting the last-mounted split steal focus
- Seed the session snapshot with version 0 and a closed status at mount
  so an already-exited session still surfaces its exit and closes the
  viewport
- Keep CSS generic font keywords (monospace, system-ui, ...) unquoted
  when building the terminal font stack
- Resolve named Ghostty themes from the Linux system dirs
  (/usr/share/ghostty/themes, /usr/local/share/ghostty/themes) too
2026-07-20 18:05:01 +02:00
Pixel Perfect a6ff5725cc Allow WebAssembly in the desktop renderer CSP
The desktop protocol's Content-Security-Policy blocked the ghostty-web
terminal from initializing: script-src had no 'wasm-unsafe-eval', so
WebAssembly compilation was rejected, and connect-src had no data:, so
the library's embedded WASM payload fetch failed. Add both sources.
2026-07-20 18:05:01 +02:00
Pixel Perfect 87998f7c2a Replace xterm.js with ghostty-web in the web terminal
Swap the thread terminal drawer from @xterm/xterm to ghostty-web, the
libghostty-vt based drop-in. The server terminal protocol is unchanged;
the swap is contained to the client renderer:

- Gate terminal creation on the ghostty-web WASM init and replay the
  session buffer that arrives before it resolves
- Invert custom key handler returns (ghostty-web treats true as
  "consumed", the opposite of xterm.js)
- Convert link provider rows/ranges between the 1-based terminal-links
  helpers and ghostty-web's 0-based coordinates, and drop the built-in
  providers whose activate() bypasses the app's preview flow
- Guard zero-length writes: ghostty-web 0.4.0 alloc(0) returns an
  out-of-bounds pointer and crashes on status-only session updates
- Adapt at-bottom checks to ghostty-web's inverted viewportY semantics

Also style the terminal from the user's local Ghostty config when one
exists: the server parses font-family/font-size/theme (resolving named
themes from the user themes dir or the Ghostty.app bundle) into an
optional ServerConfig.terminalStyle field, and the drawer applies it
over the app-derived defaults. Nerd Font fallbacks cover powerline and
devicon glyphs, and the mount is painted with the theme background so
partial-cell fringes match the canvas.
2026-07-20 18:05:01 +02:00
44 changed files with 1142 additions and 1900 deletions

No files matched your search

@@ -57,11 +57,11 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
"connect-src 'self' http: https: ws: wss:",
"connect-src 'self' data: http: https: ws: wss:",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,10 +212,18 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);
assert.deepEqual(directives["connect-src"], [
"'self'",
"data:",
"http:",
"https:",
"ws:",
"wss:",
]);
assert.deepEqual(directives["img-src"], [
"'self'",
"t3code:",
@@ -71,6 +71,8 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
// Required to compile the ghostty-web terminal's WebAssembly module.
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -79,7 +81,8 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
// the build-configured Clerk, relay, and OTLP endpoints. Those environment
// origins are not known when this response policy is created, so restrict
// connections by the network schemes the client supports instead of by host.
const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
// data: allows ghostty-web to fetch its embedded WebAssembly payload.
const connectSources = ["'self'", "data:", "http:", "https:", "ws:", "wss:"];
return [
"default-src 'self'",
@@ -65,9 +65,6 @@ export interface ThreadDetailScreenProps {
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
readonly activeThreadBusy: boolean;
readonly hasMoreOlderActivities: boolean;
readonly loadingOlderActivities: boolean;
readonly onLoadOlderActivities: () => void;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -425,9 +422,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
hasMoreOlder={props.hasMoreOlderActivities}
loadingOlder={props.loadingOlderActivities}
onLoadOlder={props.onLoadOlderActivities}
/>
</View>
) : (
@@ -139,10 +139,6 @@ export interface ThreadFeedProps {
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Older history beyond the live activity window can be lazy-loaded on scroll-up. */
readonly hasMoreOlder?: boolean;
readonly loadingOlder?: boolean;
readonly onLoadOlder?: () => void;
}
function MessageAttachmentImage(props: {
@@ -1463,15 +1459,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
? props.latestTurn.turnId
: null;
// Reaching the top (oldest) lazy-loads older history. The hook keys an
// in-flight guard by thread, so repeated fires during scroll coalesce.
const { hasMoreOlder, loadingOlder, onLoadOlder } = props;
const onStartReachedOlderHistory = useCallback(() => {
if (hasMoreOlder && !loadingOlder) {
onLoadOlder?.();
}
}, [hasMoreOlder, loadingOlder, onLoadOlder]);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = props.latestTurn;
@@ -1764,15 +1751,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
estimatedItemSize={180}
initialScrollAtEnd
onScroll={handleScroll}
onStartReached={onStartReachedOlderHistory}
onStartReachedThreshold={0.5}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets && !loadingOlder ? null : (
<View style={{ height: usesNativeAutomaticInsets ? undefined : topContentInset }}>
{loadingOlder ? <ActivityIndicator style={{ marginTop: 8 }} /> : null}
</View>
)
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
}
contentContainerStyle={{
paddingTop: 12,
@@ -1780,24 +1761,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}}
/>
</View>
{props.feed.length === 0 && hasMoreOlder ? (
// The window can derive zero visible entries while older history
// exists — without scrollable content `onStartReached` can never
// fire, so give the user an explicit affordance instead of the
// empty-state placeholder.
<View style={StyleSheet.absoluteFill}>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
{loadingOlder ? (
<ActivityIndicator />
) : (
<TouchableOpacity accessibilityRole="button" onPress={() => onLoadOlder?.()}>
<Text className="text-sm text-muted-foreground">Load older history</Text>
</TouchableOpacity>
)}
</View>
</View>
) : null}
{props.feed.length === 0 && !hasMoreOlder && props.contentPresentation.kind === "ready" ? (
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
<ThreadFeedPlaceholder
title="No conversation yet"
@@ -194,9 +194,7 @@ function ThreadRouteContent(
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
// Derive pending requests from the FULL loaded set (older pages + live
// window) so a prompt the user scrolled back to load still surfaces.
const requests = useSelectedThreadRequests(composer.mergedActivities);
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const navigation = useNavigation();
const params = props.route.params;
@@ -769,9 +767,6 @@ function ThreadRouteContent(
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
activeThreadBusy={composer.activeThreadBusy}
hasMoreOlderActivities={composer.hasMoreOlderActivities}
loadingOlderActivities={composer.loadingOlderActivities}
onLoadOlderActivities={composer.onLoadOlderActivities}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
@@ -1,11 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import {
ApprovalRequestId,
type OrchestrationThreadActivity,
type ProviderApprovalDecision,
} from "@t3tools/contracts";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -57,18 +53,7 @@ function setUserInputDraftCustomAnswer(
});
}
/**
* Pending approval / user-input requests for the selected thread.
*
* `activities` should be the FULL loaded set (lazy-loaded older pages + the
* windowed live view, i.e. `useThreadComposerState().mergedActivities`): the
* detail snapshot windows activities to the most recent page, so deriving from
* `selectedThread.activities` alone would hide a prompt the user scrolled back
* to load. Falls back to the live window when not provided. Deriving from the
* merged set is sound — resolutions are always newer than their requests, so a
* loaded request whose resolution exists always has that resolution loaded too.
*/
export function useSelectedThreadRequests(activities?: ReadonlyArray<OrchestrationThreadActivity>) {
export function useSelectedThreadRequests() {
const respondToApproval = useAtomCommand(
threadEnvironment.respondToApproval,
"thread approval response",
@@ -85,20 +70,16 @@ export function useSelectedThreadRequests(activities?: ReadonlyArray<Orchestrati
null,
);
const requestActivities = activities ?? selectedThread?.activities ?? null;
const activePendingApprovals = useMemo(
() => (requestActivities ? derivePendingApprovals(requestActivities) : []),
[requestActivities],
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
[selectedThread],
);
// The derivations sort ascending by createdAt; surface the NEWEST open
// request. With lazy-loaded older pages in the set, index 0 could be an
// ancient dangling request hijacking the prompt for the current one.
const activePendingApproval = activePendingApprovals.at(-1) ?? null;
const activePendingApproval = activePendingApprovals[0] ?? null;
const activePendingUserInputs = useMemo(
() => (requestActivities ? derivePendingUserInputs(requestActivities) : []),
[requestActivities],
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
[selectedThread],
);
const activePendingUserInput = activePendingUserInputs.at(-1) ?? null;
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
? (userInputDraftsByRequestKey[
@@ -6,17 +6,11 @@ import {
MessageId,
type EnvironmentId,
type ModelSelection,
type OrchestrationThreadActivity,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import {
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
@@ -42,15 +36,11 @@ import {
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
import { orchestrationEnvironment } from "../state/orchestration";
import { useSelectedThreadDetail } from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
export function appendReviewCommentToDraft(input: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
@@ -99,56 +89,9 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
// ── Older-history lazy-load (shared engine; see useOlderThreadActivities) ──
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities`); older pages are fetched on demand and prepended.
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const selectedEnvironmentIdForActivities = selectedThreadShell?.environmentId ?? null;
const selectedThreadIdForActivities = selectedThreadShell?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (selectedEnvironmentIdForActivities === null || selectedThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: selectedEnvironmentIdForActivities,
input: { threadId: selectedThreadIdForActivities, ...cursor },
});
if (result._tag !== "Success") {
// Surface real failures (a spinner that quietly gives up reads as
// missing history); keep `hasMore` so scrolling back retries.
if (!isAtomCommandInterrupted(result)) {
setPendingConnectionError("Could not load older thread history.");
}
return null;
}
return result.value;
},
[selectedEnvironmentIdForActivities, selectedThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities,
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: onLoadOlderActivities,
} = useOlderThreadActivities({
threadKey: selectedThreadShell
? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}`
: null,
liveActivities: selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: selectedThreadDetail?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const selectedThreadFeed = useMemo(
() =>
selectedThreadDetail
? buildThreadFeed({ ...selectedThreadDetail, activities: mergedActivities })
: [],
[selectedThreadDetail, mergedActivities],
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
@@ -356,13 +299,6 @@ export function useThreadComposerState() {
runtimeMode,
interactionMode,
activeThreadBusy,
// Lazy-loaded older pages + the live window — the full loaded activity set.
// Request derivations must run over this (not the windowed live set alone)
// so prompts pulled in by scroll-up still surface, matching web.
mergedActivities,
hasMoreOlderActivities,
loadingOlderActivities,
onLoadOlderActivities,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,
@@ -77,8 +77,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -187,8 +185,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -272,8 +268,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -342,8 +336,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -397,8 +389,6 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
+1 -3
View File
@@ -337,9 +337,7 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
// Project resolution only reads `.projects`; the command read model returns the
// same shape without loading the heavy per-thread activity/message tables.
return yield* projectionSnapshotQuery.getCommandReadModel();
return yield* projectionSnapshotQuery.getSnapshot();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
@@ -201,7 +201,6 @@ describe("OrchestrationEngine", () => {
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provide(
@@ -342,7 +342,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
createdAt: "2026-02-24T00:00:06.000Z",
},
],
hasMoreActivities: false,
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -975,8 +974,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
// Well under the window — nothing older to lazy-load.
assert.equal(threadDetail.value.hasMoreActivities, false);
}
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
@@ -1156,254 +1153,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect(
"windows thread-detail activities to the most recent 500 and pages older on demand",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
)
VALUES (
'project-1', 'Project 1', '/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
)
VALUES (
'thread-1', 'project-1', 'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 0, 0, 0,
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
)
`;
// 600 activities (sequence 1..600); the detail load must return only the
// most recent 500 (sequence 101..600), re-sorted ascending for display.
const total = 600;
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`activity-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`act-${seq}`}, '{}', ${seq},
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
const activities = threadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "act-101");
assert.equal(activities[0]?.sequence, 101);
assert.equal(activities.at(-1)?.summary, "act-600");
// 600 > window, so the client is told older history can be lazy-loaded.
assert.equal(threadDetail.value.hasMoreActivities, true);
}
// Lazy-load the page immediately older than the windowed view (cursor =
// oldest loaded sequence, 101): sequences 1..100, ascending, no more left.
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 101,
limit: 500,
});
assert.equal(olderPage.activities.length, 100);
assert.equal(olderPage.activities[0]?.summary, "act-1");
assert.equal(olderPage.activities.at(-1)?.summary, "act-100");
assert.equal(olderPage.hasMore, false);
// A bounded page returns the newest `limit` of the older set and reports
// that more remain (sequences 401..600, with 1..400 still older).
const boundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 601,
limit: 200,
});
assert.equal(boundedPage.activities.length, 200);
assert.equal(boundedPage.activities[0]?.summary, "act-401");
assert.equal(boundedPage.activities.at(-1)?.summary, "act-600");
assert.equal(boundedPage.hasMore, true);
yield* sql`DELETE FROM projection_thread_activities`;
// Legacy rows may not have a sequence. They are still windowed in the
// detail load and must remain pageable by the deterministic created/id
// ordering used by the snapshot query.
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`unsequenced-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`legacy-act-${seq}`}, '{}', NULL,
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const legacyThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
assert.equal(legacyThreadDetail._tag, "Some");
if (legacyThreadDetail._tag === "Some") {
const activities = legacyThreadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "legacy-act-101");
assert.equal(activities[0]?.sequence, undefined);
assert.equal(activities.at(-1)?.summary, "legacy-act-600");
const legacyOlderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: activities[0]?.createdAt ?? "2026-04-01T00:01:00.000Z",
beforeActivityId: activities[0]?.id ?? asEventId("unsequenced-0101"),
limit: 500,
});
assert.equal(legacyOlderPage.activities.length, 100);
assert.equal(legacyOlderPage.activities[0]?.summary, "legacy-act-1");
assert.equal(legacyOlderPage.activities.at(-1)?.summary, "legacy-act-100");
assert.equal(legacyOlderPage.hasMore, false);
}
const legacyBoundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: "2026-04-01T00:01:00.000Z",
beforeActivityId: asEventId("unsequenced-0601"),
limit: 200,
});
assert.equal(legacyBoundedPage.activities.length, 200);
assert.equal(legacyBoundedPage.activities[0]?.summary, "legacy-act-401");
assert.equal(legacyBoundedPage.activities.at(-1)?.summary, "legacy-act-600");
assert.equal(legacyBoundedPage.hasMore, true);
}),
);
it.effect("unsequenced cursor reaches all older rows without stranding sequenced ones", () =>
// Regression for the "unsequenced cursor hides sequenced history" concern:
// sequenced rows always sort newer than NULL-sequence (legacy) rows, so when
// the oldest loaded row is unsequenced every sequenced row is already in the
// window — the `sequence IS NULL` cursor can't strand sequenced rows.
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
) VALUES (
'project-1', 'Project 1', '/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
) VALUES (
'thread-1', 'project-1', 'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 0, 0, 0,
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
)
`;
// 600 legacy unsequenced rows (older) + 3 sequenced rows (newer). The
// window keeps the 3 sequenced + the most-recent 497 unsequenced, so the
// oldest loaded row is unsequenced and 103 older unsequenced remain.
yield* Effect.forEach(
Array.from({ length: 600 }, (_u, index) => index + 1),
(n) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
) VALUES (
${`unseq-${String(n).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`unseq-${n}`}, '{}', NULL,
${`2026-04-01T00:00:01.${String(n).padStart(3, "0")}Z`}
)
`,
{ discard: true },
);
yield* Effect.forEach(
[1, 2, 3],
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
) VALUES (
${`seq-${seq}`}, 'thread-1', NULL, 'info', 'runtime.note',
${`seq-${seq}`}, '{}', ${seq}, ${`2026-04-01T09:00:0${seq}.000Z`}
)
`,
{ discard: true },
);
const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(detail._tag, "Some");
if (detail._tag !== "Some") return;
const windowed = detail.value.activities;
assert.equal(windowed.length, 500);
// Sequenced rows are the newest (end of the ascending window); the oldest
// loaded row is unsequenced — exactly the case the concern is about.
assert.equal(windowed.at(-1)?.summary, "seq-3");
assert.equal(windowed[0]?.sequence, undefined);
// The client pages with the unsequenced cursor of the oldest loaded row.
const oldest = windowed[0];
assert.ok(oldest);
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: oldest.createdAt,
beforeActivityId: oldest.id,
limit: 500,
});
// The 103 older unsequenced rows come back, none are sequenced, and no
// sequenced row was stranded (all 3 are already in the window).
assert.equal(olderPage.activities.length, 103);
assert.equal(olderPage.hasMore, false);
assert.ok(olderPage.activities.every((a) => a.sequence === undefined));
}),
);
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1,7 +1,6 @@
import {
ChatAttachment,
CheckpointRef,
EventId,
IsoDateTime,
MessageId,
NonNegativeInt,
@@ -118,31 +117,6 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
/**
* Maximum number of most-recent activities loaded into a thread-detail snapshot.
* Bounds peak memory when opening a long-lived thread; older activities are
* fetched on demand (lazy-load, planned) and live ones stream in via events.
*/
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
// `beforeSequence`/`limit` are NonNegativeInt (not bare Number) to match the
// contract: the WHERE clause `(sequence < beforeSequence OR sequence IS NULL)`
// is only equivalent to the old `COALESCE(sequence, -1) < beforeSequence` when
// `beforeSequence` is non-negative — a negative cursor would silently match no
// sequenced rows and return only unsequenced ones. Validating here (not just at
// the RPC boundary) keeps any future non-RPC caller honest.
const ThreadActivitiesBeforeSequenceInput = Schema.Struct({
threadId: ThreadId,
beforeSequence: NonNegativeInt,
limit: NonNegativeInt,
});
const ThreadActivitiesBeforeActivityInput = Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: NonNegativeInt,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -280,23 +254,6 @@ function mapProposedPlanRow(
};
}
function mapThreadActivityRow(
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
): OrchestrationThreadActivity {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
// `sequence` is the pagination cursor; omit it when the (legacy) row is
// unsequenced so the optional contract field stays absent.
return row.sequence !== null ? Object.assign(activity, { sequence: row.sequence }) : activity;
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProjectionRepositoryError =>
Schema.isSchemaError(cause)
@@ -851,11 +808,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// The thread-detail timeline loads only the most recent window of activities so a
// long-lived thread (tens of thousands of activities, hundreds of MB of payload)
// can't blow the server heap. New activities still stream in live via the event
// subscription; older history will be fetched on demand once lazy-load lands.
// Select the most recent N (sequence DESC) then re-sort ascending for display.
const listThreadActivityRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
@@ -871,17 +823,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM (
SELECT *
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
-- One extra beyond the window so the caller can report hasMoreActivities.
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
)
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence ASC,
created_at ASC,
@@ -889,81 +832,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Older-than-cursor page for lazy-load. Returns rows newest-first (DESC) so a
// simple LIMIT yields the page adjacent to the cursor; the caller reverses to
// ascending. `sequence IS NULL` (legacy unsequenced) rows sort last under
// `sequence DESC` (SQLite orders NULLs last in DESC) — the very oldest — so
// paging eventually reaches them. `beforeSequence` is a NonNegativeInt, so
// `(sequence < beforeSequence OR sequence IS NULL)` is equivalent to the old
// `COALESCE(sequence, -1) < beforeSequence` but lets the
// (thread_id, sequence, created_at, activity_id) index satisfy the ORDER BY
// directly instead of forcing a filesort over the whole thread.
const listThreadActivityRowsBeforeSequence = SqlSchema.findAll({
Request: ThreadActivitiesBeforeSequenceInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeSequence, limit }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND (sequence < ${beforeSequence} OR sequence IS NULL)
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
// Legacy unsequenced (sequence NULL) rows are paged by a (created_at,
// activity_id) cursor. created_at is compared lexicographically as TEXT, which
// equals chronological order only because timestamps are canonical ISO-8601
// (always UTC `Z`, fixed millisecond precision) — the same invariant every
// `ORDER BY created_at` in this layer (including the detail window above)
// already relies on, so the cursor stays consistent with how rows are
// displayed. activity_id breaks created_at ties; its ordering is arbitrary but
// matches the window's `activity_id` tiebreak, so pages never skip or repeat.
const listUnsequencedThreadActivityRowsBeforeActivity = SqlSchema.findAll({
Request: ThreadActivitiesBeforeActivityInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeCreatedAt, beforeActivityId, limit }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND sequence IS NULL
AND (
created_at < ${beforeCreatedAt}
OR (
created_at = ${beforeCreatedAt}
AND activity_id < ${beforeActivityId}
)
)
ORDER BY
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
const getThreadSessionRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadSessionDbRowSchema,
@@ -1208,7 +1076,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
for (const row of activityRows) {
updatedAt = maxIso(updatedAt, row.createdAt);
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
threadActivities.push(mapThreadActivityRow(row));
threadActivities.push({
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
@@ -1313,8 +1190,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
// The full snapshot is unwindowed, so there is never more to load.
hasMoreActivities: false,
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -2123,14 +1998,21 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
// The query fetches WINDOW+1 ascending rows; if it returned the extra
// one, older activities exist beyond the window — drop that oldest row
// and flag it so clients can lazy-load older history.
activities: (activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
: activityRows
).map(mapThreadActivityRow),
hasMoreActivities: activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW,
activities: activityRows.map((row) => {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
if (row.sequence !== null) {
return Object.assign(activity, { sequence: row.sequence });
}
return activity;
}),
checkpoints: checkpointRows.map((row) => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
@@ -2181,43 +2063,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
const getThreadActivitiesPage: ProjectionSnapshotQueryShape["getThreadActivitiesPage"] = (
input,
) =>
Effect.gen(function* () {
const limit = Math.min(
Math.max(1, input.limit ?? THREAD_DETAIL_ACTIVITY_WINDOW),
THREAD_DETAIL_ACTIVITY_WINDOW,
);
// Fetch one extra to detect whether older activities remain.
const rowsEffect =
"beforeSequence" in input
? listThreadActivityRowsBeforeSequence({
threadId: input.threadId,
beforeSequence: input.beforeSequence,
limit: limit + 1,
})
: listUnsequencedThreadActivityRowsBeforeActivity({
threadId: input.threadId,
beforeCreatedAt: input.beforeCreatedAt,
beforeActivityId: input.beforeActivityId,
limit: limit + 1,
});
const rows = yield* rowsEffect.pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadActivitiesPage:query",
"ProjectionSnapshotQuery.getThreadActivitiesPage:decodeRows",
),
),
);
const hasMore = rows.length > limit;
// Rows are newest-first; keep the page closest to the cursor, then reverse
// to ascending for display.
const page = (hasMore ? rows.slice(0, limit) : rows).map(mapThreadActivityRow).toReversed();
return { activities: page, hasMore };
});
return {
getCommandReadModel,
getSnapshot,
@@ -2233,7 +2078,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getThreadShellById,
getThreadDetailById,
getThreadDetailSnapshot,
getThreadActivitiesPage,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -27,8 +27,9 @@ export interface OrchestrationEngineShape {
*
* @param fromSequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to read. Defaults to the event
* store's page-bounded default. Callers must keep this bounded; use a
* projection snapshot instead of replaying an arbitrarily stale cursor.
* store's page-bounded default; pass a higher value when the caller must
* read every event after the cursor (e.g. per-thread catch-up that filters
* a small subset out of a potentially larger global range).
* @returns Stream containing ordered events.
*/
readonly readEvents: (
@@ -9,8 +9,6 @@
import type {
CheckpointRef,
OrchestrationCheckpointSummary,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetThreadActivitiesResult,
OrchestrationProject,
OrchestrationProjectShell,
OrchestrationReadModel,
@@ -170,16 +168,6 @@ export interface ProjectionSnapshotQueryShape {
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
/**
* Cursor-paginated load of a thread's older activities (lazy-load / infinite
* scroll). Returns the page of activities immediately older than the provided
* sequence or unsequenced activity cursor, ascending, plus whether older ones
* remain.
*/
readonly getThreadActivitiesPage: (
input: OrchestrationGetThreadActivitiesInput,
) => Effect.Effect<OrchestrationGetThreadActivitiesResult, ProjectionRepositoryError>;
}
/**
+1 -5
View File
@@ -31,12 +31,8 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.snapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
// The only consumer (the `t3` CLI project resolver) reads just
// `.projects`, so use the command read model — it returns the same
// OrchestrationReadModel shape but never materialises the per-thread
// activity/message/checkpoint tables (490MB+ on a busy DB → heap OOM).
return yield* projectionSnapshotQuery
.getCommandReadModel()
.getSnapshot()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
@@ -27,7 +27,6 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
@@ -210,7 +210,6 @@ describe("ProviderSessionReaper", () => {
),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provideMerge(NodeServices.layer),
-46
View File
@@ -5877,52 +5877,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeThread replaces a stale cursor with a fresh snapshot", () =>
Effect.gen(function* () {
const snapshotSequence = 5_000;
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
let replayCalls = 0;
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshotSequence: () => Effect.succeed({ snapshotSequence }),
getThreadDetailSnapshot: () =>
Effect.succeed(
Option.some({
snapshotSequence,
thread,
}),
),
},
orchestrationEngine: {
readEvents: () => {
replayCalls += 1;
return Stream.empty;
},
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 1,
}).pipe(Stream.take(1), Stream.runCollect),
),
);
assert.equal(replayCalls, 0);
assert.equal(result[0]?.kind, "snapshot");
if (result[0]?.kind === "snapshot") {
assert.equal(result[0].snapshot.snapshotSequence, snapshotSequence);
assert.equal(result[0].snapshot.thread.id, defaultThreadId);
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("subscribeShell coalesces a per-thread burst without stalling other threads", () =>
Effect.gen(function* () {
const busyThreadId = ThreadId.make("thread-busy");
@@ -97,7 +97,6 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(AnalyticsService.AnalyticsService, {
record: () => Effect.void,
@@ -161,7 +160,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -206,7 +204,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -257,7 +254,6 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vite-plus/test";
import {
ghosttyThemeSearchPaths,
parseGhosttyConfig,
splitThemeSelection,
} from "./ghosttyStyle.ts";
const posixPath = {
isAbsolute: (value: string) => value.startsWith("/"),
join: (...segments: ReadonlyArray<string>) =>
segments
.map((segment, index) =>
index === 0 ? segment.replace(/\/$/, "") : segment.replace(/^\//, ""),
)
.join("/"),
};
const windowsPath = {
isAbsolute: (value: string) => /^[A-Za-z]:[\\/]/.test(value),
join: (...segments: ReadonlyArray<string>) => segments.join("\\"),
};
describe("parseGhosttyConfig", () => {
it("omits empty scalar color assignments", () => {
const config = parseGhosttyConfig(`
background =
foreground = ""
cursor-color = #c0ffee
`);
expect(config.colors.background).toBeUndefined();
expect(config.colors.foreground).toBeUndefined();
expect(config.colors.cursor).toBe("#c0ffee");
});
});
describe("splitThemeSelection", () => {
it("keeps a Windows absolute theme path as a bare selection", () => {
expect(splitThemeSelection("C:/Users/Alex/Ghostty Themes/t3code")).toEqual({
light: "C:/Users/Alex/Ghostty Themes/t3code",
dark: "C:/Users/Alex/Ghostty Themes/t3code",
});
});
it("still parses explicit light and dark theme selections", () => {
expect(splitThemeSelection("light:Day,dark:Night")).toEqual({
light: "Day",
dark: "Night",
});
});
});
describe("ghosttyThemeSearchPaths", () => {
it("searches beside the macOS Application Support config", () => {
const candidates = ghosttyThemeSearchPaths(posixPath, {
home: "/Users/alex",
xdgConfigHome: "/Users/alex/.config",
themeName: "t3code",
});
expect(candidates).toContain(
"/Users/alex/Library/Application Support/com.mitchellh.ghostty/themes/t3code",
);
});
it("tries an absolute theme file before named-theme directories", () => {
const candidates = ghosttyThemeSearchPaths(windowsPath, {
home: "C:\\Users\\alex",
xdgConfigHome: "C:\\Users\\alex\\.config",
themeName: "D:\\themes\\t3code",
});
expect(candidates[0]).toBe("D:\\themes\\t3code");
});
});
+289
View File
@@ -0,0 +1,289 @@
import * as NodeOS from "node:os";
import type { ServerTerminalStyle, ServerTerminalThemeColors } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
const PALETTE_SIZE = 16;
interface GhosttyConfigValues {
readonly fontFamily: ReadonlyArray<string>;
readonly fontSize: number | undefined;
readonly theme: string | undefined;
readonly colors: MutableThemeColors;
}
interface MutableThemeColors {
background?: string | undefined;
foreground?: string | undefined;
cursor?: string | undefined;
selectionBackground?: string | undefined;
selectionForeground?: string | undefined;
palette: Array<string>;
}
function emptyColors(): MutableThemeColors {
return { palette: Array.from({ length: PALETTE_SIZE }, () => "") };
}
function stripQuotes(value: string): string {
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, -1);
}
return value;
}
function applyColorEntry(colors: MutableThemeColors, key: string, value: string): void {
// Empty assignments are resets, not colors. Keeping an empty scalar here
// would later violate ServerConfig's TrimmedNonEmptyString schema and make
// the whole server.getConfig response fail to encode.
if (value.length === 0) return;
switch (key) {
case "background":
colors.background = value;
return;
case "foreground":
colors.foreground = value;
return;
case "cursor-color":
colors.cursor = value;
return;
case "selection-background":
colors.selectionBackground = value;
return;
case "selection-foreground":
colors.selectionForeground = value;
return;
case "palette": {
const match = value.match(/^(\d+)\s*=\s*(\S+)$/);
if (!match) return;
const index = Number(match[1]);
if (!Number.isInteger(index) || index < 0 || index >= PALETTE_SIZE) return;
colors.palette[index] = match[2] ?? "";
return;
}
default:
return;
}
}
/** Parse Ghostty's `key = value` config format, keeping only what the web terminal uses. */
export function parseGhosttyConfig(source: string): GhosttyConfigValues {
const fontFamily: Array<string> = [];
let fontSize: number | undefined;
let theme: string | undefined;
const colors = emptyColors();
for (const rawLine of source.split("\n")) {
const line = rawLine.trim();
if (line.length === 0 || line.startsWith("#")) continue;
const separatorIndex = line.indexOf("=");
if (separatorIndex <= 0) continue;
const key = line.slice(0, separatorIndex).trim();
const value = stripQuotes(line.slice(separatorIndex + 1).trim());
switch (key) {
case "font-family":
// Repeated entries build a fallback chain; an empty value resets it.
if (value.length === 0) {
fontFamily.length = 0;
} else {
fontFamily.push(value);
}
break;
case "font-size": {
const parsed = Number(value);
if (Number.isFinite(parsed) && parsed > 0) {
fontSize = parsed;
}
break;
}
case "theme":
theme = value.length > 0 ? value : undefined;
break;
default:
applyColorEntry(colors, key, value);
break;
}
}
return { fontFamily, fontSize, theme, colors };
}
/** Split `theme = light:A,dark:B` into per-mode names; a bare name applies to both. */
export function splitThemeSelection(theme: string): { light?: string; dark?: string } {
const result: { light?: string; dark?: string } = {};
let hasModeSelection = false;
for (const part of theme.split(",")) {
const match = /^\s*(light|dark):(.*)$/.exec(part);
if (!match) continue;
const mode = match[1];
const name = (match[2] ?? "").trim();
if (name.length === 0) continue;
hasModeSelection = true;
if (mode === "light") result.light = name;
if (mode === "dark") result.dark = name;
}
// A colon is also part of a Windows drive path (C:/theme), and may be part
// of another valid bare theme identifier. Only enter per-mode parsing when
// an explicit light: or dark: selection was recognized.
return hasModeSelection ? result : { light: theme, dark: theme };
}
function hasAnyColor(colors: MutableThemeColors): boolean {
return (
colors.background !== undefined ||
colors.foreground !== undefined ||
colors.cursor !== undefined ||
colors.selectionBackground !== undefined ||
colors.selectionForeground !== undefined ||
colors.palette.some((entry) => entry.length > 0)
);
}
function mergeColors(base: MutableThemeColors, override: MutableThemeColors): MutableThemeColors {
return {
background: override.background ?? base.background,
foreground: override.foreground ?? base.foreground,
cursor: override.cursor ?? base.cursor,
selectionBackground: override.selectionBackground ?? base.selectionBackground,
selectionForeground: override.selectionForeground ?? base.selectionForeground,
palette: base.palette.map((entry, index) => {
const overrideEntry = override.palette[index] ?? "";
return overrideEntry.length > 0 ? overrideEntry : entry;
}),
};
}
function toThemeColors(colors: MutableThemeColors): ServerTerminalThemeColors | undefined {
if (!hasAnyColor(colors)) return undefined;
return {
...(colors.background !== undefined ? { background: colors.background } : {}),
...(colors.foreground !== undefined ? { foreground: colors.foreground } : {}),
...(colors.cursor !== undefined ? { cursor: colors.cursor } : {}),
...(colors.selectionBackground !== undefined
? { selectionBackground: colors.selectionBackground }
: {}),
...(colors.selectionForeground !== undefined
? { selectionForeground: colors.selectionForeground }
: {}),
palette: colors.palette,
};
}
// Bundled theme locations by platform: the macOS app bundle and the
// Linux system resource dirs documented by Ghostty.
const GHOSTTY_SYSTEM_THEME_DIRS = [
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
];
export function ghosttyThemeSearchPaths(
path: Pick<Path.Path, "isAbsolute" | "join">,
input: { readonly home: string; readonly xdgConfigHome: string; readonly themeName: string },
): ReadonlyArray<string> {
return [
...(path.isAbsolute(input.themeName) ? [input.themeName] : []),
path.join(input.xdgConfigHome, "ghostty", "themes", input.themeName),
path.join(
input.home,
"Library",
"Application Support",
"com.mitchellh.ghostty",
"themes",
input.themeName,
),
...GHOSTTY_SYSTEM_THEME_DIRS.map((dir) => path.join(dir, input.themeName)),
];
}
/**
* Load terminal font and theme colors from the user's local Ghostty config.
* Best effort by design: any missing file or parse problem yields `undefined`
* so the client falls back to its built-in terminal appearance.
*/
export const loadGhosttyTerminalStyle: Effect.Effect<
ServerTerminalStyle | undefined,
never,
FileSystem.FileSystem | Path.Path
> = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = NodeOS.homedir();
// Per the XDG spec an empty XDG_CONFIG_HOME must be treated as unset.
const xdgConfigHomeEnv = process.env["XDG_CONFIG_HOME"];
const xdgConfigHome =
xdgConfigHomeEnv !== undefined && xdgConfigHomeEnv.length > 0
? xdgConfigHomeEnv
: path.join(home, ".config");
const readFirstExisting = (candidates: ReadonlyArray<string>) =>
Effect.gen(function* () {
for (const candidate of candidates) {
const exists = yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (!exists) continue;
const content = yield* fs
.readFileString(candidate)
.pipe(Effect.orElseSucceed(() => undefined));
if (content !== undefined) return content;
}
return undefined;
});
// Ghostty reads the XDG config first and the macOS Application Support
// config after it, so later files override earlier values. It also accepts
// config.ghostty as the file name. Merge every location that exists instead
// of stopping at the first match.
const configDirs = [
path.join(xdgConfigHome, "ghostty"),
path.join(home, "Library", "Application Support", "com.mitchellh.ghostty"),
];
const configSources: Array<string> = [];
for (const dir of configDirs) {
// Read both file names when they coexist so neither shadows the other;
// Ghostty loads config.ghostty before config, so config wins conflicts.
for (const candidate of [path.join(dir, "config.ghostty"), path.join(dir, "config")]) {
const source = yield* readFirstExisting([candidate]);
if (source !== undefined) configSources.push(source);
}
}
if (configSources.length === 0) return undefined;
const config = parseGhosttyConfig(configSources.join("\n"));
const loadThemeColors = (themeName: string) =>
Effect.gen(function* () {
const themeSource = yield* readFirstExisting(
ghosttyThemeSearchPaths(path, { home, xdgConfigHome, themeName }),
);
if (themeSource === undefined) return emptyColors();
return parseGhosttyConfig(themeSource).colors;
});
const themeSelection = config.theme ? splitThemeSelection(config.theme) : {};
const resolveModeColors = (themeName: string | undefined) =>
Effect.gen(function* () {
const themeColors = themeName ? yield* loadThemeColors(themeName) : emptyColors();
// Explicit colors in the user config override the selected theme.
return toThemeColors(mergeColors(themeColors, config.colors));
});
const light = yield* resolveModeColors(themeSelection.light);
const dark = yield* resolveModeColors(themeSelection.dark);
const style: ServerTerminalStyle = {
...(config.fontFamily.length > 0 ? { fontFamily: config.fontFamily } : {}),
...(config.fontSize !== undefined ? { fontSize: config.fontSize } : {}),
...(light !== undefined ? { light } : {}),
...(dark !== undefined ? { dark } : {}),
};
const hasAnyValue =
style.fontFamily !== undefined ||
style.fontSize !== undefined ||
style.light !== undefined ||
style.dark !== undefined;
return hasAnyValue ? style : undefined;
}).pipe(Effect.orElseSucceed(() => undefined));
+8 -78
View File
@@ -34,7 +34,6 @@ import {
type OrchestrationThreadStreamItem,
OrchestrationGetFullThreadDiffError,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_WS_METHODS,
type ProjectId,
@@ -82,6 +81,7 @@ import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
import { loadGhosttyTerminalStyle } from "./terminal/ghosttyStyle.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -116,24 +116,6 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT = 1_000;
const subscriptionReplayLimit = (
afterSequence: number,
snapshotSequence: number,
): number | null => {
const eventCount = snapshotSequence - afterSequence;
if (
!Number.isSafeInteger(eventCount) ||
eventCount < 0 ||
eventCount > ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT
) {
return null;
}
return eventCount;
};
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
@@ -306,7 +288,6 @@ const SHELL_RESUME_MAX_GAP = 1_000;
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getThreadActivities, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
@@ -1085,6 +1066,7 @@ const makeWsRpcLayer = (
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
const terminalStyle = yield* loadGhosttyTerminalStyle;
const providers = yield* providerRegistry.getProviders;
const settings = ServerSettings.redactServerSettingsForClient(
yield* serverSettings.getSettings,
@@ -1101,6 +1083,7 @@ const makeWsRpcLayer = (
issues: keybindingsConfig.issues,
providers,
availableEditors: yield* externalLauncher.resolveAvailableEditors(),
...(terminalStyle !== undefined ? { terminalStyle } : {}),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
@@ -1203,20 +1186,6 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getThreadActivities]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getThreadActivities,
projectionSnapshotQuery.getThreadActivitiesPage(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetThreadActivitiesError({
message: "Failed to load thread activities page",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
@@ -1416,53 +1385,14 @@ const makeWsRpcLayer = (
// catch-up followed by the buffered/ongoing live events. Overlapping
// events are deduped by sequence on the client.
//
// A recent cursor replays the exact global range through the
// per-thread filter. A stale cursor receives a current thread
// snapshot instead, keeping catch-up bounded even when the global
// event log is very large.
// Read the full range after the cursor (not the store's default
// page-bounded limit): the range is normally tiny (a fresh HTTP
// snapshot sequence) and the per-thread filter runs after reading,
// so a global cap could otherwise omit this thread's events.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const { snapshotSequence } = yield* projectionSnapshotQuery
.getSnapshotSequence()
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot sequence",
cause,
}),
),
);
const replayLimit = subscriptionReplayLimit(afterSequence, snapshotSequence);
if (replayLimit === null) {
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to load thread ${input.threadId}`,
cause,
}),
),
);
if (Option.isNone(snapshot)) {
return yield* new OrchestrationGetSnapshotError({
message: `Thread ${input.threadId} was not found`,
cause: input.threadId,
});
}
return Stream.concat(
Stream.make({ kind: "snapshot" as const, snapshot: snapshot.value }),
bufferedLiveStream,
);
}
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, replayLimit)
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
+1 -2
View File
@@ -31,10 +31,9 @@
"@t3tools/shared": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"ghostty-web": "0.4.0",
"jose": "catalog:",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
+2 -52
View File
@@ -63,10 +63,6 @@ import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
useOlderThreadActivities,
type OlderActivitiesCursor,
} from "@t3tools/client-runtime/state/older-thread-activities";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { isElectron } from "../env";
@@ -194,7 +190,6 @@ import {
primaryServerKeybindingsAtom,
serverEnvironment,
} from "../state/server";
import { orchestrationEnvironment } from "../state/orchestration";
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
@@ -1865,45 +1860,7 @@ function ChatViewContent(props: ChatViewProps) {
);
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const phase = derivePhase(activeThread?.session ?? null);
// ── Older-history lazy-load ────────────────────────────────────────────────
// The detail snapshot windows activities to the most recent page (the server
// sets `hasMoreActivities` when older ones exist); older pages are fetched on
// demand (infinite scroll-up) and prepended by the shared engine. Messages
// aren't windowed server-side, so this just back-fills the older tool
// activity.
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
reportFailure: false,
});
const activeThreadEnvironmentIdForActivities = activeThread?.environmentId ?? null;
const activeThreadIdForActivities = activeThread?.id ?? null;
const loadOlderActivitiesPage = useCallback(
async (cursor: OlderActivitiesCursor) => {
if (activeThreadEnvironmentIdForActivities === null || activeThreadIdForActivities === null) {
return null;
}
const result = await loadThreadActivities({
environmentId: activeThreadEnvironmentIdForActivities,
input: { threadId: activeThreadIdForActivities, ...cursor },
});
// Failures stay silent on web (the "Load older history" affordance itself
// is the retry surface); returning null keeps `hasMore` for the retry.
return result._tag === "Success" ? result.value : null;
},
[activeThreadEnvironmentIdForActivities, activeThreadIdForActivities, loadThreadActivities],
);
const {
mergedActivities: threadActivities,
hasMoreOlder: hasMoreOlderActivities,
loadingOlder: loadingOlderActivities,
loadOlder: loadOlderActivities,
} = useOlderThreadActivities({
threadKey: activeThread ? `${activeThread.environmentId}\u0000${activeThread.id}` : null,
liveActivities: activeThread?.activities ?? EMPTY_ACTIVITIES,
hasMoreLiveActivities: activeThread?.hasMoreActivities ?? false,
loadPage: loadOlderActivitiesPage,
});
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
@@ -5299,9 +5256,6 @@ function ChatViewContent(props: ChatViewProps) {
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
hasMoreOlder={hasMoreOlderActivities}
loadingOlder={loadingOlderActivities}
onLoadOlder={loadOlderActivities}
latestTurn={activeLatestTurn}
runningTurnId={
activeThread.session?.status === "running"
@@ -5450,11 +5404,7 @@ function ChatViewContent(props: ChatViewProps) {
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
// Merged set (older pages + live window), not the windowed
// live slice: the context meter scans for the latest
// context-window.updated event, which can sit in a
// lazy-loaded page on long threads.
activeThreadActivities={threadActivities}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
File diff suppressed because it is too large. Load diff
@@ -5,68 +5,8 @@ import {
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveOlderHistoryAutoLoad,
} from "./MessagesTimeline.logic";
describe("resolveOlderHistoryAutoLoad", () => {
it("dispatches only once while a failed or successful load leaves the viewport at the top", () => {
const first = resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: false,
});
expect(first).toEqual({ requestedAtStart: true, shouldLoad: true });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: first.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: true,
requestedAtStart: first.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
});
it("rearms automatic loading only after leaving the top", () => {
const away = resolveOlderHistoryAutoLoad({
isAtStart: false,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: true,
});
expect(away).toEqual({ requestedAtStart: false, shouldLoad: false });
expect(
resolveOlderHistoryAutoLoad({
isAtStart: true,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: away.requestedAtStart,
}),
).toEqual({ requestedAtStart: true, shouldLoad: true });
});
it("does not reset the latch before list state is available", () => {
expect(
resolveOlderHistoryAutoLoad({
isAtStart: undefined,
hasMoreOlder: true,
loadingOlder: false,
requestedAtStart: true,
}),
).toEqual({ requestedAtStart: true, shouldLoad: false });
});
});
describe("computeMessageDurationStart", () => {
it("returns message createdAt when there is no preceding user message", () => {
const result = computeMessageDurationStart([
@@ -21,42 +21,6 @@ export interface TimelineEndState {
readonly isNearEnd?: boolean;
}
export interface OlderHistoryAutoLoadInput {
readonly isAtStart: boolean | undefined;
readonly hasMoreOlder: boolean;
readonly loadingOlder: boolean;
readonly requestedAtStart: boolean;
}
export interface OlderHistoryAutoLoadResult {
readonly requestedAtStart: boolean;
readonly shouldLoad: boolean;
}
/**
* Permit at most one automatic older-history request per visit to the top.
* Loading completion and prepended rows both retrigger timeline measurements;
* neither should recursively request another page while the viewport remains
* pinned at the start. Leaving the top rearms automatic loading, while the
* explicit header control remains available for an immediate retry.
*/
export function resolveOlderHistoryAutoLoad(
input: OlderHistoryAutoLoadInput,
): OlderHistoryAutoLoadResult {
if (input.isAtStart === false) {
return { requestedAtStart: false, shouldLoad: false };
}
if (
input.isAtStart !== true ||
input.requestedAtStart ||
!input.hasMoreOlder ||
input.loadingOlder
) {
return { requestedAtStart: input.requestedAtStart, shouldLoad: false };
}
return { requestedAtStart: true, shouldLoad: true };
}
export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
return state?.isNearEnd ?? state?.isAtEnd;
}
@@ -640,37 +640,4 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("lucide-x");
expect(markup).toContain('aria-label="Tool call failed"');
});
it("offers a 'Load older history' control when older activity remains", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Hi")]}
hasMoreOlder
/>,
);
expect(markup).toContain("Load older history");
});
it("shows a loading indicator while older history is being fetched", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[buildUserTimelineEntry("Hi")]}
hasMoreOlder
loadingOlder
/>,
);
expect(markup).toContain("Loading older history");
});
it("renders no older-history control when none remains", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[buildUserTimelineEntry("Hi")]} />,
);
expect(markup).not.toContain("older history");
});
});
@@ -73,7 +73,6 @@ import {
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveOlderHistoryAutoLoad,
resolveTimelineIsAtEnd,
resolveTimelineMinimapHasPersistentGutter,
resolveTimelineMinimapHeightStyle,
@@ -186,10 +185,6 @@ interface MessagesTimelineProps {
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
/** Older history beyond the live activity window can be lazy-loaded. */
hasMoreOlder?: boolean;
loadingOlder?: boolean;
onLoadOlder?: () => void;
}
// ---------------------------------------------------------------------------
@@ -224,9 +219,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onIsAtEndChange,
onManualNavigation,
hideEmptyPlaceholder = false,
hasMoreOlder = false,
loadingOlder = false,
onLoadOlder,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -338,14 +330,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
);
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
const olderHistoryRequestedAtStartRef = useRef(false);
useEffect(() => {
olderHistoryRequestedAtStartRef.current = false;
}, [routeThreadKey]);
const requestOlderHistoryAtStart = useCallback(() => {
olderHistoryRequestedAtStartRef.current = true;
onLoadOlder?.();
}, [onLoadOlder]);
const handleAnchorReady = useCallback(
(info: { anchorIndex: number | undefined }) => {
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
@@ -377,20 +361,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
if (isAtEnd !== undefined) {
onIsAtEndChange(isAtEnd);
}
// Reaching the top lazy-loads one older page. Measurements rerun when the
// request settles and when rows prepend, so keep the visit latched until
// the user leaves the top; otherwise failures retry forever and successful
// pages chain-load the whole history back into memory.
const olderHistoryAutoLoad = resolveOlderHistoryAutoLoad({
isAtStart: state?.isAtStart,
hasMoreOlder: hasMoreOlder && onLoadOlder !== undefined,
loadingOlder,
requestedAtStart: olderHistoryRequestedAtStartRef.current,
});
olderHistoryRequestedAtStartRef.current = olderHistoryAutoLoad.requestedAtStart;
if (olderHistoryAutoLoad.shouldLoad) {
requestOlderHistoryAtStart();
}
if (!state || minimapItems.length === 0) {
return;
}
@@ -413,16 +383,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
strip.dataset.inView = inView ? "true" : "false";
}
}, [
listRef,
minimapItems,
minimapStripMap,
onIsAtEndChange,
hasMoreOlder,
loadingOlder,
onLoadOlder,
requestOlderHistoryAtStart,
]);
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
useEffect(() => {
const frame = requestAnimationFrame(handleScroll);
@@ -454,28 +415,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [timelineViewportElement, rows.length]);
const listHeader = useMemo(() => {
if (loadingOlder) {
return (
<div className="flex items-center justify-center py-2 text-xs text-muted-foreground">
Loading older history…
</div>
);
}
if (hasMoreOlder) {
return (
<button
type="button"
onClick={requestOlderHistoryAtStart}
className="flex w-full cursor-pointer items-center justify-center py-2 text-xs text-muted-foreground transition-colors hover:text-foreground"
>
Load older history
</button>
);
}
return TIMELINE_LIST_HEADER;
}, [loadingOlder, hasMoreOlder, requestOlderHistoryAtStart]);
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
timestampFormat,
@@ -527,11 +466,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
[],
);
// Only short-circuit to the empty state when there is genuinely nothing to
// fetch: the window can derive zero VISIBLE rows (e.g. only tool-neutral work
// entries) while older history still exists — the list must render then so
// its "Load older history" header stays reachable.
if (rows.length === 0 && !isWorking && !hasMoreOlder && !loadingOlder) {
if (rows.length === 0 && !isWorking) {
if (hideEmptyPlaceholder) {
return null;
}
@@ -576,7 +511,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={listHeader}
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
<TimelineMinimap
-1
View File
@@ -8,7 +8,6 @@ import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"
import "@fontsource-variable/dm-sans/index.css";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import "@xterm/xterm/css/xterm.css";
import "./index.css";
import { isElectron } from "./env";
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vite-plus/test";
import { shouldFocusTerminalAfterSetup } from "./terminal-focus";
describe("shouldFocusTerminalAfterSetup", () => {
it("focuses the active terminal on its first setup", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: false,
restorePreviousTerminalFocus: false,
}),
).toBe(true);
});
it("does not steal focus when terminal style causes a remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: true,
hasMounted: true,
restorePreviousTerminalFocus: false,
}),
).toBe(false);
});
it("restores focus when the terminal itself was focused before remount", () => {
expect(
shouldFocusTerminalAfterSetup({
autoFocus: false,
hasMounted: true,
restorePreviousTerminalFocus: true,
}),
).toBe(true);
});
});
+7
View File
@@ -0,0 +1,7 @@
export function shouldFocusTerminalAfterSetup(input: {
readonly autoFocus: boolean;
readonly hasMounted: boolean;
readonly restorePreviousTerminalFocus: boolean;
}): boolean {
return input.restorePreviousTerminalFocus || (!input.hasMounted && input.autoFocus);
}
+18
View File
@@ -37,6 +37,24 @@ describe("extractTerminalLinks", () => {
]);
});
it("finds non-http scheme urls", () => {
const line = "email mailto:[email protected] or clone ssh://[email protected]/t3/t3code.git now";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "mailto:[email protected]",
start: 6,
end: 28,
},
{
kind: "url",
text: "ssh://[email protected]/t3/t3code.git",
start: 38,
end: 72,
},
]);
});
it("trims trailing punctuation from links", () => {
const line = "(https://example.com/docs), ./src/main.ts:12.";
expect(extractTerminalLinks(line)).toEqual([
+4 -1
View File
@@ -36,7 +36,10 @@ export interface WrappedTerminalLinkLine {
segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
}
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
// Also matches the non-http schemes ghostty and other terminals linkify;
// authority-style schemes require // while opaque ones take a bare payload.
const URL_PATTERN =
/(?:https?|ftp|ssh|git|gemini|gopher):\/\/[^\s"'`<>]+|(?:mailto|tel|news|magnet):[^\s"'`<>:][^\s"'`<>]*/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
-18
View File
@@ -123,14 +123,6 @@
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
},
"./state/thread-reducer": {
"types": "./src/state/threadReducer.ts",
"default": "./src/state/threadReducer.ts"
},
"./state/older-thread-activities": {
"types": "./src/state/olderThreadActivities.ts",
"default": "./src/state/olderThreadActivities.ts"
},
"./state/thread-sort": {
"types": "./src/state/threadSort.ts",
"default": "./src/state/threadSort.ts"
@@ -151,16 +143,6 @@
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/react": "~19.2.14",
"react": "19.2.6",
"vite-plus": "catalog:"
},
"peerDependencies": {
"react": "^19.0.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
}
}
@@ -1,270 +0,0 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { liveWindowOldestActivityId, oldestActivityByChronology } from "./threadReducer.ts";
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
/**
* Pagination cursor for a thread's older activities. Sequenced rows page by
* `beforeSequence`; legacy/unsequenced rows (the common case — `sequence` is
* absent on most real rows) page by the `(createdAt, activityId)` keyset.
*/
export type OlderActivitiesCursor =
| { readonly beforeSequence: number }
| {
readonly beforeCreatedAt: OrchestrationThreadActivity["createdAt"];
readonly beforeActivityId: OrchestrationThreadActivity["id"];
};
export interface OlderActivitiesPage {
readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
readonly hasMore: boolean;
}
export interface UseOlderThreadActivitiesOptions {
/**
* Identity of the thread the live window belongs to (e.g.
* `${environmentId}\0${threadId}`); null when no thread is selected.
* Changing it resets the lazy-loaded pages.
*/
readonly threadKey: string | null;
/** The server-windowed live activity set from the thread detail. */
readonly liveActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** The server's `hasMoreActivities` flag from the detail snapshot. */
readonly hasMoreLiveActivities: boolean;
/**
* Fetch the page immediately older than the cursor. Resolve `null` to skip
* the page silently (a failure the caller already surfaced, or an
* interrupted command) — `hasMore` is left true so the user can retry.
* MUST be referentially stable (useCallback) for the load callback to be.
*/
readonly loadPage: (cursor: OlderActivitiesCursor) => Promise<OlderActivitiesPage | null>;
}
export interface UseOlderThreadActivitiesResult {
/** Lazy-loaded older pages + the live window, oldest first. */
readonly mergedActivities: ReadonlyArray<OrchestrationThreadActivity>;
/** Whether older history exists beyond everything loaded. */
readonly hasMoreOlder: boolean;
readonly loadingOlder: boolean;
/** Dispatch a load of the next older page (no-op while one is in flight). */
readonly loadOlder: () => void;
}
// ── Pure decision kernel (exported for unit tests) ──────────────────────────
export interface LiveWindowShape {
readonly key: string | null;
/** Chronological-oldest activity id (an identity sentinel, not a lookup key). */
readonly oldest: string | null;
readonly count: number;
}
/**
* Whether the live window was RESHAPED rather than purely appended-to: a
* different thread, a re-snapshot (reconnect) that changes the window's
* chronological-oldest row, or a checkpoint revert that shrinks it. A pure
* append (same thread, same oldest, count not smaller) is NOT a reshape.
*/
export function didLiveWindowReshape(previous: LiveWindowShape, next: LiveWindowShape): boolean {
return (
next.key !== previous.key || next.oldest !== previous.oldest || next.count < previous.count
);
}
/**
* The cursor for the page immediately older than `oldest`: sequenced rows page
* by `beforeSequence`; unsequenced rows (the common case) by the
* `(createdAt, activityId)` keyset.
*/
export function olderActivitiesCursorFor(
oldest: OrchestrationThreadActivity,
): OlderActivitiesCursor {
return oldest.sequence !== undefined
? { beforeSequence: oldest.sequence }
: { beforeCreatedAt: oldest.createdAt, beforeActivityId: oldest.id };
}
/**
* The row the NEXT load should cursor from: the explicit cursor row already
* paged past when one exists (so an all-overlap page keeps advancing), else
* the chronologically-oldest loaded row — never index 0, which the reducer
* can fill with a newer row (unsequenced rows sort to the end).
*/
export function nextOlderActivitiesCursorRow(
pagedPast: OrchestrationThreadActivity | null,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity | null {
return pagedPast ?? oldestActivityByChronology(merged);
}
/**
* The page rows not already present in the loaded set (older pages + live
* window) — boundary overlap and mid-flight appends must never produce
* duplicate ids in the merged timeline.
*/
export function freshOlderActivities(
page: OlderActivitiesPage,
merged: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const seen = new Set(merged.map((activity) => activity.id));
return page.activities.filter((activity) => !seen.has(activity.id));
}
/**
* The older-history lazy-load engine, shared by every client (web ChatView,
* the mobile composer, the TUI ChatView). The thread-detail snapshot windows
* activities to the most recent page; older pages are fetched on demand and
* prepended.
*
* One implementation holds all the hardening the per-client copies kept
* drifting on:
* - reset on live-window RESHAPE, not just thread switch: a reconnect
* re-snapshot changes the window's chronological-oldest row and a checkpoint
* revert shrinks it, but a plain append does neither (the reducer re-sorts
* unsequenced rows, so index 0 is not a stable boundary — the sentinel is
* {@link liveWindowOldestActivityId});
* - a generation guard so a load resolving after a reset can't repopulate the
* cleared state;
* - a synchronous in-flight key so scroll-triggered duplicate dispatches
* coalesce before the loading state commits;
* - an explicit advancing cursor (the oldest row paged PAST), so an
* all-overlap page keeps paging instead of dead-ending while the server
* still reports more — the server cursor is strict, so it strictly
* decreases and paging cannot loop;
* - dedup against the LATEST merged set via a ref, so a live append or a
* prior prepend settling mid-flight can't produce duplicate ids;
* - `hasMore` stays true on a failed/skipped page (the history still exists;
* scrolling back retries).
*/
export function useOlderThreadActivities(
options: UseOlderThreadActivitiesOptions,
): UseOlderThreadActivitiesResult {
const { threadKey, liveActivities, hasMoreLiveActivities, loadPage } = options;
const [olderActivities, setOlderActivities] = useState<
ReadonlyArray<OrchestrationThreadActivity>
>([]);
const [olderLoaded, setOlderLoaded] = useState(false);
const [olderHasMore, setOlderHasMore] = useState(false);
const [loadingOlder, setLoadingOlder] = useState(false);
// Order-independent oldest boundary: `liveActivities[0]` shifts when the
// reducer re-sorts unsequenced rows on the first live append, which would
// otherwise make a plain append look like a window reshape.
const liveOldestActivityId = useMemo(
() => liveWindowOldestActivityId(liveActivities),
[liveActivities],
);
const liveActivityCount = liveActivities.length;
// Bumps on every reset so a late in-flight load can't repopulate the
// freshly-cleared state (the thread key alone doesn't change on a
// same-thread window reshape).
const generationRef = useRef(0);
// The thread key of an in-flight load — coalesces the duplicate dispatches a
// fast scroll fires before the loading state updates.
const inFlightKeyRef = useRef<string | null>(null);
// The oldest row we've paged past; advances even when a page dedupes to
// nothing. Reset on reshape.
const cursorRef = useRef<OrchestrationThreadActivity | null>(null);
const windowRef = useRef({
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
});
// useLayoutEffect (not useEffect) so the cleared state commits before paint:
// otherwise a thread switch renders one frame with the previous thread's
// lazy-loaded pages still merged in, flashing stale rows.
useLayoutEffect(() => {
const previous = windowRef.current;
windowRef.current = {
key: threadKey,
oldest: liveOldestActivityId,
count: liveActivityCount,
};
if (!didLiveWindowReshape(previous, windowRef.current)) {
return;
}
generationRef.current += 1;
inFlightKeyRef.current = null;
cursorRef.current = null;
setOlderActivities([]);
setOlderLoaded(false);
setOlderHasMore(false);
setLoadingOlder(false);
}, [threadKey, liveOldestActivityId, liveActivityCount]);
const mergedActivities = useMemo(
() => (olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities),
[olderActivities, liveActivities],
);
// Latest merged set, read inside the async load handler so dedup runs
// against current state, not the snapshot captured at dispatch time.
const mergedActivitiesRef = useRef(mergedActivities);
useLayoutEffect(() => {
mergedActivitiesRef.current = mergedActivities;
}, [mergedActivities]);
// Before any page is loaded the server flag is authoritative; afterwards
// the latest page's `hasMore` is.
const hasMoreOlder = olderLoaded ? olderHasMore : threadKey !== null && hasMoreLiveActivities;
const loadOlder = useCallback(() => {
if (threadKey === null || !hasMoreOlder) {
return;
}
const oldest = nextOlderActivitiesCursorRow(cursorRef.current, mergedActivitiesRef.current);
if (!oldest) {
return;
}
if (inFlightKeyRef.current === threadKey) {
return; // a load for this thread is already in flight
}
const cursor = olderActivitiesCursorFor(oldest);
const generation = generationRef.current;
inFlightKeyRef.current = threadKey;
setLoadingOlder(true);
void loadPage(cursor)
.then((page) => {
// The window/thread was reset while this was in flight — drop the page
// so it can't repopulate state cleared by the reset.
if (generationRef.current !== generation) {
return;
}
if (page === null) {
// Failed or interrupted (already surfaced by the caller). Keep
// `hasMore` — the history still exists and retrying is valid.
return;
}
// Advance the cursor even when every row dedupes away — the server
// cursor is strict, so it strictly decreases and paging can't loop.
const pageOldest = page.activities[0];
if (pageOldest) {
cursorRef.current = pageOldest;
}
const fresh = freshOlderActivities(page, mergedActivitiesRef.current);
if (fresh.length > 0) {
setOlderActivities((previous) => [...fresh, ...previous]);
}
setOlderLoaded(true);
setOlderHasMore(page.hasMore);
})
.finally(() => {
if (generationRef.current === generation) {
inFlightKeyRef.current = null;
setLoadingOlder(false);
}
});
}, [threadKey, hasMoreOlder, loadPage]);
return {
mergedActivities: threadKey === null ? EMPTY_ACTIVITIES : mergedActivities,
hasMoreOlder,
loadingOlder,
loadOlder,
};
}
@@ -1,7 +1,7 @@
import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
export function createOrchestrationEnvironmentAtoms<R, E>(
@@ -12,11 +12,6 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
}),
// Imperative lazy-load of older thread activities (infinite scroll-up).
loadThreadActivities: createEnvironmentRpcCommand(runtime, {
label: "environment-data:orchestration:thread-activities",
tag: ORCHESTRATION_WS_METHODS.getThreadActivities,
}),
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:full-thread-diff",
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
@@ -9,25 +9,9 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import type { OrchestrationThread, OrchestrationThreadActivity } from "@t3tools/contracts";
import type { OrchestrationThread } from "@t3tools/contracts";
import {
applyThreadDetailEvent,
liveWindowOldestActivityId,
oldestActivityByChronology,
} from "./threadReducer.ts";
const activity = (id: string, createdAt: string, sequence?: number): OrchestrationThreadActivity =>
({
id,
tone: "tool",
kind: "command",
summary: id,
payload: {},
turnId: TurnId.make("turn-1"),
createdAt,
...(sequence !== undefined ? { sequence } : {}),
}) as unknown as OrchestrationThreadActivity;
import { applyThreadDetailEvent } from "./threadReducer.ts";
const baseEventFields = {
eventId: EventId.make("event-1"),
@@ -713,61 +697,4 @@ describe("applyThreadDetailEvent", () => {
expect(result.kind).toBe("unchanged");
});
});
describe("liveWindowOldestActivityId", () => {
it("returns null for an empty window", () => {
expect(liveWindowOldestActivityId([])).toBeNull();
});
it("returns the chronologically-oldest id regardless of array position", () => {
// Reducer order places the unsequenced legacy row (oldest) LAST while the
// server snapshot would list it first; the helper picks it either way.
const window = [
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
activity("seq-2", "2026-04-01T10:00:02.000Z", 2),
activity("legacy", "2026-04-01T09:00:00.000Z"),
];
expect(liveWindowOldestActivityId(window)).toBe("legacy");
});
it("breaks createdAt ties by id", () => {
const window = [
activity("b", "2026-04-01T10:00:00.000Z", 2),
activity("a", "2026-04-01T10:00:00.000Z", 1),
];
expect(liveWindowOldestActivityId(window)).toBe("a");
});
it("is stable when a newer activity is appended (no false reshape)", () => {
const before = [
activity("legacy", "2026-04-01T09:00:00.000Z"),
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
];
// A live append is the newest activity and is unsequenced in the payload;
// it must not change the detected oldest boundary.
const after = [...before, activity("appended", "2026-04-01T11:00:00.000Z")];
expect(liveWindowOldestActivityId(after)).toBe(liveWindowOldestActivityId(before));
expect(liveWindowOldestActivityId(after)).toBe("legacy");
});
});
describe("oldestActivityByChronology", () => {
it("returns null for an empty set", () => {
expect(oldestActivityByChronology([])).toBeNull();
});
it("returns the unsequenced legacy row so the pagination cursor agrees with the sentinel", () => {
// The reducer placed the legacy (unsequenced, oldest) row at the END; paging
// must cursor from it (createdAt cursor), not from index 0's sequenced row.
const merged = [
activity("seq-5", "2026-04-01T10:00:05.000Z", 5),
activity("seq-6", "2026-04-01T10:00:06.000Z", 6),
activity("legacy", "2026-04-01T09:00:00.000Z"),
];
const oldest = oldestActivityByChronology(merged);
expect(oldest?.id).toBe("legacy");
expect(oldest?.sequence).toBeUndefined(); // → drives the unsequenced cursor
expect(liveWindowOldestActivityId(merged)).toBe(oldest?.id); // sentinel agrees
});
});
});
@@ -35,45 +35,6 @@ const activityOrder = O.combineAll<OrchestrationThreadActivity>([
O.mapInput(O.String, (a) => a.id),
]);
/**
* The oldest activity in a set, by chronology (`createdAt`, then `id`) rather
* than array position.
*
* `activities[0]` is not a stable "oldest": {@link activityOrder} sorts
* unsequenced rows to the end (a missing `sequence` is treated as newest) while
* the server snapshot lists legacy unsequenced rows first, so the first live
* append re-sorts the array and shifts index 0. Both the lazy-load *reshape*
* sentinel ({@link liveWindowOldestActivityId}) and the lazy-load *pagination
* cursor* derive from this so they agree on which row is oldest regardless of
* the reducer's placement of unsequenced rows. Returns `null` when empty.
*/
export function oldestActivityByChronology(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity | null {
let oldest: OrchestrationThreadActivity | null = null;
for (const activity of activities) {
if (
oldest === null ||
activity.createdAt < oldest.createdAt ||
(activity.createdAt === oldest.createdAt && activity.id < oldest.id)
) {
oldest = activity;
}
}
return oldest;
}
/**
* The id of {@link oldestActivityByChronology}, used as the lazy-load reshape
* sentinel (a reconnect re-snapshot or checkpoint revert changes it; a plain
* append does not). Returns `null` when empty.
*/
export function liveWindowOldestActivityId(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): OrchestrationThreadActivity["id"] | null {
return oldestActivityByChronology(activities)?.id ?? null;
}
/**
* Apply a single orchestration event to an `OrchestrationThread`, returning
* the updated thread, a deletion signal, or an "unchanged" marker when the
-48
View File
@@ -25,7 +25,6 @@ import { ProviderInstanceId } from "./providerInstance.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
getTurnDiff: "orchestration.getTurnDiff",
getThreadActivities: "orchestration.getThreadActivities",
getFullThreadDiff: "orchestration.getFullThreadDiff",
replayEvents: "orchestration.replayEvents",
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
@@ -363,10 +362,6 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
activities: Schema.Array(OrchestrationThreadActivity),
// The detail snapshot windows `activities` to the most recent page; this is
// true when older activities exist beyond the window and can be lazy-loaded
// via the getThreadActivities RPC. Absent on lightweight (shell) threads.
hasMoreActivities: Schema.optional(Schema.Boolean),
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
session: Schema.NullOr(OrchestrationSession),
});
@@ -1243,37 +1238,6 @@ export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput
export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
/**
* Cursor-paginated load of a thread's OLDER activities (lazy-load / infinite
* scroll). Sequenced activity uses `beforeSequence`, the `sequence` of the
* oldest activity the client currently holds. Legacy unsequenced activity uses
* the `(beforeCreatedAt, beforeActivityId)` pair from the oldest loaded
* activity. The server returns the page of activities immediately older than the
* cursor (chronological ascending) plus whether any remain beyond that.
*/
export const OrchestrationGetThreadActivitiesInput = Schema.Union([
Schema.Struct({
threadId: ThreadId,
beforeSequence: NonNegativeInt,
limit: Schema.optional(NonNegativeInt),
}),
Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: Schema.optional(NonNegativeInt),
}),
]);
export type OrchestrationGetThreadActivitiesInput =
typeof OrchestrationGetThreadActivitiesInput.Type;
export const OrchestrationGetThreadActivitiesResult = Schema.Struct({
activities: Schema.Array(OrchestrationThreadActivity),
hasMore: Schema.Boolean,
});
export type OrchestrationGetThreadActivitiesResult =
typeof OrchestrationGetThreadActivitiesResult.Type;
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
threadId: ThreadId,
toTurnCount: NonNegativeInt,
@@ -1301,10 +1265,6 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationGetTurnDiffInput,
output: OrchestrationGetTurnDiffResult,
},
getThreadActivities: {
input: OrchestrationGetThreadActivitiesInput,
output: OrchestrationGetThreadActivitiesResult,
},
getFullThreadDiff: {
input: OrchestrationGetFullThreadDiffInput,
output: OrchestrationGetFullThreadDiffResult,
@@ -1351,14 +1311,6 @@ export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<Orche
},
) {}
export class OrchestrationGetThreadActivitiesError extends Schema.TaggedErrorClass<OrchestrationGetThreadActivitiesError>()(
"OrchestrationGetThreadActivitiesError",
{
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect()),
},
) {}
export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
"OrchestrationGetFullThreadDiffError",
{
-12
View File
@@ -52,8 +52,6 @@ import {
OrchestrationGetFullThreadDiffError,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetTurnDiffError,
OrchestrationGetTurnDiffInput,
OrchestrationReplayEventsError,
@@ -614,15 +612,6 @@ export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.g
error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),
});
export const WsOrchestrationGetThreadActivitiesRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getThreadActivities,
{
payload: OrchestrationGetThreadActivitiesInput,
success: OrchestrationRpcSchemas.getThreadActivities.output,
error: Schema.Union([OrchestrationGetThreadActivitiesError, EnvironmentAuthorizationError]),
},
);
export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
{
@@ -764,7 +753,6 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeAuthAccessRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetThreadActivitiesRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationReplayEventsRpc,
WsOrchestrationGetArchivedShellSnapshotRpc,
+24
View File
@@ -406,6 +406,28 @@ export const ServerSignalProcessResult = Schema.Struct({
});
export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
/** Terminal colors parsed from the user's Ghostty theme (hex strings like "#1e1e2e"). */
export const ServerTerminalThemeColors = Schema.Struct({
background: Schema.optional(TrimmedNonEmptyString),
foreground: Schema.optional(TrimmedNonEmptyString),
cursor: Schema.optional(TrimmedNonEmptyString),
selectionBackground: Schema.optional(TrimmedNonEmptyString),
selectionForeground: Schema.optional(TrimmedNonEmptyString),
/** ANSI palette slots 0-15; empty string for slots the theme does not define. */
palette: Schema.optional(Schema.Array(Schema.String)),
});
export type ServerTerminalThemeColors = typeof ServerTerminalThemeColors.Type;
/** Terminal appearance derived from the user's local Ghostty config, when present. */
export const ServerTerminalStyle = Schema.Struct({
/** font-family fallback chain in config order. */
fontFamily: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
fontSize: Schema.optional(Schema.Number),
light: Schema.optional(ServerTerminalThemeColors),
dark: Schema.optional(ServerTerminalThemeColors),
});
export type ServerTerminalStyle = typeof ServerTerminalStyle.Type;
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
auth: ServerAuthDescriptor,
@@ -421,6 +443,8 @@ export const ServerConfig = Schema.Struct({
shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/** Whether thread subscriptions can emit an opt-in catch-up completion marker. */
threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/** Absent when no Ghostty config exists or it cannot be read. */
terminalStyle: Schema.optional(ServerTerminalStyle),
});
export type ServerConfig = typeof ServerConfig.Type;
+8 -80
View File
@@ -6,30 +6,12 @@ settings:
catalogs:
default:
'@effect/openapi-generator':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78
'@effect/tsgo':
specifier: 0.13.2
version: 0.13.2
'@noble/curves':
specifier: 1.9.1
version: 1.9.1
'@noble/hashes':
specifier: 1.8.0
version: 1.8.0
'@pierre/diffs':
specifier: 1.3.0-beta.5
version: 1.3.0-beta.5
'@typescript/native-preview':
specifier: 7.0.0-dev.20260604.1
version: 7.0.0-dev.20260604.1
jose:
specifier: 6.2.2
version: 6.2.2
typescript:
specifier: ~6.0.3
version: 6.0.3
vite-plus:
specifier: 0.2.2
version: 0.2.2
@@ -562,18 +544,15 @@ importers:
'@tanstack/react-router':
specifier: ^1.160.2
version: 1.170.10([email protected]([email protected]))([email protected])
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
effect:
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5)
ghostty-web:
specifier: 0.4.0
version: 0.4.0
jose:
specifier: 'catalog:'
version: 6.2.2
@@ -746,12 +725,6 @@ importers:
'@effect/vitest':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78(patch_hash=42b87cc47e70d74e62496e7a8261b3fd298ecad4464d209348ab04b96f853a5f)([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
'@types/react':
specifier: ~19.2.14
version: 19.2.16
react:
specifier: 19.2.6
version: 19.2.6
vite-plus:
specifier: 'catalog:'
version: 0.2.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])
@@ -3306,56 +3279,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-p4Y/+RYk9Bk5WO+zHSUXAClRmZ2fbJCejMuCAsU2HhyME4jqf6Ftt/mJYEwIah1wGCBDYOB7wEGV1x5bCEZ6hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-By6tRALAZsno0F4zedmtG+wdMvJiJmJoXM4d3+A9zHE4HRXLqXITwRH8mgrlcXc5yJM2g2W3riRPwTYdgemZLQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-skYeG+RgvyzspqVEBsEprL90OYYZfoVNqB3HcCNR6QDJyXKOzfDRT3zncnHmUaFluIlBHuY23mU1b5WGgR98hA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-FFgACrZOXAXUh5KQh2mt1CDOVOZmn+QzHP71wM9QobNwyQvoFfyAeefVUltW83g3sm7LTiH3yfFqLLVUpA5ZFQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-Nm/BAOfQeFiiKd502mZn/GAVKJwtd0RdCg17G3Wz/WSOIQmDi3+7/SZH4BHn1Ye5KvTVH3ua8WvfwLLycNIuvA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BiSy5Ku3mQqyxS6YIqAJgd403wEUWvI7kerfzPxc2l/txZVmZM0pSj7oDM+4bGBExowxOi7o73jEam1W0EDTZg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-BCRkJiotz5s9afLYD2LuMvzAoDYx9H17E/YbDyu4xK7l4zHDPeny9ErSXL//i/nJyaOwRk08x4b8cgJC00+JDg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxfmt/[email protected]':
resolution: {integrity: sha512-4Oaxe1qrGgXfpCJ1C/ERJ2iCtV2rN1R79ga9fsfyVHfSQRu/hVW780u2KDqZWFZ/iGTHODJji0JemxqFZ63eIQ==}
@@ -3458,56 +3423,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-JGHS9Mnr7iWyyLDxgCv1MhzVpAckgptg00F2gnxt/GD7lQ2SW1BRcxHqhSTaSdDpjWRrBkBxMMh4+Hn3aVtExg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-AOYgBZqxNshrg83P9v0RYv+m8s10Cqkj4/PxXFDhcS3k7FqsIG5+CxErshZCIN7G8iy4Y+VGfAsuEdar8AcbBg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-QMybPS5ij3/vrKG67mqzHwW++91sYxK/PPUVi6SBtNCEzW4niS52fVBdXbQ6nou0wWbUPEpx8Sl/ZjtgE3clXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-gOc3W7JV0PXRpIL7stUlLe3Wa9Gp0Kdlup87IT3gHDvPKck2xNgMIl/Gs2lldYY2lyXZDC4rWi3hmoLUobkgbQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-rpGxph+FjjHcYI5q6uxB3Az+tnfmEnDbSA8+PK9ZE/VzyUAkvBOMeuY7ZQMhu5mpZH7YQDsTdW6Cx4kV/msc6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-WND+uhf/Ko13SLqQMWQUgsZuLvYYEvL0ZKgg0tgGYfLqxG7l8Ju123fHDMJyYSDl5E3bUbpFUuii/OvMreFQzw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-SrpbrUL70nG9vh6zP4/oKHWgLuHquwsr7MW9XOn0olBVgh10Uqr8qscKhQoBGEn6olK/IUpn5GSKcdQ5AjUhGA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-qkrsEn6NmgFKr7U/QnezQMb+q/vzAy0Dd9Y95gQGQTyjzDLN+HRZMuM5u70iyH4nBLCfKBzhjMsYCehKay2jyg==}
@@ -4043,7 +4000,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==}
@@ -4057,14 +4013,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==}
@@ -4078,14 +4032,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==}
@@ -4099,14 +4051,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==}
@@ -4120,14 +4070,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==}
@@ -4141,14 +4089,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==}
@@ -4162,7 +4108,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==}
@@ -4622,7 +4567,6 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
@@ -4636,7 +4580,6 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
@@ -4650,7 +4593,6 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
@@ -4664,7 +4606,6 @@ packages:
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -5131,28 +5072,24 @@ packages:
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-YGtvTHT7qP4c5pZmM4kLL78/d8hj2NS150R92cR2SVOW/l9Ilq5R5WrEiMA4k5Ea3B++IJWZT5MRFI0tW9qlcg==}
engines: {node: '>=20.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-FvaMI/vsy4PVM+Qd73K+KM8blfCAfaoZaGaGWNrrlMryhyPThXPnHoB1AQcrKbEAWb+z2fc4zLS4sH+8uI65fw==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-ZsMochHqXqxj2sGTJNJzz3vabppbe4BFgZAjJfsnVzkwR7jv6c5p1BM71LFWxP4qd5LL0TJT7lbeRhALlI44RQ==}
engines: {node: '>=20.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-noBNyJufux0cf18eDpQLOQUZ1Kybfx9zlr+yQ6gAnxMEsQXSvYqZgWymfRDesBE3G/0XB5bg+AUtWijp3TwVcw==}
@@ -5200,12 +5137,6 @@ packages:
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
'@xterm/[email protected]':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
'@yuuang/[email protected]':
resolution: {integrity: sha512-eDYLT0kVBkp7e2BwdRDmt6N1rkeDPUHDefk3ZX0/nok+GLsqfy1WBoSL3Yg7HVXN1EyW8OBVc2uK8Zq8HbmaSA==}
engines: {node: '>= 12'}
@@ -7052,6 +6983,9 @@ packages:
resolution: {integrity: sha512-VilgtJj/ALgGY77fiLam5iD336eSWi96Q15JSAG1zi8NRBysm3LXKdGnHb4m5cuyxvOLQQKWpBZAT6ni4FI2iQ==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-0puDBik2qapbD/QQBW9o5ZHfXnZBqZWx/ctBiVtKZ6ZLds4NYb+wZuw1cRLXZk9zYovIQ908z3rvFhexAvc5Hg==}
[email protected]:
resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
@@ -7678,7 +7612,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-jmUQVx4331m6LIX+0wUhBbmMX7TCfjF5FoOH6SD1CttzuYlGNVpA7QnrmLxrsub43ClTINfGSYyHe2HWeLl5CQ==}
@@ -7699,7 +7632,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==}
@@ -7720,7 +7652,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==}
@@ -7741,7 +7672,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-mSL4rqPi4iXq5YVqzSsJgMVFENoa4nGTT/GjO2c0Yl9OuQfPsIfncvLrEW6RbbB24WtZ3xP/2CCmI3tNkNV4oA==}
@@ -15204,10 +15134,6 @@ snapshots:
'@xmldom/[email protected]': {}
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
'@yuuang/[email protected]':
optional: true
@@ -17529,6 +17455,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: