Compare commits

...
Author SHA1 Message Date
maria-rcks 355a1c5985 fix(server): dedupe codex subagent item events 2026-08-06 22:56:22 -04:00
Theo BrowneandClaude Fable 5 6b73b3defe feat: paginate thread loading with user-anchored turn windows (#5493)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 19:33:49 -07:00
Theo Browne 7aad7911f6 fix(server): let stopped threads settle immediately (#5553) 2026-08-06 18:43:13 -07:00
Theo Browne 6da92244cc fix(web): show one toast when snoozing threads in bulk (#5560) 2026-08-06 18:16:36 -07:00
Theo BrowneandClaude Fable 5 c471145e96 fix(server): stopping a Claude thread no longer shows an ede_diagnostic error (#5557)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:55:20 -07:00
Theo Browne 64a991ad45 fix(web): show remote environment for non-Git projects (#5555) 2026-08-06 17:55:00 -07:00
Theo BrowneandClaude Fable 5 0ec4fbc4a3 fix(server): stop showing commit/push/PR notices as errors in the work log (#5559)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:52:29 -07:00
Theo BrowneandClaude Fable 5 ea50b695a7 fix(web): update tooltip no longer dismisses when scrolling release notes (#5547)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:31:12 -07:00
Theo BrowneandClaude Fable 5 331c6dce7f fix(server): skip origin fetch when creating worktrees in repos without an origin remote (#5556)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 20:13:10 -04:00
Wout Stiens 4f5834ba72 fix(web): clear woke state on explicit thread actions (#5486) 2026-08-06 14:08:35 -04:00
Wout Stiens aa16c180e5 fix(web): align composer inline chips with prompt text (#5495) 2026-08-06 12:57:02 -04:00
Carlos Rico-OspinaandClaude Opus 5 470d4eb993 fix(mobile): stop thread messages reading through pending cards (#5450)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-06 12:56:01 -04:00
t3-code[bot] 99d91ddaa4 fix(acp): keep unknown approvals actionable (#5430)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:31 -04:00
t3-code[bot] ab3b55e29a fix(web): clarify auto permission fallback (#5431)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:00 -04:00
Theo BrowneandClaude Fable 5 e4abc31f1e docs(server): pin interleaved-collapse divergence as intentional with test
Bugbot flagged that clients collapse only adjacent lifecycle rows, so
dropping a superseded update separated by an interleaved parallel call
diverges from full-history rendering. Measured on a real database: 1.5%
of dropped rows (553/36,581), all pure in-flight state whose final result
the retained completion still shows, and zero dropped rows carry a
client-merged payload field their completion lacks (verified across all
49,515 update rows). Documents the tradeoff and adds a test pinning it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo BrowneandClaude Fable 5 b7d1981b57 fix(server): drop superseded tool updates from snapshots
A tool.updated row is the in-flight snapshot of a call; once the call
completes, the tool.completed row carries the final state and both
clients fold every matching update into it. Shipping the updates buys
nothing: 47k such rows exist in one real database, and a single thread
carries 3,291 of them.

Filter them out of thread snapshots, mirroring the existing
context-window dedup. Matching is per turn and only against a LATER
completion, so a revert that discards the completing turn cannot leave
a call unrepresented, and a later update under the same identity (the
next call, still in flight) survives. Live events are untouched.

Rows are matched on the same identity the clients collapse by: an
explicit data.toolCallId when the adapter emits one, otherwise the
itemType/title/detail triple. No tool lifecycle row in the real db
carries a toolCallId, so the fallback does the work.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo Browne 64a3cd6d7d fix(server): separate trial cleanup from handoff retention 2026-08-06 08:09:51 -04:00
Theo Browne 48e2c27f2f fix(web): make update version tooltips accessible 2026-08-06 08:09:51 -04:00
Theo Browne 8b2ea5721a fix(server): order explicit service shutdown 2026-08-06 08:09:51 -04:00
Theo Browne df2f1273e9 fix(server): clean up interrupted update trials 2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 f9e8236899 fix(server): release the tunnel when an explicit stop interrupts an update
A pending update in the launcher state is not proof a replacement
server is coming: `t3 service uninstall` or `systemctl stop` during
the pending window also tears the server down, permanently. The
launcher now writes a stop marker before signalling its child on an
explicit stop and clears it on the next start; the shutdown tunnel
release keeps the tunnel only for pending updates without the marker.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 8f341f20c9 test(server): use the launcher state writer in release tests
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 808d685355 fix(server): keep the managed tunnel across remote update restarts
Measured on a live update: the server was back in ~9s but stayed
unreachable for ~96s, because releasing the tunnel on shutdown forces
the replacement tunnel's hostname route through 1-2 minutes of edge
propagation. An update handoff always brings a server right back
(new version or rollback), so the tunnel is never orphaned; skip the
release when the launcher state file records a pending update. The
next boot respawns the connector from the stored config against the
same tunnel and is reachable as soon as it connects.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 80720ad592 fix(web): calm one-row server update status and banner
The version-skew banner is no longer an amber warning: it reads
"Server update available" with the raw versions (unreadable for
nightlies) moved to a tooltip. The in-flight rail (Download/Install/
Resume) becomes a single status row, "Downloading…" then
"Restarting…", since the wire installing stage is a sub-second
launcher handoff and "resuming" meant nothing to most people.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Hugo Blom a483337a02 fix: respect time format for sidebar snooze (#4438) 2026-08-06 11:40:58 +02:00
Theo BrowneandClaude Fable 5 1ffba7093a fix(web): closed plan sidebar stays closed when returning to a thread (#5484)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:37:27 -07:00
Theo BrowneandClaude Fable 5 3da315e7b5 perf(server): stop shipping full MCP tool results in thread payloads (#5482)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:34:27 -07:00
Theo BrowneandClaude Fable 5 a2ca89aa10 feat: native subagent & workflow observability (#5219)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 00:32:28 -04:00
Theo BrowneandClaude Fable 5 990bb0b689 fix: reconnect faster after remote server updates (#5404)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-05 19:12:52 -07:00
Julius Marminge 7251f1a1f1 Prevent terminal loading flash (#5432) 2026-08-05 23:09:23 +02:00
t3-code[bot] 30e471530b fix(web): preserve terminal font size when splitting (#5444)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-05 17:02:53 -04:00
Julius Marminge de592a00e8 Enrich terminal font previews (#5428) 2026-08-05 16:03:10 +00:00
Wout Stiens 2a04db134c fix(web): keep terminal font settings reliable (#5397) 2026-08-05 13:42:56 +02:00
Theo Browne 37d3667de4 fix(web): keep model picker shortcuts in sync (#5400) 2026-08-05 04:23:18 -07:00
Theo Browne 9697b765e5 fix(ci): isolate releases from shared API rate limits (#5394) 2026-08-05 02:36:10 -07:00
Wout Stiens 9d9a872bcc fix(web): restore terminal link hover styles (#5382) 2026-08-05 11:20:17 +02:00
Wout Stiens 9235c83eb7 fix(web): keep the composer command menu anchored to the composer (#5336) 2026-08-05 11:19:58 +02:00
shivamandT3 Code Test e0c85a20ef fix(mobile): avoid double dividers between thread sections (#5391)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 13:28:10 +05:30
Fllip 3c5bdb84a9 fix(web): truncate long project switcher names (#5348) 2026-08-05 02:03:56 -04:00
shivam 70de6e1786 fix(mobile): prevent Android thread search crash (#5386) 2026-08-05 11:30:10 +05:30
shivamandT3 Code Test 47dfc65265 fix(mobile): preserve grouped project workspaces (#4642)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 10:51:35 +05:30
Theo Browne 41ebf22eea fix(web): clear main branch lint warnings (#5384) 2026-08-04 21:31:39 -07:00
Hwanseo Choi 3d429662c9 fix(mcp): unblock Kimi models in OpenCode with preview tools (#5128) 2026-08-04 23:03:15 -04:00
Theo Browne 7b38fb5c6b fix(server): allow remote updates with database migrations (#5374) 2026-08-04 18:41:56 -07:00
Fllip 7537adc30f fix(web): prevent legacy model picker layout shift (#5349) 2026-08-04 20:05:44 -04:00
Theo Browne 94696b0f54 fix(desktop,web): improve in-app browser shortcuts and URL behavior (#4703) 2026-08-04 17:01:34 -07:00
Theo BrowneandClaude Fable 5 fff6a5b028 feat(web): make pairing QR codes actually scannable, with endpoint choice (#5360)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:53:54 -07:00
Theo BrowneandClaude Fable 5 da6e1a9678 feat(sidebar-v2): thread pinning for sidebar v2 (#5312)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:35:51 -07:00
8eca20005b feat(web): configurable fonts and sizes under Settings → Appearance (#5103)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-05 00:55:06 +02:00
Theo Browne 2fa1fec8d8 refactor(server): make title prompts plaintext (#5368) 2026-08-04 15:51:56 -07:00
Theo Browne 9bd2a4c688 fix(server): keep regenerated titles on topic (#5365) 2026-08-04 15:32:05 -07:00
maria 4fb03aff0b fix(web): better right panel (new diffs styling) (#5260) 2026-08-05 00:00:24 +02:00
Theo Browne d7950ac153 fix(server): generate durable thread titles (#5357) 2026-08-04 14:02:33 -07:00
Theo BrowneandClaude Fable 5 36caf34c68 fix(desktop,web): contain renderer memory growth and recover from renderer OOM crashes (#5148)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 13:37:03 -07:00
Bilal Bakr 90e3778660 fix(web): stop the chat timeline reading through the provider status banner (#5353) 2026-08-04 15:41:07 -04:00
Rushikesh Gaikwad 94331c58ec fix(mobile): show correct provider icons for Grok, Cursor, and OpenCode (#4586) 2026-08-04 11:04:37 -07:00
Arham AminandClaude Opus 4.8 c30a6d9b99 fix(server): scrub AppImage XDG_DATA_DIRS and GSETTINGS_SCHEMA_DIR from terminals (#5075)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:35:10 -04:00
Yukun Shan 37ae1abbe9 fix(ssh): isolate managed tunnel processes (#4347) 2026-08-04 09:34:23 -04:00
Arham AminandClaude Opus 4.8 82b76e2138 fix(server): use a Cursor todo's title when its content is blank (#5073)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:19:12 -04:00
naMqe 8a16cadbaf fix(web): increase tooltip z-index to overlay popovers and menus (#5326) 2026-08-04 09:18:34 -04:00
Julius Marminge 2b1d4fecb8 Upgrade Effect to beta.103 (#5331) 2026-08-04 13:56:50 +02:00
t3-code[bot] cec1bb9de3 fix(web): align multiline error alert controls (#5304) 2026-08-04 13:34:22 +02:00
t3-code[bot] 25ec0b9d13 fix(web): simplify chat code blocks (#5301) 2026-08-04 13:34:10 +02:00
Rodrigo BrechardandRodrigo Brechard 966cc05a90 fix(contracts): decode ServerProviders forward-compatibly (#5327)
Co-authored-by: Rodrigo Brechard <[email protected]>
2026-08-04 13:07:22 +02:00
Wout Stiens 1cbd88aba0 fix(server): strip replayable terminal queries from history (#5319) 2026-08-04 12:52:05 +02:00
Wout Stiens 553867262c fix(terminal): protect held Ctrl/Cmd+W close shortcut (#5322) 2026-08-04 12:51:36 +02:00
Wout StiensandClaude Opus 5 11639bf439 fix(web): blink the terminal cursor again (#5314)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-04 12:50:19 +02:00
t3-code[bot] a261a6440a fix(web): match loading screen to dark theme (#5303) 2026-08-04 00:50:56 +02:00
290 changed files with 19250 additions and 2818 deletions

No files matched your search

+6 -12
View File
@@ -747,15 +747,9 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: write
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
@@ -823,7 +817,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -840,11 +834,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -860,7 +854,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
deploy_web:
name: Deploy hosted web app
+2 -2
View File
@@ -16,7 +16,7 @@ import {
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAnnotationSubmissionResultSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
const keyboardEvent = (
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
) => ({
key: "Enter",
metaKey: false,
ctrlKey: false,
shiftKey: false,
isComposing: false,
...overrides,
});
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
});
});
@@ -0,0 +1,16 @@
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
interface AnnotationKeyboardEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly isComposing: boolean;
}
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
return event.metaKey || event.ctrlKey ? "send" : "attach";
}
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-sanitized-write",
"notifications",
"geolocation",
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
// and silently granting it would hand every page the user's installed-font
// fingerprint (and font file bytes via FontData.blob()). The app's own font
// picker runs in the main window session, which is unaffected by this list.
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
+22
View File
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
});
});
describe("isPreviewRefreshShortcut", () => {
const input = (overrides: Partial<Electron.Input> = {}) =>
({
type: "keyDown",
key: "r",
meta: true,
control: false,
shift: false,
alt: false,
...overrides,
}) as Electron.Input;
it("recognizes the platform refresh chord without matching modified variants", () => {
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
true,
);
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
});
});
const {
browserWindowConstructor,
createFromPath,
+26 -7
View File
@@ -11,6 +11,7 @@ import type {
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
PreviewAnnotationSubmissionResult,
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
@@ -109,7 +110,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -406,6 +407,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
input.type === "keyDown" &&
input.key.toLowerCase() === "r" &&
(input.meta || input.control) &&
!input.shift &&
!input.alt;
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
@@ -1365,6 +1373,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
});
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
if (isPreviewRefreshShortcut(input)) {
event.preventDefault();
runFork(
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
wc.reload(),
).pipe(Effect.ignore),
);
return;
}
runFork(forwardShortcut(event, input));
};
yield* Scope.addFinalizer(
@@ -1792,7 +1809,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
(resume) => {
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
@@ -1807,14 +1824,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
payload: PreviewAnnotationPayload | null,
payload: PreviewAnnotationSubmissionResult | null,
) {
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
const settle = (payload: PreviewAnnotationPayload | null) => {
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
@@ -1844,11 +1861,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
Effect.matchEffect({
onFailure: () => Effect.sync(() => settle(payload)),
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
onSuccess: (screenshot) =>
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
}),
Effect.ensuring(
attempt(
@@ -3586,7 +3605,7 @@ export class PreviewManager extends Context.Service<
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
+14 -7
View File
@@ -11,8 +11,10 @@ import type {
PreviewAnnotationRegionTarget,
PreviewAnnotationStrokeTarget,
PreviewAnnotationStyleChange,
PreviewAnnotationSubmission,
} from "@t3tools/contracts";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
@@ -426,7 +428,7 @@ function startAnnotation(): void {
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot");
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
refreshToolButtons();
};
submit.addEventListener("click", () => {
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
]);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
});
});
comment.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
if (!submission) return;
event.preventDefault();
submit.click();
submitAnnotation(submission);
});
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -20,6 +20,15 @@ const clientSettings: ClientSettings = {
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
fontFamilyCode: "",
fontFamilyComposer: "",
fontFamilySans: "",
fontFamilyTerminal: "",
fontSizeCode: 13,
fontSizeInterface: 16,
fontSizePrompt: 14,
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+53 -4
View File
@@ -1,3 +1,4 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
// that dies on boot cannot reload-loop forever.
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
@@ -514,6 +521,18 @@ export const make = Effect.gen(function* () {
}
});
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
window.webContents.on("before-input-event", (event, input) => {
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
event.preventDefault();
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(environment.displayName);
@@ -537,6 +556,7 @@ export const make = Effect.gen(function* () {
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
let rendererRecoveryTimestamps: number[] = [];
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
@@ -618,10 +638,39 @@ export const make = Effect.gen(function* () {
},
);
window.webContents.on("render-process-gone", (_event, details) => {
void runPromise(
logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
const recoverable =
details.reason === "crashed" ||
details.reason === "oom" ||
details.reason === "abnormal-exit";
// Long sessions can OOM the renderer (V8 heap exhaustion from
// accumulated thread state). Without a reload the user is left staring
// at a dead white window while agents keep running invisibly, so
// recover by reloading — the renderer rehydrates from the backend,
// which is unaffected. Recovery attempts are bounded so a renderer
// that dies immediately on boot cannot reload-loop forever.
runFork(
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
);
const shouldRecover =
recoverable &&
!window.isDestroyed() &&
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
yield* logWindowWarning("main window render process gone", {
reason: details.reason,
exitCode: details.exitCode,
recovering: shouldRecover,
});
if (!shouldRecover) {
return;
}
rendererRecoveryTimestamps.push(now);
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
if (!window.isDestroyed()) {
loadApplication();
}
}),
);
});
+8
View File
@@ -47,6 +47,7 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -175,6 +176,13 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsProjectGrouping: createNativeStackScreen({
screen: SettingsProjectGroupingRouteScreen,
linking: "project-grouping",
options: {
title: "Project Grouping",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
accessibilityRole="button"
hitSlop={8}
onPress={props.onBack}
className="size-11 items-center justify-center"
className="-mr-2 size-11 items-center justify-center"
>
<SymbolView
name="chevron.left"
+4
View File
@@ -50,6 +50,8 @@ import {
IconMinus,
IconNetwork,
IconPalette,
IconPin,
IconPinnedOff,
IconPlayerPlay,
IconPlayerStopFilled,
IconPlus,
@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
magnifyingglass: IconSearch,
paintbrush: IconPalette,
"person.crop.circle": IconUserCircle,
pin: IconPin,
"pin.slash": IconPinnedOff,
play: IconPlayerPlay,
plus: IconPlus,
"qrcode.viewfinder": IconQrcode,
+39 -1
View File
@@ -9,6 +9,7 @@ type ProviderIconProps = {
export function ProviderIcon(props: ProviderIconProps) {
const isDarkMode = useColorScheme() === "dark";
const size = props.size ?? 16;
const mono = isDarkMode ? "#e5e5e5" : "#171717";
if (props.provider === "claudeAgent") {
return (
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
);
}
if (props.provider === "grok") {
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Path
fill={fill}
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
/>
<Path
fill={fill}
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
/>
</Svg>
);
}
if (props.provider === "cursor") {
return (
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
<Path
fill={isDarkMode ? "#EDECEC" : "#26251E"}
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
/>
</Svg>
);
}
if (props.provider === "opencode") {
return (
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
</Svg>
);
}
// codex (and unknown drivers)
return (
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
<Path
fill={isDarkMode ? "#e5e5e5" : "#171717"}
fill={mono}
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
/>
</Svg>
@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
// makes pre-pagination clients discard the record instead of decoding a
// partial thread as complete (rollback safety).
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
@@ -42,6 +42,8 @@ export function HomeRouteScreen() {
settleThread,
snoozeThread,
unsnoozeThread,
pinThread,
unpinThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -155,6 +157,8 @@ export function HomeRouteScreen() {
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
+38 -1
View File
@@ -111,6 +111,8 @@ interface HomeScreenProps {
) => Promise<boolean>;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -516,6 +518,18 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnsnoozeThread],
);
const handlePinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onPinThread(thread);
},
[props.onPinThread],
);
const handleUnpinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnpinThread(thread);
},
[props.onUnpinThread],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -575,6 +589,15 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -671,7 +694,11 @@ export function HomeScreen(props: HomeScreenProps) {
);
const renderV2Item = useCallback(
({ item }: { readonly item: ThreadListV2ListItem }) => {
({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
const nextItem = threadListV2Items[index + 1];
const showTrailingDivider =
nextItem?.type === "v2-thread" ||
(nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
@@ -689,6 +716,7 @@ export function HomeScreen(props: HomeScreenProps) {
: null
}
showPendingDivider={item.showPendingDivider}
showTrailingDivider={showTrailingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
@@ -718,8 +746,10 @@ export function HomeScreen(props: HomeScreenProps) {
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
showTrailingDivider={showTrailingDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -753,9 +783,12 @@ export function HomeScreen(props: HomeScreenProps) {
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
@@ -768,12 +801,15 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
handlePinThread,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
handleUnsnoozeThread,
handleSwipeableClose,
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -784,6 +820,7 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
@@ -31,12 +31,6 @@ export interface ResolvedHomeListOptions extends HomeListOptions {
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
export function resolveProjectGroupingMode(
projectGroupingEnabled: boolean | undefined,
): SidebarProjectGroupingMode {
return projectGroupingEnabled === false ? "separate" : "repository";
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
@@ -76,7 +70,9 @@ const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>
export function HomeListOptionsProvider({
children,
projectGroupingMode,
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
}: PropsWithChildren<{
readonly projectGroupingMode: SidebarProjectGroupingMode;
}>) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
@@ -375,7 +375,7 @@ describe("buildHomeThreadGroups", () => {
).toHaveLength(2);
});
it("uses the repository label for a singleton repository scope", () => {
it("uses the physical project title for a singleton scope", () => {
const project = makeProject({
environmentId: EnvironmentId.make("environment-1"),
id: ProjectId.make("project-1"),
@@ -408,8 +408,8 @@ describe("buildHomeThreadGroups", () => {
],
);
expect(scopes[0]?.title).toBe("codething-mvp");
expect(groups[0]?.title).toBe("codething-mvp");
expect(scopes[0]?.title).toBe("local-worktree-name");
expect(groups[0]?.title).toBe("local-worktree-name");
});
it("sorts the newest thread first regardless of snapshot order", () => {
@@ -565,10 +565,16 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
expect(
buildGroups(projects, threads, { projectGroupingMode: "repository_path" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
expect(
buildGroups(projects, threads, { projectGroupingMode: "separate" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
});
it("default view shows only threads from the last 5 days", () => {
+18 -63
View File
@@ -1,5 +1,5 @@
import {
deriveLogicalProjectKey,
buildProjectGroups,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
@@ -37,10 +37,6 @@ export interface HomeProjectScope {
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
}
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
}
function getProjectSortTimestamp(
project: EnvironmentProject,
sortOrder: HomeProjectSortOrder,
@@ -60,64 +56,19 @@ export function buildHomeProjectScopes(input: {
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
for (const project of projects) {
const physicalKey = derivePhysicalProjectKey(project);
const existing = projectsByPhysicalKey.get(physicalKey);
if (existing) existing.push(project);
else projectsByPhysicalKey.set(physicalKey, [project]);
}
const winnersByPhysicalKey = new Map<
string,
{ readonly key: string; readonly project: EnvironmentProject }
>();
for (const [physicalKey, members] of projectsByPhysicalKey) {
const project = members.reduce((winner, candidate) => {
const freshnessDelta =
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
? candidate
: winner;
});
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
winnersByPhysicalKey.set(physicalKey, {
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
project,
});
}
const groups = new Map<string, EnvironmentProject[]>();
for (const { key, project } of winnersByPhysicalKey.values()) {
const existing = groups.get(key);
if (existing) existing.push(project);
else groups.set(key, [project]);
}
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of projects) {
const refKey = scopedProjectKey(project.environmentId, project.id);
if (seenProjectRefs.has(refKey)) continue;
seenProjectRefs.add(refKey);
const key =
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
const refs = projectRefsByGroup.get(key);
const projectRef = { environmentId: project.environmentId, projectId: project.id };
if (refs) refs.push(projectRef);
else projectRefsByGroup.set(key, [projectRef]);
}
return Array.from(groups, ([key, projects]) => {
const representative = projects[0]!;
return buildProjectGroups({
projects,
settings: {
sidebarProjectGroupingMode: input.projectGroupingMode,
sidebarProjectGroupingOverrides: {},
},
}).map((group) => {
return {
key,
title: deriveProjectGroupLabel({ representative, members: projects }),
representative,
projects,
projectRefs: projectRefsByGroup.get(key) ?? [],
key: group.key,
title: group.label,
representative: group.representative,
projects: group.members.map((member) => member.project),
projectRefs: group.memberProjectRefs,
};
});
}
@@ -264,9 +215,11 @@ export function buildHomeThreadGroups(input: {
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupTitleByKey = new Map<string, string>();
const groupKeyByProjectKey = new Map<string, string>();
for (const scope of buildHomeProjectScopes(input)) {
groupTitleByKey.set(scope.key, scope.title);
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
@@ -345,7 +298,9 @@ export function buildHomeThreadGroups(input: {
continue;
}
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const title =
groupTitleByKey.get(group.key) ??
deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
@@ -29,6 +29,13 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
);
}
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinning === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -202,10 +209,14 @@ export function useThreadListActions(): {
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
@@ -310,6 +321,62 @@ export function useThreadListActions(): {
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
[executeAction],
);
const pinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not pin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not pin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be pinned.",
);
return false;
}
return true;
},
[pinMutation],
);
const unpinThread = useCallback(
async (thread: EnvironmentThreadShell) => {
if (!environmentSupportsPinning(thread.environmentId)) {
Alert.alert(
"Could not unpin thread",
"This environment's server does not support pinning yet. Update the server to use Pin.",
);
return false;
}
selectionHaptic();
const result = await unpinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not unpin thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread could not be unpinned.",
);
return false;
}
return true;
},
[unpinMutation],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
@@ -320,6 +387,8 @@ export function useThreadListActions(): {
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
};
}
@@ -37,11 +37,15 @@ import {
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom } from "../../state/preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import {
parseActiveThreadPath,
useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -190,15 +194,17 @@ export function AdaptiveWorkspaceLayout(props: {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferencesResult)) {
return AsyncResult.isFailure(preferencesResult) ? (
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
/>
) : null;
}
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
return (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={resolveProjectGroupingMode(
preferencesResult.value.projectGroupingEnabled,
)}
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
/>
);
}
@@ -1,15 +1,25 @@
import { ScrollView, View } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
export function SettingsAppearanceRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
@@ -0,0 +1,106 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { useThemeColor } from "../../lib/useThemeColor";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { SettingsSection } from "./components/SettingsSection";
const GROUPING_OPTIONS: ReadonlyArray<{
readonly mode: SidebarProjectGroupingMode;
readonly label: string;
readonly description: string;
}> = [
{
mode: "repository",
label: "Group by repository",
description: "Matching repositories appear as one project.",
},
{
mode: "repository_path",
label: "Group by repository path",
description: "Keep monorepo paths separate.",
},
{
mode: "separate",
label: "Keep separate",
description: "Show every workspace as its own project.",
},
];
export function SettingsProjectGroupingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const checkmarkColor = useThemeColor("--color-icon");
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
const selectedMode = AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode
: null;
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Project Grouping" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-3 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
<SettingsSection title="Default grouping">
{GROUPING_OPTIONS.map((option, index) => (
<Pressable
key={option.mode}
accessibilityRole="radio"
accessibilityState={{
checked: selectedMode === option.mode,
disabled: !preferencesReady,
}}
disabled={!preferencesReady}
onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))}
className={
index === 0
? "flex-row items-center gap-4 p-4"
: "flex-row items-center gap-4 border-t border-border-subtle p-4"
}
>
<View className="min-w-0 flex-1 gap-1">
<Text className="text-lg text-foreground">{option.label}</Text>
<Text className="text-sm leading-normal text-foreground-muted">
{option.description}
</Text>
</View>
{selectedMode === option.mode ? (
<SymbolView
name="checkmark"
size={18}
tintColor={checkmarkColor}
type="monochrome"
weight="semibold"
/>
) : null}
</Pressable>
))}
</SettingsSection>
</ScrollView>
</View>
);
}
@@ -530,20 +530,9 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.projectGroupingEnabled !== false
: true;
return (
<SettingsSection title="General">
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
</SettingsSection>
);
}
@@ -1,4 +1,11 @@
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -54,14 +61,48 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
</Text>
</View>
);
@@ -2,6 +2,7 @@ export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -50,6 +50,7 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function formatWorkspaceLabel(input: {
@@ -89,7 +90,7 @@ export function NewTaskDraftScreen(props: {
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -277,24 +278,25 @@ export function NewTaskDraftScreen(props: {
return;
}
if (selectedProject) {
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
if (selection.kind === "preserve") {
return;
}
if (logicalProjects.length === 1) {
setProject(logicalProjects[0]!.project);
if (selection.kind === "select") {
setProject(selection.project);
return;
}
navigation.dispatch(StackActions.replace("NewTask"));
}, [
logicalProjects,
projectScopes,
projects,
props.initialProjectRef,
props.incomingShareId,
props.pendingTaskId,
navigation,
selectedProject,
selectedProjectKey,
setProject,
]);
@@ -1,8 +1,8 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef } from "react";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useEffect, useRef, useState } from "react";
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -11,12 +11,13 @@ import { cn } from "../../lib/cn";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects, useThreadShells } from "../../state/entities";
import { useProjects } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { useNewTaskFlow } from "./new-task-flow-provider";
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
@@ -79,7 +80,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
const projects = useProjects();
const threads = useThreadShells();
const { projectScopes } = useNewTaskFlow();
const { state: catalogState } = useWorkspaceState();
const navigation = useNavigation();
const isFocused = useIsFocused();
@@ -87,6 +88,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const { getShare, releaseShareReservation } = useIncomingShare();
const routeShareId = Array.isArray(route.params?.incomingShareId)
? route.params.incomingShareId[0]
@@ -100,33 +102,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
: null;
const screenTitle = incomingShare ? "Start a task" : "Choose project";
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(() => {
const nextItems: Array<{
readonly environmentId: EnvironmentId;
readonly id: ProjectId;
readonly key: string;
readonly title: string;
readonly workspaceRoot: string;
}> = [];
for (const group of repositoryGroups) {
const project = group.projects[0]?.project;
if (!project) {
continue;
}
nextItems.push({
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
});
}
return nextItems;
}, [repositoryGroups]);
const projectEmptyState = deriveProjectEmptyState(catalogState);
const resumedDestinationKeyRef = useRef<string | null>(null);
const reservedDestinationProject = incomingShare?.destination
@@ -137,7 +112,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
) ?? null)
: null;
async function selectProject(item: (typeof items)[number]): Promise<void> {
async function selectProject(project: EnvironmentProject): Promise<void> {
if (incomingShare?.destination && !reservedDestinationProject) {
try {
await releaseShareReservation(incomingShare.id, incomingShare.destination);
@@ -154,14 +129,26 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
environmentId: project.environmentId,
projectId: project.id,
title: project.title,
incomingShareId: incomingShare?.id,
},
});
}
function toggleGroup(groupKey: string): void {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (next.has(groupKey)) {
next.delete(groupKey);
} else {
next.add(groupKey);
}
return next;
});
}
useEffect(() => {
const destination = incomingShare?.destination;
if (!destination) {
@@ -251,11 +238,12 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingBottom: 8,
paddingHorizontal: 20,
paddingTop: 8,
}}
>
{items.length === 0 ? (
{projectScopes.length === 0 ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
<Text className="text-center text-lg font-t3-bold text-foreground">
@@ -286,42 +274,89 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
{projectScopes.map((scope, scopeIndex) => {
const hasMultipleProjects = scope.projects.length > 1;
const expanded = expandedGroupKeys.has(scope.key);
const singleProject = hasMultipleProjects ? null : scope.projects[0];
return (
<Pressable
key={item.key}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(item)}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
isFirst && "rounded-t-[24px]",
isLast && "rounded-b-[24px]",
)}
<View
key={scope.key}
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
>
<View className="flex-row items-center justify-between gap-3">
<Pressable
disabled={singleProject !== null && reservedDestinationProject !== null}
onPress={() => {
if (singleProject) {
void selectProject(singleProject);
} else {
toggleGroup(scope.key);
}
}}
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
>
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={item.environmentId}
environmentId={scope.representative.environmentId}
size={20}
projectTitle={item.title}
workspaceRoot={item.workspaceRoot}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
/>
</View>
<View className="flex-1">
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
<View className="min-w-0 flex-1">
<Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
<Text
className="text-xs leading-snug text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{hasMultipleProjects
? `${scope.projects.length} workspaces`
: singleProject?.workspaceRoot}
</Text>
</View>
<SymbolView
name="chevron.right"
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</Pressable>
{hasMultipleProjects && expanded
? scope.projects.map((project) => (
<Pressable
key={scopedProjectKey(project.environmentId, project.id)}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(project)}
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
>
<ProjectFavicon
environmentId={project.environmentId}
size={18}
projectTitle={project.title}
workspaceRoot={project.workspaceRoot}
/>
<View className="min-w-0 flex-1">
<Text className="text-sm font-t3-bold text-foreground">
{project.title}
</Text>
<Text
className="text-xs text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{project.workspaceRoot}
</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</Pressable>
))
: null}
</View>
);
})}
</View>
@@ -14,8 +14,10 @@ export interface PendingApprovalCardProps {
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
// behind this card, so a translucent surface bleeds messages through it.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -24,8 +24,11 @@ export interface PendingUserInputCardProps {
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
// The surface is opaque on purpose: the card floats over the thread feed
// with no blur behind it, so a translucent background renders the questions
// on top of whatever message happens to sit underneath.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -61,6 +61,8 @@ export interface ThreadDetailScreenProps {
readonly connectionStateLabel: EnvironmentConnectionPhase;
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
@@ -371,6 +373,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
) : (
@@ -164,6 +164,11 @@ export interface ThreadFeedProps {
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
readonly loading: boolean;
readonly onLoadEarlier: () => void;
} | null;
}
function MessageAttachmentImage(props: {
@@ -1893,7 +1898,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
<>
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
{props.loadEarlier != null ? (
<Pressable
onPress={props.loadEarlier.onLoadEarlier}
disabled={props.loadEarlier.loading}
className="items-center py-2"
>
<Text className="text-xs text-foreground-secondary">
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
</Text>
</Pressable>
) : null}
</>
}
contentContainerStyle={{
paddingTop: 12,
@@ -205,6 +205,8 @@ function ThreadNavigationSidebarPane(
snoozeThread,
unsnoozeThread,
unsettleThread,
pinThread,
unpinThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -481,6 +483,15 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const pinningEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinning === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -792,6 +803,7 @@ function ThreadNavigationSidebarPane(
previous.item.thread === item.item.thread &&
previous.item.variant === item.item.variant &&
previous.item.snoozed === item.item.snoozed &&
previous.item.pinned === item.item.pinned &&
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
);
}
@@ -879,6 +891,7 @@ function ThreadNavigationSidebarPane(
thread={thread}
variant={item.item.variant}
snoozed={item.item.snoozed}
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
project={projectByKey.get(scopeKey) ?? null}
@@ -915,9 +928,12 @@ function ThreadNavigationSidebarPane(
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
@@ -1045,6 +1061,8 @@ function ThreadNavigationSidebarPane(
handleSwipeableClose,
handleSwipeableWillOpen,
openPendingTask,
pinThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
@@ -1064,6 +1082,7 @@ function ThreadNavigationSidebarPane(
nowMinute,
toggleSettledShelf,
toggleSnoozedShelf,
unpinThread,
unsettleThread,
unsnoozeThread,
updateGroupDisplay,
@@ -8,6 +8,10 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -190,6 +194,20 @@ function ThreadRouteContent(
useThreadSelection();
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
// "Load earlier turns" header state for windowed (paginated) thread loads.
const loadEarlierTurns = useMemo(() => {
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
return null;
}
return {
loading:
selectedThreadDetailState.page._tag === "Some" &&
selectedThreadDetailState.page.value.loadingOlder,
onLoadEarlier: () => {
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
},
};
}, [selectedThread, selectedThreadDetailState]);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
@@ -766,6 +784,7 @@ function ThreadRouteContent(
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
loadEarlier={loadEarlierTurns}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
@@ -27,7 +27,6 @@ import {
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import {
@@ -59,6 +58,12 @@ import {
} from "../../state/use-remote-environment-registry";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
import {
buildHomeProjectScopes,
sortHomeProjectScopes,
type HomeProjectScope,
} from "../home/homeThreadList";
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
type WorkspaceMode = "local" | "worktree";
@@ -109,10 +114,7 @@ export function branchBadgeLabel(input: {
}
type NewTaskFlowContextValue = {
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
readonly project: EnvironmentProject;
}>;
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
@@ -175,32 +177,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const logicalProjects = useMemo(
const groupingSettings = useMobileProjectGroupingSettings();
const projectScopes = useMemo(
() =>
pipe(
repositoryGroups,
Arr.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return { key: group.key, project: primaryProject };
sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
}),
Arr.filter(
(
entry,
): entry is {
readonly key: string;
readonly project: EnvironmentProject;
} => entry !== null,
),
),
[repositoryGroups],
threads,
pendingTasks: [],
projectSortOrder: "updated_at",
}),
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
);
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
@@ -846,7 +836,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const value = useMemo<NewTaskFlowContextValue>(
() => ({
logicalProjects,
projectScopes,
selectedEnvironmentId,
selectedProjectKey,
selectedModelKey,
@@ -912,7 +902,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
finishEditingPendingTask,
interactionMode,
loadBranches,
logicalProjects,
projectScopes,
modelOptions,
prompt,
providerGroups,
@@ -0,0 +1,82 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import type { HomeProjectScope } from "../home/homeThreadList";
import {
getOnlySelectableProject,
resolveDraftProjectSelection,
} from "./new-task-project-selection";
function makeProject(id: string): EnvironmentProject {
return {
environmentId: EnvironmentId.make("environment"),
id: ProjectId.make(id),
title: id,
workspaceRoot: `/work/${id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-01T00:00:00.000Z",
updatedAt: "2026-07-01T00:00:00.000Z",
};
}
function makeScope(projects: ReadonlyArray<EnvironmentProject>): HomeProjectScope {
return {
key: "github.com/t3tools/t3code",
title: "T3 Code",
representative: projects[0]!,
projects,
projectRefs: projects.map((project) => ({
environmentId: project.environmentId,
projectId: project.id,
})),
};
}
describe("getOnlySelectableProject", () => {
it("auto-selects when there is exactly one physical project", () => {
const project = makeProject("t3code");
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
});
it("does not auto-select a representative when one group has multiple clones", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
});
});
describe("resolveDraftProjectSelection", () => {
it("preserves an explicit project selection", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:t3code", [project], [makeScope([project])]),
).toEqual({ kind: "preserve" });
});
it("selects the only physical project when no project was explicitly selected", () => {
const project = makeProject("t3code");
expect(resolveDraftProjectSelection(null, [project], [makeScope([project])])).toEqual({
kind: "select",
project,
});
});
it("opens the picker for multiple physical projects in one logical group", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
kind: "pick",
});
});
it("does not preserve a project key that is missing from the catalog", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:removed", [project], [makeScope([project])]),
).toEqual({
kind: "select",
project,
});
});
});
@@ -0,0 +1,34 @@
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { HomeProjectScope } from "../home/homeThreadList";
export type DraftProjectSelectionResolution =
| { readonly kind: "preserve" }
| { readonly kind: "select"; readonly project: EnvironmentProject }
| { readonly kind: "pick" };
export function getOnlySelectableProject(
projectScopes: ReadonlyArray<HomeProjectScope>,
): EnvironmentProject | null {
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
}
export function resolveDraftProjectSelection(
selectedProjectKey: string | null,
projects: ReadonlyArray<EnvironmentProject>,
projectScopes: ReadonlyArray<HomeProjectScope>,
): DraftProjectSelectionResolution {
const hasExplicitProjectSelection =
selectedProjectKey !== null &&
projects.some(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
);
if (hasExplicitProjectSelection) {
return { kind: "preserve" };
}
const onlyProject = getOnlySelectableProject(projectScopes);
return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };
}
@@ -204,6 +204,8 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}) {
@@ -291,7 +293,9 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
</View>
)}
</Pressable>
@@ -305,6 +309,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows its wake time and offers Wake. */
readonly snoozed?: boolean;
/** Pinned-block row: shows the pin glyph and offers Unpin. */
readonly pinned?: boolean;
/** Preformatted against the parent minute tick so this memoized row's
countdown keeps moving. */
readonly snoozeWakeLabelText?: string;
@@ -325,6 +331,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
into the drawer surface, selection filled with the accent color —
matching the v1 sidebar rows. */
readonly pane?: "screen" | "sidebar";
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
/** Highlights the thread open in the detail pane (iPad split view). The
compact Home list never sets it — phones navigate away on select. */
readonly selected?: boolean;
@@ -337,11 +345,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;
/** False on environments whose server predates thread.settle/unsettle:
swipe + menu fall back to Archive instead of failing on use. */
readonly settlementSupported: boolean;
/** False on servers that predate thread.snooze/unsnooze. */
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -368,9 +380,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onUnsnoozeThread,
onUnsettleThread,
onArchiveThread,
onPinThread,
onUnpinThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pinnedRow = props.pinned === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
@@ -383,6 +398,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const drawerColor = useThemeColor("--color-drawer");
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const pinTintColor = useThemeColor("--color-foreground-muted");
const sidebarPane = props.pane === "sidebar";
const selected = props.selected === true;
@@ -398,6 +414,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
);
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
@@ -434,6 +452,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
})),
[snoozePresets],
);
// Pinned cards keep the full lifecycle menu; only the pin item flips to
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
// hides the card until wake with the pin intact.)
const pinMenuItem = useMemo<MenuAction[]>(
() =>
props.pinningSupported
? [
pinnedRow
? { id: "unpin", title: "Unpin", image: "pin.slash" }
: { id: "pin", title: "Pin", image: "pin" },
]
: [],
[pinnedRow, props.pinningSupported],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -443,15 +475,22 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
image: "clock",
subactions: snoozePresetActions,
},
...pinMenuItem,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[snoozePresetActions],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "settle") handleSettle();
if (nativeEvent.event === "unsettle") handleUnsettle();
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "pin") handlePin();
if (nativeEvent.event === "unpin") handleUnpin();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
@@ -468,8 +507,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handlePin,
handleSettle,
handleSnooze,
handleUnpin,
handleUnsettle,
handleUnsnooze,
snoozePresets,
@@ -560,6 +601,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
>
{props.projectTitle ?? props.project?.title ?? ""}
</Text>
{pinnedRow ? (
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
) : null}
<Text
className={cn(
"text-xs tabular-nums",
@@ -690,7 +734,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
actions reveal behind the row. */
<View className="bg-screen">
<View className="px-5 py-2.5">{cardContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
</View>
)}
</Pressable>
@@ -805,7 +851,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: CARD_MENU_ACTIONS
: cardMenuActions
}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
@@ -288,6 +288,57 @@ describe("buildThreadListV2Items", () => {
expect(layout.snoozedCount).toBe(1);
});
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-settled"),
title: "Pinned while settled",
pinnedAt: "2026-06-01T12:00:00.000Z",
// Stale settled state (the decider clears it on pin): the pin wins.
settledOverride: "settled",
settledAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
expect(layout.items.map((item) => item.pinned)).toEqual([true, false]);
expect(layout.settledCount).toBe(0);
});
it("snooze hides a pinned thread and wake restores it to the pinned block", () => {
const snoozedInput = {
threads: [
makeThread({ id: ThreadId.make("active"), title: "Active" }),
makeThread({
id: ThreadId.make("pinned-snoozed"),
title: "Pinned and snoozed",
pinnedAt: "2026-06-01T12:00:00.000Z",
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T11:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
};
// Before the wake time: the snooze wins; the pin holds underneath.
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(whileSnoozed.snoozedCount).toBe(1);
// After the wake time: the thread returns pinned, back on top.
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" });
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
expect(afterWake.items[0]?.pinned).toBe(true);
expect(afterWake.snoozedCount).toBe(0);
});
it("classifies snooze with the second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -180,6 +180,8 @@ export interface ThreadListV2Item {
readonly variant: "card" | "slim";
/** Snoozed-shelf row: shows the wake countdown and offers Wake. */
readonly snoozed: boolean;
/** Pinned-block row: renders the pin glyph and offers Unpin. */
readonly pinned: boolean;
readonly isLast: boolean;
}
@@ -351,6 +353,7 @@ export function buildThreadListV2Items(input: {
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
: null;
const pinned: EnvironmentThreadShell[] = [];
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
@@ -378,9 +381,10 @@ export function buildThreadListV2Items(input: {
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: a snoozed thread leaves the list until it
// wakes (or raises its hand — effectiveSnoozed refuses blocked/failed
// work). Snooze outranks settled classification, same as web.
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -392,6 +396,12 @@ export function buildThreadListV2Items(input: {
}
continue;
}
// A pin otherwise overrides the lifecycle: pinned threads render above
// the inbox and never auto-settle out of sight.
if (thread.pinnedAt != null) {
pinned.push(thread);
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
@@ -434,11 +444,21 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortThreadsForListV2(pinned)) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: true,
isLast: false,
});
}
for (const thread of orderedActive) {
items.push({
thread,
variant: "card",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -448,6 +468,7 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: true,
pinned: false,
isLast: false,
});
}
@@ -457,6 +478,7 @@ export function buildThreadListV2Items(input: {
thread,
variant: "slim",
snoozed: false,
pinned: false,
isLast: false,
});
}
@@ -1,192 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { groupProjectsByRepository } from "./repositoryGroups";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
): EnvironmentThreadShell {
return {
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
describe("groupProjectsByRepository", () => {
it("groups projects across environments by repository identity", () => {
const repoIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
};
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
makeProject({
environmentId: EnvironmentId.make("env-staging"),
id: ProjectId.make("project-staging"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-staging"),
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-staging"),
title: "Fix reconnect flow",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-local"),
title: "Polish mobile shell",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-03T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups).toHaveLength(1);
expect(groups[0]).toMatchObject({
key: "github.com/t3tools/t3code",
title: "T3 Code",
subtitle: "t3tools/t3code",
projectCount: 2,
threadCount: 2,
});
expect(
groups[0]?.projects.map((entry) => ({
environmentId: entry.project.environmentId,
latestActivityAt: entry.latestActivityAt,
threads: entry.threads.map((thread) => thread.id),
})),
).toEqual([
{
environmentId: "env-local",
latestActivityAt: "2026-04-03T12:00:00.000Z",
threads: ["thread-1"],
},
{
environmentId: "env-staging",
latestActivityAt: "2026-04-02T12:00:00.000Z",
threads: ["thread-2"],
},
]);
expect(groups[0]?.latestActivityAt).toBe("2026-04-03T12:00:00.000Z");
});
it("orders threads, projects, and repository groups by latest activity", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("older-project"),
title: "Older",
}),
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("newer-project"),
title: "Newer",
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("older-thread"),
projectId: ProjectId.make("older-project"),
title: "Older thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newer-thread"),
projectId: ProjectId.make("older-project"),
title: "Newer thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-04T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newest-thread"),
projectId: ProjectId.make("newer-project"),
title: "Newest thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-05T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups.map((group) => group.title)).toEqual(["Newer", "Older"]);
expect(groups[1]?.projects[0]?.threads.map((thread) => thread.id)).toEqual([
"newer-thread",
"older-thread",
]);
});
it("falls back to a scoped project key when repository identity is unavailable", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "Scratchpad",
}),
];
const groups = groupProjectsByRepository({ projects, threads: [] });
expect(groups).toHaveLength(1);
expect(groups[0]?.key).toBe("env-local:project-local");
expect(groups[0]?.title).toBe("Scratchpad");
expect(groups[0]?.subtitle).toBeNull();
});
});
-131
View File
@@ -1,131 +0,0 @@
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { RepositoryIdentity } from "@t3tools/contracts";
import { scopedProjectKey } from "./scopedEntities";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
const DateDescending = Order.flip(Order.Date);
export interface RepositoryProjectGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly latestActivityAt: string;
}
export interface RepositoryGroup {
readonly key: string;
readonly title: string;
readonly subtitle: string | null;
readonly repositoryIdentity: RepositoryIdentity | null;
readonly projectCount: number;
readonly threadCount: number;
readonly latestActivityAt: string;
readonly projects: ReadonlyArray<RepositoryProjectGroup>;
}
function compareIsoDateDescending(left: string, right: string): number {
return new Date(right).getTime() - new Date(left).getTime();
}
function deriveRepositoryGroupKey(project: EnvironmentProject): string {
return (
project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
);
}
function deriveRepositoryTitle(project: EnvironmentProject): string {
const identity = project.repositoryIdentity;
return identity?.displayName ?? identity?.name ?? project.title;
}
function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null {
if (!identity) {
return null;
}
if (identity.owner && identity.name) {
return `${identity.owner}/${identity.name}`;
}
return identity.canonicalKey;
}
function deriveProjectLatestActivity(
project: EnvironmentProject,
threads: ReadonlyArray<EnvironmentThreadShell>,
): string {
const latestThread = threads[0];
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
export function groupProjectsByRepository(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}): ReadonlyArray<RepositoryGroup> {
const threadsByProjectKey = new Map<string, EnvironmentThreadShell[]>();
for (const thread of input.threads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = threadsByProjectKey.get(key);
if (existing) {
existing.push(thread);
} else {
threadsByProjectKey.set(key, [thread]);
}
}
const grouped = new Map<string, RepositoryGroup>();
for (const project of input.projects) {
const key = deriveRepositoryGroupKey(project);
const projectKey = scopedProjectKey(project.environmentId, project.id);
const threads = Arr.sortWith(
threadsByProjectKey.get(projectKey) ?? [],
(s) => new Date(s.updatedAt ?? s.createdAt),
DateDescending,
);
const latestActivityAt = deriveProjectLatestActivity(project, threads);
const projectGroup: RepositoryProjectGroup = {
key: projectKey,
project,
threads,
latestActivityAt,
};
const existing = grouped.get(key);
if (!existing) {
grouped.set(key, {
key,
title: deriveRepositoryTitle(project),
subtitle: deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: project.repositoryIdentity ?? null,
projectCount: 1,
threadCount: threads.length,
latestActivityAt,
projects: [projectGroup],
});
continue;
}
grouped.set(key, {
...existing,
title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project),
subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null,
projectCount: existing.projectCount + 1,
threadCount: existing.threadCount + threads.length,
latestActivityAt:
compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
? latestActivityAt
: existing.latestActivityAt,
projects: Arr.sortWith(
[...existing.projects, projectGroup],
(s) => new Date(s.latestActivityAt),
DateDescending,
),
});
}
return Arr.sortWith(grouped.values(), (s) => new Date(s.latestActivityAt), DateDescending);
}
@@ -532,3 +532,39 @@ describe("buildThreadFeed", () => {
});
});
});
describe("quiet timeline: nested agents", () => {
it("keeps a nested agent's terminal row but hides its background work", () => {
const thread = makeThread({
id: ThreadId.make("thread-nested"),
projectId: ProjectId.make("project-1"),
title: "Nested agents",
activities: [
// A subagent's own shell: internal, covered by the owner's liveness.
makeActivity({
id: EventId.make("shell-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:02.000Z",
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
}),
// A nested AGENT's completion: mobile has no Agents sheet, so this
// terminal row is the only signal it ever finished.
makeActivity({
id: EventId.make("nested-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:03.000Z",
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
}),
],
});
const feed = buildThreadFeed(thread);
const ids = feed.flatMap((entry) =>
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
);
expect(ids).toContain("nested-done");
expect(ids).not.toContain("shell-done");
});
});
+93 -1
View File
@@ -80,6 +80,8 @@ interface WorkLogEntry {
interface DerivedWorkLogEntry extends WorkLogEntry {
activityKind: OrchestrationThreadActivity["kind"];
collapseKey?: string;
/** Grouping key for subagent lifecycle rows (one row per agent). */
taskId?: string;
}
type RawThreadFeedEntry =
@@ -235,6 +237,63 @@ function resolvePendingUserInputAnswer(
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
* task.completed — these rows are mobile's only terminal signal for them. */
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
"idle",
"completed",
"failed",
"cancelled",
"interrupted",
]);
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "task.updated") {
return false;
}
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
return (
payload?.timelineBypass === true &&
typeof payload.status === "string" &&
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
);
}
/**
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
* activity lives in the Agents sheet, not the work log. Terminal rows are
* kept — with no Agents surface on mobile they are the terminal signal
* (a surface that hides rows must keep its own terminal signal). That means
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
* children never emit task.completed — review finding).
*/
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
if (!payload) {
return false;
}
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
if (payload.timelineBypass === true && !isTerminalTaskRow) {
return true;
}
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
// the only signal mobile gets (no Agents sheet), so it stays. Only an
// agent's own background work (stamped "background") is internal — same
// rule as web (review finding: hiding on agentId alone dropped nested
// completions with no replacement UI).
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
if (!ownedByAgent) {
return false;
}
return !(isTerminalTaskRow && payload.agentKind === "agent");
}
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): DerivedWorkLogEntry[] {
@@ -243,9 +302,13 @@ function deriveWorkLogEntries(
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
// Terminal bypassed updates pass: Codex children's only terminal signal.
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
if (activity.kind === "tool.progress") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
if (isAgentInternalActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries);
@@ -271,7 +334,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
const commandPreview = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
// task.updated included: terminal bypassed updates (Codex children's only
// terminal signal) must carry task identity so they collapse per child
// instead of stacking anonymous "Task idle" rows.
const isTaskActivity =
activity.kind === "task.progress" ||
activity.kind === "task.completed" ||
activity.kind === "task.updated";
const taskSummary =
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
? payload.summary
@@ -284,10 +353,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
? payload.detail
: null;
const taskLabel = taskSummary || taskDetailAsLabel;
const taskId =
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
? payload.taskId
: undefined;
const entry: DerivedWorkLogEntry = {
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
...(taskId ? { taskId } : {}),
label: taskLabel || activity.summary,
tone:
activity.kind === "task.progress"
@@ -352,7 +426,25 @@ function collapseDerivedWorkLogEntries(
entries: ReadonlyArray<DerivedWorkLogEntry>,
): DerivedWorkLogEntry[] {
const collapsed: DerivedWorkLogEntry[] = [];
// Subagent rows collapse by identity, not adjacency (quiet-timeline
// guarantee; mirrors web's session-logic).
const taskRowIndex = new Map<string, number>();
for (const entry of entries) {
const isTaskRow =
entry.taskId !== undefined &&
(entry.activityKind === "task.progress" ||
entry.activityKind === "task.completed" ||
entry.activityKind === "task.updated");
if (isTaskRow && entry.taskId !== undefined) {
const existingIndex = taskRowIndex.get(entry.taskId);
if (existingIndex !== undefined) {
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
continue;
}
taskRowIndex.set(entry.taskId, collapsed.length);
collapsed.push(entry);
continue;
}
const previous = collapsed.at(-1);
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
@@ -5,6 +5,7 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import * as MobileDatabase from "./mobile-database";
import * as MobileSecureStorage from "./mobile-secure-storage";
@@ -22,7 +23,9 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted out of per
@@ -80,6 +83,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
} = {};
@@ -110,6 +114,13 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
if (
parsed.projectGroupingMode === "repository" ||
parsed.projectGroupingMode === "repository_path" ||
parsed.projectGroupingMode === "separate"
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
@@ -0,0 +1,33 @@
import type { ProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { Preferences } from "../persistence/mobile-preferences";
export const DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS: ProjectGroupingSettings = {
sidebarProjectGroupingMode: "repository",
sidebarProjectGroupingOverrides: {},
};
export function resolveMobileProjectGroupingSettings(
preferences: Preferences,
): ProjectGroupingSettings {
return {
sidebarProjectGroupingMode:
preferences.projectGroupingMode ??
(preferences.projectGroupingEnabled === false ? "separate" : "repository"),
sidebarProjectGroupingOverrides: {},
};
}
/**
* Dual-writes the legacy boolean for one release so an OTA rollback to an
* older mobile bundle preserves the user's grouping choice.
*/
export function mobileProjectGroupingModePatch(
mode: SidebarProjectGroupingMode,
): Partial<Preferences> {
return {
projectGroupingMode: mode,
projectGroupingEnabled: mode !== "separate",
};
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vite-plus/test";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
describe("mobile project grouping preferences", () => {
it("maps the legacy boolean while preferring the new mode", () => {
expect(resolveMobileProjectGroupingSettings({}).sidebarProjectGroupingMode).toBe("repository");
expect(
resolveMobileProjectGroupingSettings({ projectGroupingEnabled: false })
.sidebarProjectGroupingMode,
).toBe("separate");
expect(
resolveMobileProjectGroupingSettings({
projectGroupingEnabled: false,
projectGroupingMode: "repository_path",
}).sidebarProjectGroupingMode,
).toBe("repository_path");
});
it("dual-writes the legacy boolean for rollback compatibility", () => {
expect(mobileProjectGroupingModePatch("separate")).toEqual({
projectGroupingMode: "separate",
projectGroupingEnabled: false,
});
expect(mobileProjectGroupingModePatch("repository_path")).toEqual({
projectGroupingMode: "repository_path",
projectGroupingEnabled: true,
});
});
});
+17
View File
@@ -0,0 +1,17 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { mobilePreferencesAtom } from "./preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
export * from "./project-grouping.logic";
export function useMobileProjectGroupingSettings() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value)
: DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS;
}
@@ -50,6 +50,7 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityRe
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
@@ -305,7 +306,7 @@ export const makeOrchestrationIntegrationHarness = (
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusTest,
);
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
+2
View File
@@ -22,6 +22,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
*/
export const RPC_REQUIRED_SCOPES = {
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
@@ -75,6 +76,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,
[WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
[WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
+6 -2
View File
@@ -1,3 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
@@ -56,8 +58,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
const encoded = yield* encodeDesktopBootstrap(payload);
yield* fs.writeFileString(filePath, `${encoded}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
return yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
});
it.effect("falls back to effect/config values when flags are omitted", () =>
+1 -1
View File
@@ -466,7 +466,7 @@ export const DurationFromString = Schema.String.pipe(
return Effect.succeed(duration);
}
return Effect.fail(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
}),
);
+10
View File
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Terminal from "effect/Terminal";
import * as BootService from "../cloud/bootService.ts";
import {
acquireRelayClientForLink,
formatHeadlessAuthorizationPrompt,
@@ -63,6 +64,15 @@ it.effect("treats cancelling optional background setup as a successful skip", ()
}),
);
it.effect("keeps a successful connection when a remote service update is pending", () =>
Effect.gen(function* () {
const result = yield* recoverServiceOnboardingOffer(
Effect.fail(new BootService.BootServiceUpdatePendingError()),
);
assert.isFalse(result);
}),
);
it.effect("does not install the relay client when the user declines the managed download", () =>
Effect.gen(function* () {
let installCalls = 0;
+2
View File
@@ -185,6 +185,8 @@ export const recoverServiceOnboardingOffer = <R>(
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceInstallError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceUpdatePendingError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
+47 -7
View File
@@ -15,7 +15,11 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ProcessRunner from "../processRunner.ts";
import * as BootService from "./bootService.ts";
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
import { parseServiceState } from "./serviceProtocol.ts";
import {
parseServiceState,
SERVICE_LAUNCHER_PROTOCOL,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
const unit = BootService.renderBootServiceUnit({
@@ -27,7 +31,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
});
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
expect(unit).toContain("KillMode=control-group");
expect(unit).toContain("KillMode=mixed");
expect(unit).not.toContain("versions/1.2.3");
});
@@ -97,15 +101,24 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
yield* fs.writeFileString(
statePath,
'{"protocol":1,"activeVersion":"1.2.3","update":{"id":"u","fromVersion":"1.2.3","targetVersion":"1.2.4","status":"pending"}}',
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
update: {
id: "u",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
expect((yield* service.status).current).toBe(false);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
@@ -141,6 +154,33 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("restarts without overwriting a pending remote update", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness();
yield* service.install;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
"systemctl --user stop t3code.service",
"systemctl --user restart t3code.service",
]);
}),
);
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("darwin");
+24 -2
View File
@@ -21,6 +21,7 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
serviceStateHasPendingUpdate,
type ServiceState,
} from "./serviceProtocol.ts";
@@ -63,7 +64,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
"KillMode=control-group",
// Let the launcher mark an explicit stop before it signals the server.
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
"KillMode=mixed",
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
@@ -110,10 +113,20 @@ export class BootServiceInstallError extends Schema.TaggedErrorClass<BootService
}
}
export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
"BootServiceUpdatePendingError",
{},
) {
override get message(): string {
return "A remote server update is still pending. Wait for it to finish, then retry.";
}
}
export type BootServiceError =
| BootServiceUnsupportedError
| BootServiceCommandError
| BootServiceInstallError;
| BootServiceInstallError
| BootServiceUpdatePendingError;
export interface BootServiceStatus {
readonly supported: boolean;
@@ -288,6 +301,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
yield* Effect.gen(function* () {
if (installed) {
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
if (
Option.isSome(previousStateText) &&
serviceStateHasPendingUpdate(previousStateText.value)
) {
return yield* new BootServiceUpdatePendingError();
}
}
yield* fs
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
+115
View File
@@ -1,7 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Tracer from "effect/Tracer";
import {
@@ -15,6 +18,14 @@ import { EnvironmentId } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfigModule from "../config.ts";
import { writeServiceState } from "../serviceLauncher.ts";
import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
type ServiceUpdateRecord,
} from "./serviceProtocol.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
@@ -24,6 +35,7 @@ import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
@@ -256,6 +268,23 @@ describe("releaseManagedTunnelOnShutdown", () => {
readonly respond?: () => Response;
}
// Writes the launcher's durable state file into this test's baseDir with
// the launcher's own writer; the release reads it to detect an in-flight
// update handoff.
const writeLauncherState = (update: ServiceUpdateRecord) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "0.0.30",
update,
}),
);
});
const provideReleaseHarness =
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
@@ -306,6 +335,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
}),
),
),
// The release consults the launcher state file under the configured
// baseDir, so every harness run gets a scoped temp baseDir.
Effect.provide(
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
Layer.provideMerge(NodeServices.layer),
),
),
Effect.scoped,
);
// The persisted state of a CLI-managed link whose tunnel is releasable.
@@ -390,6 +427,84 @@ describe("releaseManagedTunnelOnShutdown", () => {
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const released = yield* releaseManagedTunnelOnShutdown();
// The launcher restarts a server immediately, so the tunnel is not
// orphaned; keeping it avoids the hostname route re-propagation that
// dominates update downtime. The stored config must survive so the
// next boot respawns the connector against the same tunnel.
expect(released).toBe(false);
expect(applyConfigCalls).toEqual([]);
expect(requests).toEqual([]);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases a pending update when the launcher is stopping", () => {
// `t3 service uninstall` or `systemctl stop` during the pending window:
// the launcher writes its stop marker before signalling the child, so no
// replacement server is coming and the tunnel must not be kept.
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
expect(yield* pendingServiceUpdateExists).toBe(true);
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases when the recorded update already settled", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
status: "committed",
});
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
+52
View File
@@ -46,7 +46,9 @@ import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -56,8 +58,14 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { requireEnvironmentScope } from "../auth/http.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
@@ -627,6 +635,37 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
},
);
// The launcher owns this durable state, so read it directly both when a trial
// decides whether it owns pre-activation cleanup and while a server tears down.
export const pendingServiceUpdateExists = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stateText = yield* fs
.readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
.pipe(Effect.option);
return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
if (!(yield* pendingServiceUpdateExists)) {
return false;
}
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stopping = yield* fs
.exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
.pipe(Effect.orElseSucceed(() => false));
return !stopping;
});
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
// relay keeps the link and its hostname reservation, and the next startup's
@@ -649,6 +688,19 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
return false;
}
// A shutdown that hands off to a pending remote update is not the
// environment going offline: the launcher immediately brings a server back
// (the new version, or the old one after a rollback). Deleting the tunnel
// here forces that server to provision a replacement UUID, and the public
// hostname's route to the new tunnel takes 1-2 minutes to propagate — the
// dominant cost of an update restart. Keep the tunnel instead: the next
// boot respawns the connector from the stored config and is reachable as
// soon as it connects, and the reconcile confirms the still-live tunnel
// without replacing it.
if (yield* pendingUpdateHandoffExists) {
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
return false;
}
const token = yield* dependencies.cliTokenManager.getExisting;
if (Option.isNone(token)) {
return false;
+2 -3
View File
@@ -4,7 +4,6 @@ import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
@@ -24,7 +23,7 @@ function validateRelayUrl(value: string) {
? Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Relay URL must be a secure absolute HTTPS origin.",
}),
),
@@ -130,7 +129,7 @@ function validateHostedAppUrl(value: string) {
return Effect.fail(
new Config.ConfigError(
new Schema.SchemaError(
new SchemaIssue.InvalidValue(Option.some(value), {
new SchemaIssue.InvalidValue({
message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",
}),
),
+6 -2
View File
@@ -11,6 +11,7 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
import * as ServerSelfUpdate from "./selfUpdate.ts";
interface HarnessOptions {
@@ -50,7 +51,11 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
const result =
options.preflight === "blocked"
? { status: "blocked", version: "1.1.0", reason: "local update required" }
: { status: "ready", version: "1.1.0", launcherProtocol: 1 };
: {
status: "ready",
version: "1.1.0",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
};
return {
// @effect-diagnostics-next-line preferSchemaOverJson:off - fake child-process stdout.
stdout: JSON.stringify(result),
@@ -64,7 +69,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
});
const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
managed: options.managed ?? true,
trial: false,
requestUpdate:
options.requestUpdate ??
(() =>
+1 -1
View File
@@ -170,7 +170,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
yield* reportProgress("installing");
const updateId = yield* launcher
.requestUpdate({ targetVersion })
.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })
.pipe(
Effect.mapError((error) =>
failWith(
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
} from "./serviceProtocol.ts";
@@ -53,10 +54,11 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
dbPath: "/tmp/state.sqlite",
status: "pending" as const,
};
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.1.0",
update: pending,
});
@@ -79,13 +81,14 @@ it.effect("waits for the launcher to durably commit the trial update ID", () =>
it.effect("returns the launcher-generated ID only after update acceptance", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
});
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
yield* Effect.yieldNow;
host.emit({
type: "update-accepted",
@@ -97,11 +100,15 @@ it.effect("returns the launcher-generated ID only after update acceptance", () =
it.effect("preserves a launcher rejection as a distinct error", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({ protocol: 1, childVersion: "1.0.0" });
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(client.requestUpdate({ targetVersion: "1.1.0" }), {
startImmediately: true,
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.0.0",
});
const client = yield* makeClient(host, "1.0.0");
const requested = yield* Effect.forkChild(
client.requestUpdate({ targetVersion: "1.1.0", dbPath: "/tmp/state.sqlite" }),
{ startImmediately: true },
);
yield* Effect.yieldNow;
host.emit({ type: "update-rejected", reason: "requires local update" });
expect(yield* Fiber.join(requested).pipe(Effect.flip)).toMatchObject({
@@ -115,12 +122,13 @@ it.effect("preserves a launcher rejection as a distinct error", () =>
it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
protocol: 1,
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.1.0",
update: {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.2.0",
dbPath: "/tmp/state.sqlite",
status: "pending",
},
});
+10 -6
View File
@@ -100,9 +100,9 @@ export class ServiceLauncherClient extends Context.Service<
ServiceLauncherClient,
{
readonly managed: boolean;
readonly trial: boolean;
readonly requestUpdate: (input: {
readonly targetVersion: string;
readonly dbPath: string;
}) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
readonly prepareTrial: Effect.Effect<
ServerSelfUpdateOutcome | undefined,
@@ -137,8 +137,8 @@ const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup"
export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
function* () {
const { context, managed } = yield* resolveStartup();
return { managed, trial: context?.update?.status === "pending" };
const { managed } = yield* resolveStartup();
return { managed };
},
);
@@ -199,7 +199,7 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
}),
);
const requestUpdate = (input: { readonly targetVersion: string }) =>
const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
exchange(
{ type: "request-update", ...input },
(reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
@@ -233,14 +233,18 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
if (reply.type !== "committed") {
return Effect.die("service launcher returned an impossible prepared response");
}
return Effect.succeed({ ...pending, status: "committed" as const });
return Effect.succeed({
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
});
}),
)
: Effect.succeed(outcome);
return ServiceLauncherClient.of({
managed,
trial: pending !== undefined,
requestUpdate,
prepareTrial,
});
+20 -41
View File
@@ -1,47 +1,26 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as NodeSqlite from "node:sqlite";
import { migrationManifest } from "../persistence/Migrations.ts";
import { runServicePreflight } from "./servicePreflight.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
it.layer(NodeServices.layer)("service update preflight", (it) => {
it.effect("requires exact migration-manifest equality without mutating the database", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-preflight-test-" });
const databasePath = path.join(root, "state.sqlite");
const database = new NodeSqlite.DatabaseSync(databasePath);
database.exec("CREATE TABLE effect_sql_migrations (migration_id INTEGER, name TEXT)");
const insert = database.prepare(
"INSERT INTO effect_sql_migrations (migration_id, name) VALUES (?, ?)",
);
for (const [id, name] of migrationManifest) insert.run(id, name);
database.close();
expect(runServicePreflight({ databasePath, launcherProtocol: 1, version: "1.2.3" })).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: 1,
});
const changed = new NodeSqlite.DatabaseSync(databasePath);
changed.exec("DELETE FROM effect_sql_migrations WHERE migration_id = 35");
changed.close();
const blocked = runServicePreflight({
databasePath,
launcherProtocol: 1,
version: "1.2.3",
});
expect(blocked.status).toBe("blocked");
if (blocked.status === "blocked") {
expect(blocked.reason).toContain("npx [email protected] service update");
}
it("requires the database-snapshot launcher protocol", () => {
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL - 1,
version: "1.2.3",
}),
);
).toMatchObject({ status: "blocked", version: "1.2.3" });
expect(
runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
version: "1.2.3",
}),
).toEqual({
status: "ready",
version: "1.2.3",
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
});
});
+1 -38
View File
@@ -1,7 +1,4 @@
import * as NodeSqlite from "node:sqlite";
import packageJson from "../../package.json" with { type: "json" };
import { migrationManifest } from "../persistence/Migrations.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
export type ServicePreflightResult =
@@ -16,20 +13,8 @@ export type ServicePreflightResult =
readonly reason: string;
};
const localUpdateReason = (version: string) =>
`This version includes a database update and cannot be installed remotely. Run \`npx t3@${version} service update\` on the server machine.`;
const isMigrationRow = (
value: unknown,
): value is { readonly migration_id: number; readonly name: string } =>
typeof value === "object" &&
value !== null &&
"migration_id" in value &&
typeof value.migration_id === "number" &&
"name" in value &&
typeof value.name === "string";
export function runServicePreflight(input: {
/** Older servers always pass this flag when invoking a staged preflight. */
readonly databasePath: string;
readonly launcherProtocol: number;
readonly version?: string;
@@ -44,28 +29,6 @@ export function runServicePreflight(input: {
};
}
try {
const database = new NodeSqlite.DatabaseSync(input.databasePath, { readOnly: true });
try {
const rows: ReadonlyArray<unknown> = database
.prepare("SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id")
.all();
const exact =
rows.length === migrationManifest.length &&
rows.every((row, index) => {
const expected = migrationManifest[index];
return (
isMigrationRow(row) && row.migration_id === expected?.[0] && row.name === expected?.[1]
);
});
if (!exact) return { status: "blocked", version, reason: localUpdateReason(version) };
} finally {
database.close();
}
} catch {
return { status: "blocked", version, reason: localUpdateReason(version) };
}
return { status: "ready", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };
}
+27 -4
View File
@@ -1,14 +1,20 @@
import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
export const SERVICE_LAUNCHER_PROTOCOL = 1 as const;
/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */
export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
/** Written by the launcher just before an explicit stop kills its child, so
the child can tell "the service is going away" from "the launcher is about
to start my replacement" while a pending update is recorded. */
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
export interface PendingServiceUpdate {
readonly id: string;
readonly fromVersion: string;
readonly targetVersion: string;
readonly dbPath: string;
readonly status: "pending";
}
@@ -31,6 +37,7 @@ export type ServiceLauncherChildMessage =
| {
readonly type: "request-update";
readonly targetVersion: string;
readonly dbPath: string;
}
| {
readonly type: "prepared";
@@ -78,7 +85,9 @@ export function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undef
return undefined;
}
if (status === "pending") {
return { id, fromVersion, targetVersion, status };
return typeof value.dbPath === "string" && value.dbPath.trim() !== ""
? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }
: undefined;
}
if (
(status === "committed" || status === "rolled-back" || status === "failed") &&
@@ -165,6 +174,16 @@ export function parseServiceState(value: string): ServiceState | undefined {
}
}
/** Detects an in-flight update across launcher protocol versions before replacing its state. */
export function serviceStateHasPendingUpdate(value: string): boolean {
try {
const parsed: unknown = JSON.parse(value);
return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === "pending";
} catch {
return false;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
@@ -202,8 +221,12 @@ export function decodeServiceLauncherChildMessage(
value: unknown,
): ServiceLauncherChildMessage | undefined {
if (!isRecord(value)) return undefined;
if (value.type === "request-update" && typeof value.targetVersion === "string") {
return { type: value.type, targetVersion: value.targetVersion };
if (
value.type === "request-update" &&
typeof value.targetVersion === "string" &&
typeof value.dbPath === "string"
) {
return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };
}
return value.type === "prepared" && typeof value.updateId === "string"
? { type: value.type, updateId: value.updateId }
@@ -145,6 +145,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
@@ -69,6 +69,10 @@ export class GitWorkflowService extends Context.Service<
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<void, GitCommandError>;
readonly remoteExists: (input: {
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<boolean, GitCommandError>;
readonly resolveRemoteTrackingCommit: (input: {
readonly cwd: string;
readonly refName: string;
@@ -303,6 +307,10 @@ export const make = Effect.gen(function* () {
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
),
remoteExists: (input) =>
ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
Effect.andThen(git.remoteExists(input)),
),
resolveRemoteTrackingCommit: (input) =>
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
+3 -68
View File
@@ -14,10 +14,10 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { cast } from "effect/Function";
import {
Headers,
HttpBody,
HttpClient,
HttpClientResponse,
HttpMiddleware,
HttpRouter,
HttpServerResponse,
HttpServerRequest,
@@ -30,7 +30,6 @@ import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
@@ -44,74 +43,10 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
const GZIP_MIN_BYTES = 1024;
function acceptsGzip(value: string | undefined): boolean {
if (!value) return false;
const accepted = new Map(
value.split(",").map((entry) => {
const [coding = "", ...parameters] = entry.trim().toLowerCase().split(";");
const quality = parameters
.map((parameter) => parameter.trim().match(/^q=(.+)$/)?.[1])
.find((parameter) => parameter !== undefined);
return [coding, quality === undefined ? 1 : Number(quality)] as const;
}),
);
return (accepted.get("gzip") ?? accepted.get("*") ?? 0) > 0;
}
function varyByAcceptEncoding(value: string | undefined): string {
if (!value) return "Accept-Encoding";
const values = new Set(value.split(",").map((entry) => entry.trim().toLowerCase()));
return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
}
const compressHttpResponse = Effect.fnUntraced(function* (
response: HttpServerResponse.HttpServerResponse,
acceptEncoding: string | undefined,
) {
const body = response.body;
if (
body._tag !== "Uint8Array" ||
body.contentLength < GZIP_MIN_BYTES ||
!body.contentType.startsWith("application/json") ||
response.headers["content-encoding"]
) {
return response;
}
const variedResponse = HttpServerResponse.setHeader(
response,
"vary",
varyByAcceptEncoding(response.headers.vary),
);
if (!acceptsGzip(acceptEncoding)) return variedResponse;
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const headers = Headers.set(
Headers.remove(variedResponse.headers, "content-length"),
"content-encoding",
"gzip",
);
return compression.gzip(body.body, {
status: response.status,
statusText: response.statusText,
headers,
cookies: response.cookies,
contentType: body.contentType,
});
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
global: true,
});
export const httpCompressionLayer = HttpRouter.middleware(
(httpEffect) =>
Effect.flatMap(
Effect.all([httpEffect, HttpServerRequest.HttpServerRequest]),
([response, request]) => compressHttpResponse(response, request.headers["accept-encoding"]),
),
{ global: true },
);
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -1,29 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as NodeStream from "node:stream";
import * as Effect from "effect/Effect";
import * as HttpResponseCompression from "./HttpResponseCompression.ts";
it.effect("uses a native Node stream", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
}
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
);
it.effect("uses a native Web stream for Bun", () =>
Effect.gen(function* () {
const compression = yield* HttpResponseCompression.HttpResponseCompression;
const response = compression.gzip(new Uint8Array(), {});
expect(response.body._tag).toBe("Raw");
if (response.body._tag === "Raw") {
expect(response.body.body).toBeInstanceOf(ReadableStream);
}
}).pipe(Effect.provide(HttpResponseCompression.layerBun)),
);
@@ -1,36 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
export class HttpResponseCompression extends Context.Service<
HttpResponseCompression,
{
readonly gzip: (
body: Uint8Array,
options: HttpServerResponse.Options,
) => HttpServerResponse.HttpServerResponse;
}
>()("t3/httpCompression/HttpResponseCompression") {}
export const layerNode = Layer.effect(
HttpResponseCompression,
Effect.gen(function* () {
const NodeZlib = yield* Effect.promise(() => import("node:zlib"));
return {
gzip: (body, options) => {
const stream = NodeZlib.createGzip();
stream.end(body);
return HttpServerResponse.raw(stream, options);
},
};
}),
);
export const layerBun = Layer.succeed(HttpResponseCompression, {
gzip: (body, options) =>
HttpServerResponse.raw(
new Response(body).body!.pipeThrough(new CompressionStream("gzip")),
options,
),
});
+2 -3
View File
@@ -29,7 +29,6 @@ import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as PubSub from "effect/PubSub";
import * as Result from "effect/Result";
@@ -68,7 +67,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Effect.filterOrFail(
Predicate.isNotNull,
() =>
new SchemaIssue.InvalidValue(Option.some(rule), {
new SchemaIssue.InvalidValue({
message: "Invalid keybinding rule",
}),
),
@@ -80,7 +79,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
const key = encodeShortcut(resolved.shortcut);
if (!key) {
return yield* Effect.fail(
new SchemaIssue.InvalidValue(Option.some(resolved), {
new SchemaIssue.InvalidValue({
message: "Resolved shortcut cannot be encoded to key string",
}),
);
+6 -3
View File
@@ -5,7 +5,7 @@ import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3to
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import * as McpHttpServer from "./McpHttpServer.ts";
@@ -26,8 +26,9 @@ const invocation = {
};
const client = McpSchema.McpServerClient.of({
clientId: 1,
protocolVersion: "2025-06-18",
initializePayload: {
protocolVersion: "2025-03-26",
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "mcp-test", version: "1.0.0" },
},
@@ -103,6 +104,7 @@ it.effect("terminates HTTP MCP sessions with DELETE", () =>
name: "MCP termination test",
version: "1.0.0",
path: "/mcp",
protocols: [McpProtocol.v2025_06_18],
});
yield* HttpRouter.serve(serverLayer, {
disableListenLog: true,
@@ -239,8 +241,9 @@ it.effect("registers annotated tools and preserves authenticated request context
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
Effect.flip,
);
expect(malformed.isError).toBe(true);
expect(malformed._tag).toBe("InvalidParams");
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
+2 -1
View File
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import type * as Types from "effect/Types";
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import packageJson from "../../package.json" with { type: "json" };
@@ -220,6 +220,7 @@ const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
protocols: [McpProtocol.v2025_06_18],
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
@@ -12,6 +12,19 @@ const schemaHasDescription = (schema: unknown): boolean => {
.some((members) => members.some(schemaHasDescription));
};
const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => {
if (!schema || typeof schema !== "object") return false;
const record = schema as Record<string, unknown>;
const allOf = Array.isArray(record.allOf) ? record.allOf : [];
const descriptionCount = allOf.filter(
(member) =>
member !== null &&
typeof member === "object" &&
typeof (member as Record<string, unknown>).description === "string",
).length;
return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions);
};
it("exports provider-compatible object schemas with described parameters", () => {
for (const tool of Object.values(PreviewToolkit.tools)) {
const schema = Tool.getJsonSchema(tool) as {
@@ -27,6 +40,9 @@ it("exports provider-compatible object schemas with described parameters", () =>
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
if (tool.name === "preview_navigate") {
expect(schemaHasMultipleAllOfDescriptions(schema)).toBe(false);
}
expect(
schema.properties?.tabId,
`${tool.name} must allow an explicit collaborative browser tab target`,
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vite-plus/test";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
return {
id: "activity-1",
tone: "tool",
kind: "tool.completed",
summary: "Tool",
payload,
turnId: null,
createdAt: "2026-08-01T10:00:00.000Z",
} as unknown as OrchestrationThreadActivity;
}
/**
* Wire-survival regression: the slimming pass rewrites payload.data but must
* never strip the top-level per-agent fields the subagent fold depends on.
* If slimming ever moves to an allowlist over the whole payload, these
* assertions are the tripwire.
*/
describe("projectActivityPayload agent-field survival", () => {
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
const projected = projectActivityPayload(
activity({
itemType: "command_execution",
agentId: "task-123",
parentToolUseId: "toolu_abc",
data: {
toolName: "Bash",
input: { command: "ls" },
command: "ls",
rawOutput: { content: "x".repeat(10) },
somethingClientNeverReads: { big: "blob" },
},
}),
);
const payload = projected.payload as Record<string, unknown>;
expect(payload.agentId).toBe("task-123");
expect(payload.parentToolUseId).toBe("toolu_abc");
// Slimming itself still applies to data.
const data = payload.data as Record<string, unknown>;
expect(data.somethingClientNeverReads).toBeUndefined();
});
it("slims Codex-shaped mcp_tool_call items to rendered fields plus a result summary", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
item: {
type: "mcpToolCall",
id: "item-1",
tool: "fetch_pr",
server: "github",
status: "completed",
arguments: { pr: 42 },
durationMs: 1200,
result: {
content: [{ type: "text", text: `PR body line one\n${"x".repeat(5000)}` }],
structuredContent: { huge: "y".repeat(5000) },
},
_meta: { internal: true },
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
const item = data.item as Record<string, unknown>;
expect(item.tool).toBe("fetch_pr");
expect(item.server).toBe("github");
expect(item.arguments).toEqual({ pr: 42 });
expect(item._meta).toBeUndefined();
expect(item.result).toEqual({ content: "PR body line one" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("slims Claude-shaped mcp_tool_call data (toolName/input/result block)", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
toolName: "mcp__github__fetch_pr",
input: { pr: 42 },
result: {
type: "tool_result",
tool_use_id: "toolu_1",
content: [{ type: "text", text: `first line of output\n${"z".repeat(5000)}` }],
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
expect(data.toolName).toBe("mcp__github__fetch_pr");
expect(data.input).toEqual({ pr: 42 });
expect(data.result).toEqual({ content: "first line of output" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("passes task lifecycle payloads (no data field) through untouched", () => {
const source = activity({
taskId: "task-9",
title: "Audit auth",
role: "explorer",
model: "opus",
effort: "high",
workflowName: "audit-flow",
phases: [{ index: 0, title: "Audit" }],
typedUsage: { totalTokens: 1200 },
runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },
timelineBypass: true,
});
const projected = projectActivityPayload(source);
expect(projected.payload).toEqual(source.payload);
});
});
@@ -123,6 +123,114 @@ function summarizeToolTextOutput(value: string): string | null {
return null;
}
/**
* Fields of an MCP tool-call item both clients render in the expanded
* work-log row. Everything else — notably `result`, which carries the full
* tool output and dominates wire size on MCP-heavy threads — is summarized
* or dropped. Full payloads remain in persistence.
*/
const MCP_ITEM_KEPT_FIELDS = [
"type",
"id",
"tool",
"server",
"status",
"arguments",
"appContext",
"error",
"durationMs",
] as const;
/**
* Pulls renderable text out of an MCP tool result: either a Codex-style
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
* `tool_result` block whose `content` is a string or block array.
*/
function extractMcpResultText(result: unknown): string | null {
const record = asRecord(result);
if (!record) {
return typeof result === "string" ? result : null;
}
if (typeof record.content === "string") {
return record.content;
}
if (Array.isArray(record.content)) {
const texts: string[] = [];
for (const entry of record.content) {
const text = asRecord(entry)?.text;
if (typeof text === "string" && text.trim().length > 0) {
texts.push(text);
}
}
if (texts.length > 0) {
return texts.join("\n");
}
}
return null;
}
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
if (result === undefined || result === null) {
return undefined;
}
const text = extractMcpResultText(result);
const summary = text ? summarizeToolTextOutput(text) : null;
return summary ? { content: summary } : undefined;
}
/**
* MCP tool calls carry full tool results (`data.item.result` on Codex,
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
* keep the expanded-row UI working. Keep the fields the UI actually renders
* and summarize the result like regular tool output.
*/
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
const projectedData: Record<string, unknown> = {};
const item = asRecord(data.item);
if (item) {
const projectedItem: Record<string, unknown> = {};
for (const key of MCP_ITEM_KEPT_FIELDS) {
if (key in item) {
projectedItem[key] = item[key];
}
}
const result = summarizeMcpResult(item.result);
if (result) {
projectedItem.result = result;
}
projectedData.item = projectedItem;
}
if ("toolName" in data) {
projectedData.toolName = data.toolName;
}
if ("input" in data) {
projectedData.input = data.input;
}
if (!item) {
const result = summarizeMcpResult(data.result);
if (result) {
projectedData.result = result;
}
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
projectedData.files = changedFiles.map((path) => ({ path }));
}
return projectedData;
}
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
const rawOutput = asRecord(value);
if (!rawOutput) {
@@ -160,10 +268,20 @@ export function projectActivityPayload(
): OrchestrationThreadActivity {
const payload = asRecord(activity.payload);
const data = asRecord(payload?.data);
if (!payload || !data || payload.itemType === "mcp_tool_call") {
if (!payload || !data) {
return activity;
}
if (payload.itemType === "mcp_tool_call") {
return {
...activity,
payload: {
...payload,
data: projectMcpToolCallData(data),
},
};
}
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
@@ -247,6 +365,107 @@ function dropStaleContextWindowActivities(
);
}
/**
* Identity both clients use to fold a tool lifecycle row into the call it
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
* with no identity at all — those never collapse on the client either, so they
* must not be dropped here.
*/
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
const payload = asRecord(activity.payload);
if (!payload) {
return null;
}
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
if (toolCallId) {
return `id:${toolCallId}`;
}
const itemType = asTrimmedString(payload.itemType) ?? "";
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
// gain a trailing "complete"/"completed" the in-flight updates lack.
const label = (asTrimmedString(payload.title) ?? activity.summary)
.replace(/\s+(?:complete|completed)\s*$/iu, "")
.trim();
const detail = asTrimmedString(payload.detail) ?? "";
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
return null;
}
return [itemType, label, detail].join("");
}
/**
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
* update is the in-flight snapshot of a call; once the call completes, the
* completion carries the final state and the clients fold every matching
* update into it, so shipping the updates buys nothing — 47k such rows exist
* in one real database, and a single thread carries 2,291 of them totalling
* ~1MB post-slimming.
*
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
* retains per turn: a live `thread.reverted` makes the client discard whole
* turns, so a completion in a different turn could vanish and leave the
* dropped update unrepresented. The completion must also come *after* the
* update within the turn — a later update belongs to a subsequent call that
* reuses the same identity and is still in flight. Rows without a lifecycle
* identity pass through, matching the clients, which never collapse them.
* Live `thread.activity-appended` events are untouched: updates still stream
* in real time and the completion supersedes them on the client as before.
*
* Deliberate divergence from client collapse: clients fold only *adjacent*
* lifecycle rows, so a superseded update separated from its completion by an
* interleaved parallel call renders as its own row today, and this drop
* removes it. Measured against a real database, that affects 1.5% of dropped
* rows (553 of 36,581), all pure in-flight state whose final result the
* retained completion still shows. Dropping them is intentional; matching
* adjacency server-side would forfeit most of the win for parallel-heavy
* threads, which are exactly the heavy ones. Superseding completions always
* carry a payload superset of their updates (verified across all 49,515
* update rows: zero dropped rows held a client-merged field — detail, title,
* command, item, kind, files — their completion lacked), so no expanded-row
* content is lost.
*/
function dropSupersededToolUpdatedActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const completionIndicesByKey = new Map<string, number[]>();
for (let index = 0; index < activities.length; index += 1) {
const activity = activities[index]!;
if (activity.kind !== "tool.completed") {
continue;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
continue;
}
const key = `${activity.turnId ?? ""}${identity}`;
const indices = completionIndicesByKey.get(key);
if (indices) {
indices.push(index);
} else {
completionIndicesByKey.set(key, [index]);
}
}
if (completionIndicesByKey.size === 0) {
return activities;
}
return activities.filter((activity, index) => {
if (activity.kind !== "tool.updated") {
return true;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
return true;
}
const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}${identity}`);
return !indices?.some((completionIndex) => completionIndex > index);
});
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
@@ -254,9 +473,9 @@ export function projectThreadDetailSnapshot(
...snapshot,
thread: {
...snapshot.thread,
activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(
projectActivityPayload,
),
activities: dropSupersededToolUpdatedActivities(
dropStaleContextWindowActivities(snapshot.thread.activities),
).map(projectActivityPayload),
},
};
}
@@ -39,6 +39,7 @@ import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -294,6 +295,7 @@ describe("CheckpointReactor", () => {
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -301,6 +303,7 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -31,6 +31,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
@@ -55,6 +56,7 @@ async function createOrchestrationSystem() {
),
OrchestrationProjectionSnapshotQueryLive,
).pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
@@ -817,6 +819,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -922,6 +925,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -1065,6 +1069,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -31,6 +31,7 @@ import {
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1429,6 +1430,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
const threadRows = yield* sql<{ readonly latestTurnId: string | null }>`
SELECT latest_turn_id AS "latestTurnId"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
assert.deepEqual(threadRows, [{ latestTurnId: turnId }]);
}),
);
@@ -2664,6 +2672,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -611,6 +611,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -717,6 +718,36 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.pinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unpinned": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -819,7 +850,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestTurnId: event.payload.session.activeTurnId,
// activeTurnId describes current work; a terminal session must not erase history.
latestTurnId: event.payload.session.activeTurnId ?? existingRow.value.latestTurnId,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
@@ -17,7 +17,9 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -27,6 +29,7 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
@@ -312,6 +315,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -427,6 +431,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -441,6 +446,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
backgroundLiveness: null,
},
]);
@@ -1823,6 +1829,7 @@ it.effect(
() => {
const resolveCalls: string[] = [];
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provideMerge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (cwd: string) =>
@@ -1911,3 +1918,407 @@ it.effect(
}).pipe(Effect.provide(layer));
},
);
projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) => {
// A thread shaped like real fan-out usage: user turns interleaved with
// subagent turns (no user pending message), plus a turnless straggler user
// message and a turnless activity anchored between turns.
//
// row turn pending msg anchor (requested_at)
// 1 turn-1 user-msg-1 T00
// 2 turn-2 (subagent) T01
// 3 turn-3 (subagent) T02
// 4 turn-4 user-msg-4 T03
// 5 turn-5 user-msg-5 T04
//
// Straggler user message at T03.5 (turn_id NULL, not any pending_message_id)
// and a turnless activity at T03.6 — both belong to the page containing T03+.
const seedFanOutThread = Effect.fnUntraced(function* () {
const sql = yield* SqlClient.SqlClient;
// Tests in this block share one in-memory database; reset before seeding.
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-w', 'Windowed', '/tmp/project-w', '[]',
'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
latest_turn_id, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, deleted_at
)
VALUES ('thread-w', 'project-w', 'Windowed thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
'turn-5', 0, 0, 0, '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:10.000Z', NULL)
`;
const turns: ReadonlyArray<{
turn: string;
pendingMessage: string | null;
at: string;
}> = [
{ turn: "turn-1", pendingMessage: "user-msg-1", at: "2026-03-01T00:00:00.000Z" },
{ turn: "turn-2", pendingMessage: null, at: "2026-03-01T00:01:00.000Z" },
{ turn: "turn-3", pendingMessage: null, at: "2026-03-01T00:02:00.000Z" },
{ turn: "turn-4", pendingMessage: "user-msg-4", at: "2026-03-01T00:03:00.000Z" },
{ turn: "turn-5", pendingMessage: "user-msg-5", at: "2026-03-01T00:04:00.000Z" },
];
for (const { turn, pendingMessage, at } of turns) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at, completed_at,
checkpoint_files_json
)
VALUES ('thread-w', ${turn}, ${pendingMessage}, 'completed', ${at}, ${at}, ${at}, '[]')
`;
if (pendingMessage !== null) {
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${pendingMessage}, 'thread-w', NULL, 'user', ${"prompt for " + turn}, 0, ${at}, ${at})
`;
}
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${turn + "-reply"}, 'thread-w', ${turn}, 'assistant', ${"reply from " + turn}, 0, ${at}, ${at})
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES (${turn + "-activity"}, 'thread-w', ${turn}, 'tool', 'tool.completed',
'ran tool', '{"ok":true}', ${at})
`;
}
// Straggler user message sent while turn-4 ran: turn_id NULL and not any
// turn's pending_message_id.
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('user-msg-straggler', 'thread-w', NULL, 'user', 'while you are at it',
0, '2026-03-01T00:03:30.000Z', '2026-03-01T00:03:30.000Z')
`;
// Turnless activity in the same time range.
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES ('turnless-activity', 'thread-w', NULL, 'info', 'context-window.updated',
'usage', '{"usedTokens":1}', '2026-03-01T00:03:36.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 42, '2026-03-01T00:00:10.000Z')
`;
}
});
const threadW = ThreadId.make("thread-w");
const messageIds = (snapshot: { thread: { messages: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.messages.map((message) => message.id).toSorted();
const activityIds = (snapshot: { thread: { activities: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.activities.map((activity) => activity.id).toSorted();
it.effect("returns the full thread with no page metadata when no window is requested", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW);
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page, undefined);
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.snapshotSequence, 42);
}
}),
);
it.effect("windows to the last N user-anchored turns with subagent turns riding along", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 2 walks back: turn-5 (user), turn-4 (user) -> window is
// rows 4..5. Subagent turns 2-3 are older than the 2nd user turn and
// stay out; the straggler message and turnless activity (T03.5/T03.6,
// after turn-4's anchor) ride along.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), [
"turn-4-reply",
"turn-5-reply",
"user-msg-4",
"user-msg-5",
"user-msg-straggler",
]);
assert.deepEqual(activityIds(snapshot.value), [
"turn-4-activity",
"turn-5-activity",
"turnless-activity",
]);
assert.equal(snapshot.value.page?.hasMore, true);
assert.notEqual(snapshot.value.page?.beforeCursor, null);
assert.equal(snapshot.value.page?.snapshotSequence, 42);
}
}),
);
it.effect("subagent turns between user turns ride along inside the window", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 3 reaches user turn-1, dragging subagent turns 2-3 along:
// the full thread, so no further pages.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 3 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
it.effect("cursors survive a projection rewrite that reassigns turn row ids", () =>
Effect.gen(function* () {
// The revert projector (and any projection rebuild) deletes and
// re-upserts projection_turns, assigning fresh autoincrement row ids.
// The keyset cursor is derived from event content, so a page cursor
// minted before the rewrite must keep working after it.
yield* seedFanOutThread();
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
if (cursor === null || cursor === undefined) return;
// Simulate the rewrite: delete and re-insert every turn row with the
// same content, which reassigns all row ids.
const turnRows = yield* sql`
SELECT thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
FROM projection_turns WHERE thread_id = 'thread-w' ORDER BY row_id
`;
yield* sql`DELETE FROM projection_turns WHERE thread_id = 'thread-w'`;
for (const row of turnRows) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
)
VALUES (${row.thread_id as string}, ${row.turn_id as string},
${row.pending_message_id as string | null}, ${row.state as string},
${row.requested_at as string}, ${row.started_at as string},
${row.completed_at as string}, ${row.checkpoint_files_json as string})
`;
}
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
// Identical older slice to what the pre-rewrite cursor would return.
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.equal(olderPage.value.page?.hasMore, false);
}
}),
);
it.effect("beforeCursor returns the disjoint adjacent older slice", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
assert.notEqual(cursor, undefined);
if (cursor === null || cursor === undefined) return;
// Older page: user turn-1 plus subagent turns 2-3 riding along. Disjoint
// from the first page: no turn-4/5 rows, no straggler.
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.deepEqual(activityIds(olderPage.value), [
"turn-1-activity",
"turn-2-activity",
"turn-3-activity",
]);
assert.equal(olderPage.value.page?.hasMore, false);
assert.equal(olderPage.value.page?.beforeCursor, null);
}
}),
);
it.effect("a cursor for a different thread degrades to the first page", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const foreign = encodeThreadDetailPageCursor({
threadId: ThreadId.make("thread-other"),
beforeAnchorAt: "2026-03-01T00:01:00.000Z",
beforeTurnId: "turn-2",
});
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: foreign,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), messageIds(firstPage.value));
}
}),
);
it.effect("a malformed cursor degrades to the first page instead of failing", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: "not-a-cursor",
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page?.hasMore, true);
assert.equal(snapshot.value.thread.messages.length, 5);
}
}),
);
it.effect("windows never split below the raw-turn ceiling boundary contiguously", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// Page repeatedly with turnLimit 1 and assert the union of all pages is
// exactly the full thread with no duplicates (disjointness + coverage).
const seenMessages: string[] = [];
const seenActivities: string[] = [];
let cursor: string | undefined;
for (let page = 0; page < 10; page += 1) {
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
...(cursor !== undefined ? { beforeCursor: cursor } : {}),
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag !== "Some") return;
seenMessages.push(...snapshot.value.thread.messages.map((message) => message.id));
seenActivities.push(...snapshot.value.thread.activities.map((activity) => activity.id));
const next = snapshot.value.page?.beforeCursor;
if (next === null || next === undefined) break;
cursor = next;
}
assert.equal(new Set(seenMessages).size, seenMessages.length);
assert.equal(new Set(seenActivities).size, seenActivities.length);
assert.equal(seenMessages.length, 9);
assert.equal(seenActivities.length, 6);
}),
);
it.effect("a thread with no turns returns its content unwindowed on the first page", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-e', 'Empty', '/tmp/project-e', '[]',
'2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
pending_approval_count, pending_user_input_count, has_actionable_proposed_plan,
created_at, updated_at, deleted_at
)
VALUES ('thread-e', 'project-e', 'Turnless thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
0, 0, 0, '2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('pre-turn-msg', 'thread-e', NULL, 'user', 'first prompt', 0,
'2026-03-02T00:00:01.000Z', '2026-03-02T00:00:01.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 7, '2026-03-02T00:00:01.000Z')
`;
}
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(ThreadId.make("thread-e"), {
turnLimit: 5,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), ["pre-turn-msg"]);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
});
@@ -43,6 +43,7 @@ import {
type ProjectionRepositoryError,
} from "../../persistence/Errors.ts";
import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
@@ -50,6 +51,10 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import {
decodeThreadDetailPageCursor,
encodeThreadDetailPageCursor,
} from "../threadDetailCursor.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
@@ -129,6 +134,36 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
// Windowed reads order turns by the stable keyset (anchor, turn key), where
// anchor is requested_at and turn key is
// COALESCE(turn_id, ''). Both are event-derived, so cursors survive the
// revert projector's row-id rewrite and full projection rebuilds.
const ThreadTurnWindowLookupInput = Schema.Struct({
threadId: ThreadId,
// Exclusive keyset upper bound. Sentinels "~"/"" mean unbounded ("~" sorts
// after every ISO timestamp).
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
userTurnLimit: Schema.Number,
maxRawTurns: Schema.Number,
});
const ProjectionTurnWindowRowSchema = Schema.Struct({
// The turn's timeline anchor, used to bound rows that have no turn linkage
// (user messages and turnless activities) to the same page window.
anchorAt: Schema.String,
turnKey: Schema.String,
});
const ThreadTurnRangeLookupInput = Schema.Struct({
threadId: ThreadId,
// Turn-linked rows are bounded by the keyset range [min, before) over
// (anchor, turn key); turnless rows by the matching [minAnchorAt,
// beforeAnchorAt) time range. Unbounded ends use sentinels: "" for the
// lower bound, "~" (sorts after ISO dates) for the upper bound.
minAnchorAt: Schema.String,
minTurnKey: Schema.String,
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -308,6 +343,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
}
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const sql = yield* SqlClient.SqlClient;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const repositoryIdentityResolutionConcurrency = 4;
@@ -384,6 +420,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -418,6 +455,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -454,6 +492,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -890,6 +929,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1037,6 +1077,197 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Resolves a page of recent turns for a windowed thread detail read. Walks
// back from the exclusive (beforeAnchorAt, beforeTurnKey) keyset boundary
// (sentinels "~"/"" mean unbounded, i.e. the first page) until it has seen
// `userTurnLimit` user-anchored turns — turns whose pending message is a
// user message; subagent/fan-out turns between them ride along — or hits the
// `maxRawTurns` ceiling that bounds pathological fan-out. The `candidates`
// CTE applies the keyset bound and LIMIT before the window functions run;
// its ORDER BY uses raw columns so the migration-037
// (thread_id, requested_at, turn_id) index serves both range and order with
// no temp B-tree — the scan is genuinely bounded by the LIMIT. (Raw
// turn_id DESC places NULLs exactly where COALESCE-to-'' would, below every
// real id.) The caller derives the continuation cursor from the oldest
// returned row.
// Highest thread-DETAIL event sequence for this thread that the projection
// has applied (bounded by the global snapshot sequence read in the same
// transaction). This is the thread-scoped watermark a windowed page carries
// so clients can defer merging until their live subscription has caught up;
// the global sequence is not waitable per-thread. The event_type filter
// must match ws.ts's isThreadDetailEvent exactly: the subscription only
// delivers these types, so a watermark counting any other event could
// never be reached by the client and would park the page forever. Served
// by the event store's (aggregate_kind, stream_id, sequence) index.
const getThreadEventWatermarkRow = SqlSchema.findOneOption({
Request: Schema.Struct({ threadId: ThreadId, maxSequence: Schema.Number }),
Result: Schema.Struct({ threadSequence: Schema.NullOr(Schema.Number) }),
execute: ({ threadId, maxSequence }) =>
sql`
SELECT MAX(sequence) AS "threadSequence"
FROM orchestration_events
WHERE aggregate_kind = 'thread'
AND stream_id = ${threadId}
AND sequence <= ${maxSequence}
AND event_type IN (
'thread.message-sent',
'thread.proposed-plan-upserted',
'thread.activity-appended',
'thread.turn-diff-completed',
'thread.reverted',
'thread.session-set'
)
`,
});
const listTurnWindowRows = SqlSchema.findAll({
Request: ThreadTurnWindowLookupInput,
Result: ProjectionTurnWindowRowSchema,
execute: ({ threadId, beforeAnchorAt, beforeTurnKey, userTurnLimit, maxRawTurns }) =>
sql`
WITH candidates AS (
SELECT
turns.requested_at AS anchor_at,
COALESCE(turns.turn_id, '') AS turn_key,
turns.pending_message_id
FROM projection_turns AS turns
WHERE turns.thread_id = ${threadId}
AND (
turns.requested_at < ${beforeAnchorAt}
OR (
turns.requested_at = ${beforeAnchorAt}
AND COALESCE(turns.turn_id, '') < ${beforeTurnKey}
)
)
ORDER BY turns.requested_at DESC, turns.turn_id DESC
LIMIT ${maxRawTurns}
),
walked AS (
SELECT
candidates.anchor_at,
candidates.turn_key,
CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END AS is_user_turn,
SUM(CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END) OVER (
ORDER BY candidates.anchor_at DESC, candidates.turn_key DESC
) AS user_turns_seen
FROM candidates
LEFT JOIN projection_thread_messages AS messages
ON messages.message_id = candidates.pending_message_id
)
SELECT
anchor_at AS "anchorAt",
turn_key AS "turnKey"
FROM walked
WHERE user_turns_seen < ${userTurnLimit}
OR (user_turns_seen = ${userTurnLimit} AND is_user_turn = 1)
ORDER BY anchor_at ASC, turn_key ASC
`,
});
// Windowed variants of the two heavy collections. Turn-linked rows are
// bounded by the page's (anchor, turn key) keyset range over
// projection_turns; rows with no turn linkage (user messages always, and
// turnless activities like pre-turn context-window updates) are bounded by
// the matching turn-anchor time range so they land on the same page as the
// turns around them. Proposed plans and checkpoints stay unwindowed: they
// are metadata-scale.
const listThreadMessageRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE thread_id = ${threadId}
AND (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY created_at ASC, message_id ASC
`,
});
const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
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 (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
Request: FullThreadDiffContextLookupInput,
Result: ProjectionFullThreadDiffContextRowSchema,
@@ -1328,6 +1559,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1531,6 +1763,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1665,12 +1898,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -1804,12 +2041,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -2075,16 +2316,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
threadRow.value.threadId,
),
} satisfies OrchestrationThreadShell);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
// Contiguous turn range bounding a windowed detail read; undefined loads the
// full thread. Resolved from a window request inside the snapshot
// transaction (see getThreadDetailSnapshot).
interface ThreadDetailBounds {
readonly minAnchorAt: string;
readonly minTurnKey: string;
readonly beforeAnchorAt: string;
readonly beforeTurnKey: string;
}
const getThreadDetailByIdBounded = (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) =>
Effect.gen(function* () {
const [
threadRow,
@@ -2103,7 +2358,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadMessageRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadMessageRowsByThread({ threadId })
: listThreadMessageRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
@@ -2119,7 +2377,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadActivityRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
@@ -2174,6 +2435,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -2228,23 +2490,139 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
getThreadDetailByIdBounded(threadId, undefined);
// Bounds pathological fan-out: one user turn that spawned hundreds of
// subagent turns still pages in bounded chunks, at the cost of splitting the
// fan-out group across pages (the cursor continues the same group). Also
// structurally bounds the window scan via the candidates CTE's LIMIT.
const THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE = 150;
// Sentinels for unbounded keyset ends; "~" sorts after any ISO timestamp.
const ANCHOR_UNBOUNDED = "~";
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
threadId,
window,
) =>
// Read the thread detail and the snapshot sequence within a single
// transaction so the sequence is consistent with the returned state; a
// projector update landing between two separate reads could otherwise return
// a sequence ahead of the thread detail, causing the client to resume from
// too far and drop events.
// too far and drop events. Window resolution runs inside the same
// transaction so the page boundary is consistent with the returned rows.
sql
.withTransaction(
Effect.gen(function* () {
const thread = yield* getThreadDetailById(threadId);
if (window?.turnLimit === undefined) {
const thread = yield* getThreadDetailById(threadId);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
}
// A malformed or foreign-thread cursor falls back to the first page
// rather than failing: the client's stale cursor after a revert or
// reconnect should degrade to "reload recent history", not error.
const decodedCursor =
window.beforeCursor === undefined
? null
: decodeThreadDetailPageCursor(window.beforeCursor);
const cursor = decodedCursor?.threadId === threadId ? decodedCursor : null;
const windowRows = yield* listTurnWindowRows({
threadId,
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
userTurnLimit: window.turnLimit,
maxRawTurns: THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:decodeRows",
),
),
);
const oldest = windowRows[0];
// An empty window (no turns before the cursor, or a thread with no
// turns at all) still returns thread metadata with empty collections
// for turn-linked rows; turnless rows are bounded to the same empty
// range. The first page of a turnless thread stays unwindowed so
// pre-turn content (e.g. a just-created thread) is not hidden.
const bounds: ThreadDetailBounds | undefined =
oldest === undefined && cursor === null
? undefined
: {
minAnchorAt: oldest?.anchorAt ?? "",
minTurnKey: oldest?.turnKey ?? "",
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
};
// Empty window behind a cursor: nothing older remains.
const emptyBounds =
oldest === undefined && cursor !== null
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
: undefined;
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const hasMore =
oldest !== undefined &&
(yield* listTurnWindowRows({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnKey: oldest.turnKey,
userTurnLimit: 1,
maxRawTurns: 1,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:decodeRows",
),
),
)).length > 0;
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
const watermarkRow = yield* getThreadEventWatermarkRow({
threadId,
maxSequence: snapshotSequence,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:decodeRow",
),
),
);
const threadSequence = Option.match(watermarkRow, {
onNone: () => 0,
onSome: (row) => row.threadSequence ?? 0,
});
return Option.some({
snapshotSequence,
thread: thread.value,
page: {
beforeCursor:
hasMore && oldest !== undefined
? encodeThreadDetailPageCursor({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnId: oldest.turnKey,
})
: null,
hasMore,
snapshotSequence,
threadSequence,
},
});
}),
)
.pipe(
@@ -48,6 +48,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
@@ -345,6 +346,7 @@ describe("ProviderCommandReactor", () => {
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -352,6 +354,7 @@ describe("ProviderCommandReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -785,6 +788,123 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("pins the first user message when regeneration context is truncated", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const firstUserMessage = `Review subagent monitoring risks. ${"Opening context. ".repeat(200)}`;
const recentUserMessage = `LATEST FINDING: ${"implementation detail ".repeat(320)}`;
harness.generateThreadTitle.mockReturnValue(
Effect.succeed({ title: "Review subagent monitoring risks" }),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-existing-long"),
threadId: ThreadId.make("thread-1"),
title: "Generic PR review",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-before-long-title-regeneration"),
role: "user",
text: firstUserMessage,
attachments: [
{
type: "image",
id: "opening-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-middle-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("middle-message-before-long-title-regeneration"),
role: "user",
text: "Temporary handoff details.",
attachments: [
{
type: "image",
id: "middle-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-recent-turn-before-long-title-regeneration"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("recent-message-before-long-title-regeneration"),
role: "user",
text: recentUserMessage,
attachments: [
{
type: "image",
id: "recent-context-image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:02.000Z",
}),
);
await harness.runEffect(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-regenerate-long"),
threadId: ThreadId.make("thread-1"),
regenerateTitle: true,
}),
);
await harness.drain();
expect(harness.generateThreadTitle).toHaveBeenCalledTimes(1);
const input = harness.generateThreadTitle.mock.calls[0]?.[0];
if (!input) {
throw new Error("Expected a title generation input");
}
const message = input.message;
expect(message.startsWith("USER:\nReview subagent monitoring risks.")).toBe(true);
expect(message).toContain("[First user message truncated]");
expect(message).toContain("[Earlier content truncated]");
expect(message).toContain("image.png");
expect(message).toHaveLength(8_000);
expect(input.attachments?.map((attachment) => attachment.id)).toEqual([
"opening-context-image",
"recent-context-image",
]);
});
it("clears title regeneration state left pending across reactor startup", async () => {
const harness = await createHarness({
titleRegenerationBeforeStart: "one",
@@ -972,10 +1092,14 @@ describe("ProviderCommandReactor", () => {
expect(thread?.titleRegeneration).toBeNull();
});
it("keeps the full retained context and excludes attachments outside it", async () => {
it("pins the first user context and attachment before the retained tail", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const retainedContext = "x".repeat(8_000);
const firstUserContext = "USER:\nOld visual issue\n[Attachments: old-issue.png]";
const truncationMarker = "[Earlier content truncated]\n\n";
const retainedContext = "x".repeat(
8_000 - firstUserContext.length - "\n\n".length - truncationMarker.length,
);
await harness.runEffect(
harness.engine.dispatch({
@@ -1040,9 +1164,14 @@ describe("ProviderCommandReactor", () => {
await harness.drain();
expect(harness.generateThreadTitle.mock.calls[0]?.[0].message).toBe(
`[Earlier content truncated]\n\n${retainedContext}`,
`${firstUserContext}\n\n${truncationMarker}${retainedContext}`,
);
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toBeUndefined();
expect(harness.generateThreadTitle.mock.calls[0]?.[0].attachments).toEqual([
expect.objectContaining({
id: "old-title-context-image",
name: "old-issue.png",
}),
]);
});
it("does not overwrite a manual rename while title regeneration is running", async () => {
@@ -94,41 +94,61 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const DEFAULT_THREAD_TITLE = "New thread";
const MAX_REGENERATION_ATTACHMENTS = 4;
const MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;
const MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;
const THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
const FIRST_USER_CONTEXT_TRUNCATION_MARKER = "\n[First user message truncated]";
function formatThreadTitleContext(
messages: ReadonlyArray<{
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}>,
type ThreadTitleMessage = {
readonly role: "user" | "assistant" | "system";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
};
function formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {
if (message.role === "system") {
return undefined;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
return contents.length > 0 ? `${message.role.toUpperCase()}:\n${contents}` : undefined;
}
function limitFirstUserSection(section: string): string {
if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {
return section;
}
return `${section.slice(
0,
MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,
)}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;
}
function collectRecentThreadTitleContext(
messages: ReadonlyArray<ThreadTitleMessage>,
maxChars: number,
): {
readonly message: string;
readonly context: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly truncated: boolean;
} {
let context = "";
let truncated = false;
const retainedAttachments: Array<ChatAttachment> = [];
for (const message of messages.toReversed()) {
if (message.role === "system") {
continue;
}
const text = message.text.trim();
const attachmentSummary = (message.attachments ?? [])
.map((attachment) => attachment.name)
.join(", ");
const contents = [
...(text.length > 0 ? [text] : []),
...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),
].join("\n");
if (contents.length === 0) {
const section = formatThreadTitleSection(message);
if (section === undefined) {
continue;
}
const section = `${message.role.toUpperCase()}:\n${contents}`;
const separator = context.length > 0 ? "\n\n" : "";
const available = MAX_THREAD_TITLE_CONTEXT_CHARS - context.length - separator.length;
const available = maxChars - context.length - separator.length;
if (section.length > available) {
if (available > 0) {
context = `${section.slice(-available)}${separator}${context}`;
@@ -141,9 +161,54 @@ function formatThreadTitleContext(
retainedAttachments.unshift(...(message.attachments ?? []));
}
return { context, attachments: retainedAttachments, truncated };
}
function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {
readonly message: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
} {
const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);
if (!recent.truncated) {
return {
message: recent.context,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const firstUserMessage = messages.find(
(message) => message.role === "user" && formatThreadTitleSection(message),
);
const firstUserSection = firstUserMessage
? formatThreadTitleSection(firstUserMessage)
: undefined;
if (!firstUserMessage || !firstUserSection) {
return {
message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,
attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),
};
}
const pinnedSection = limitFirstUserSection(firstUserSection);
const recentContextBudget =
MAX_THREAD_TITLE_CONTEXT_CHARS -
pinnedSection.length -
"\n\n".length -
THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;
const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);
const pinnedAttachment = firstUserMessage.attachments?.[0];
const recentAttachments = retainedRecent.attachments.filter(
(attachment) => attachment.id !== pinnedAttachment?.id,
);
return {
message: truncated ? `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${context}` : context,
attachments: retainedAttachments.slice(-MAX_REGENERATION_ATTACHMENTS),
message: `${pinnedSection}\n\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,
attachments: [
...(pinnedAttachment ? [pinnedAttachment] : []),
...recentAttachments.slice(
-(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),
),
],
};
}
@@ -44,6 +44,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
@@ -237,6 +238,9 @@ describe("ProviderRuntimeIngestion", () => {
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
// Single shared liveness instance across ingestion (writer), the
// engine, and the snapshot query (reader).
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -3143,7 +3147,8 @@ describe("ProviderRuntimeIngestion", () => {
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started",
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:turn-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed",
@@ -3227,7 +3232,8 @@ describe("ProviderRuntimeIngestion", () => {
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:named-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed",
@@ -3318,7 +3324,8 @@ describe("ProviderRuntimeIngestion", () => {
await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:swept-task-1",
),
);
@@ -7,6 +7,8 @@ import {
type OrchestrationMessage,
type OrchestrationProposedPlanId,
CheckpointRef,
classifyTaskAgentKind,
EventId,
isToolLifecycleItemType,
ThreadId,
type ThreadTokenUsageSnapshot,
@@ -32,6 +34,7 @@ import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionT
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderRuntimeIngestionService,
@@ -307,6 +310,52 @@ function requestKindFromCanonicalRequestType(
}
}
/**
* Copies the optional TaskAgentLinkage bundle from a task.* runtime payload
* into the persisted activity payload. Identity fields ride on every row so
* client folds survive activity retention; absent fields stay absent.
*/
function taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {
const fields: Record<string, unknown> = {
// Server-stamped classification: persisted rows are self-describing, so
// clients trust the stamp instead of re-deriving agent-vs-background
// from taskType denylists and marker heuristics (legacy rows without a
// stamp keep the client fallback).
agentKind: classifyTaskAgentKind({
taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,
agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,
}),
};
for (const key of [
"taskType",
"agentId",
"title",
"role",
"model",
"effort",
"toolUseId",
"parentAgentId",
"workflowName",
"agentIndex",
"phaseIndex",
"phaseTitle",
"phases",
"attempt",
"runHandles",
"outputFile",
"agentPath",
"timelineBypass",
"typedUsage",
"status",
"error",
] as const) {
if (payload[key] !== undefined) {
fields[key] = payload[key];
}
}
return fields;
}
export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
@@ -505,6 +554,7 @@ export function runtimeEventToActivities(
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -515,7 +565,16 @@ export function runtimeEventToActivities(
case "task.progress": {
return [
{
id: event.eventId,
// Stable per-task id: progress is "latest state", not history, so
// each tick REPLACES the last via the activity upsert (PK + the
// replace-by-id apply in projector and client reducer). Keeps one
// progress row per task instead of thousands, so a large fleet's
// ticks can no longer evict its own start/terminal rows out of
// the 500-row retention window. Thread-scoped: activity_id is a
// GLOBAL primary key and Claude task ids are session-local, so a
// bare taskId could collide across threads and steal another
// thread's row (review finding).
id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
@@ -532,6 +591,71 @@ export function runtimeEventToActivities(
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.updated": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: event.payload.status === "failed" ? "error" : "info",
kind: "task.updated",
summary:
event.payload.status === "failed"
? "Task failed"
: event.payload.status
? `Task ${event.payload.status}`
: "Task updated",
payload: {
taskId: event.payload.taskId,
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),
...(event.payload.isBackgrounded !== undefined
? { isBackgrounded: event.payload.isBackgrounded }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "tool.progress": {
// Only agent-owned heartbeats are persisted: they feed the owning
// agent's activity line. Parent-conversation tool progress stays
// ephemeral (item lifecycle already covers it).
if (event.payload.taskId === undefined) {
return [];
}
return [
{
// Same stable-id treatment as task.progress: a heartbeat is
// "what is this agent doing right now", so one row per task
// (thread-scoped for the same global-PK collision reason).
id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "tool.progress",
summary: event.payload.toolName ?? "Tool progress",
payload: {
taskId: event.payload.taskId,
...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.elapsedSeconds !== undefined
? { elapsedSeconds: event.payload.elapsedSeconds }
: {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -565,6 +689,7 @@ export function runtimeEventToActivities(
}
: {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -630,6 +755,10 @@ export function runtimeEventToActivities(
...(event.payload.status ? { status: event.payload.status } : {}),
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -652,6 +781,10 @@ export function runtimeEventToActivities(
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -673,6 +806,10 @@ export function runtimeEventToActivities(
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -688,6 +825,7 @@ export function runtimeEventToActivities(
}
const make = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1756,6 +1894,43 @@ const make = Effect.gen(function* () {
yield* rememberTaskDescription(thread.id, event.payload.taskId, description);
}
}
// Sidebar background liveness: fed from the same lifecycle stream,
// read by the shell query at mapping time (no persistence).
switch (event.type) {
case "task.started":
case "task.progress":
case "task.updated":
case "task.completed": {
const payload = event.payload as {
taskId: string;
taskType?: string;
status?: string;
agentId?: string;
};
threadBackgroundLiveness.recordTaskLiveness({
threadId: thread.id,
taskId: payload.taskId,
taskType: payload.taskType,
status: payload.status,
agentId: payload.agentId,
kind:
event.type === "task.started"
? "started"
: event.type === "task.progress"
? "progress"
: event.type === "task.updated"
? "updated"
: "completed",
});
break;
}
case "session.exited":
threadBackgroundLiveness.clearThreadLiveness(thread.id);
break;
default:
break;
}
let taskTitle: string | undefined;
if (event.type === "task.completed") {
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
+4
View File
@@ -13,6 +13,8 @@ import {
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -42,6 +44,8 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -17,6 +17,7 @@ import type {
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
OrchestrationThreadDetailWindow,
OrchestrationThreadShell,
ProjectId,
ThreadId,
@@ -174,9 +175,16 @@ export interface ProjectionSnapshotQueryShape {
* sequence in one consistent transaction, so the returned `snapshotSequence`
* exactly matches the state reflected in `thread` (no interleaving projector
* update between the two reads).
*
* When `window` is provided, the thread's messages, activities, proposed
* plans, and checkpoints are bounded to a page of recent turns and the
* response carries `page` metadata (see `OrchestrationThreadDetailWindow`).
* Without a window the full thread is returned with no `page` field —
* pagination is strictly opt-in.
*/
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
window?: OrchestrationThreadDetailWindow,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
}
@@ -0,0 +1,173 @@
import { describe, expect, it } from "vite-plus/test";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
describe("ThreadBackgroundLiveness", () => {
it("agents present as working; monitors as monitoring; agents win", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-1";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("terminal rows without a taskType still clear monitor entries", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-2";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
// Terminal tick arrives with no taskType (common on task.completed).
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: undefined,
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("nested agents (agentId + agent taskType) still count toward liveness", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-nested";
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: "completed",
kind: "completed",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("untyped rows count as agents; idle is not live; agent-owned tasks are ignored", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-3";
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "idle",
kind: "updated",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
liveness.recordTaskLiveness({
threadId,
taskId: "sh:1",
taskType: "local_bash",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("reclassification moves a task between buckets instead of duplicating it", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-reclass";
// First seen without a taskType: counts as an agent.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: undefined,
status: "running",
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
// Later transition reveals it's a shell: downgrade to monitoring, not
// a stale duplicate pinning "working".
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
// Turning out to be inert or agent-owned drops the prior entry too.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("plan tasks are inert; clear removes everything; instances are isolated", () => {
const a = ThreadBackgroundLiveness.make();
const b = ThreadBackgroundLiveness.make();
a.recordTaskLiveness({
threadId: "t",
taskId: "p1",
taskType: "plan",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
a.recordTaskLiveness({
threadId: "t",
taskId: "a1",
taskType: "local_workflow",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBe("working");
expect(b.getThreadBackgroundLiveness("t")).toBeNull();
a.clearThreadLiveness("t");
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
});
});
@@ -0,0 +1,160 @@
/**
* ThreadBackgroundLivenessService - in-memory per-thread background liveness
* for the sidebar status pill.
*
* The turn can settle while native background work runs on (subagent fleets,
* workflow runs, Monitor watch loops); the shell previously showed nothing.
* Ingestion records task lifecycle transitions and the shell query reads the
* derived state at mapping time — no persistence, no migration. After a
* server restart the registry is empty until new task events arrive, which
* matches reality: orphaned background work is not live.
*
* "monitoring" is reserved for watch loops (monitor tasks and background
* shells) when they are the ONLY live work; any agent work presents as
* "working".
*
* @module ThreadBackgroundLivenessService
*/
import { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export type ThreadBackgroundLiveness = "working" | "monitoring" | null;
interface ThreadLivenessState {
readonly agents: Set<string>;
readonly monitors: Set<string>;
}
// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:
// watch loops — monitor tasks plus background shells, which in practice are
// PR babysitting/log tails since pacing sleeps complete inside the turn;
// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's
// agentKind stamp, and the client fold can never drift apart.
const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
"completed",
"failed",
"stopped",
"cancelled",
"interrupted",
]);
export class ThreadBackgroundLivenessService extends Context.Service<
ThreadBackgroundLivenessService,
{
/**
* Feed one task lifecycle transition. taskType may be absent on
* synthesized rows (workflow members, Codex children) — those count as
* agents. agentId marks a task launched from inside a subagent: its
* internal shells are covered by the owning agent's liveness, but a
* NESTED AGENT (agentId + agent-flavored taskType) still counts — it
* can outlive its parent and must keep the thread Working.
*/
readonly recordTaskLiveness: (input: {
readonly threadId: string;
readonly taskId: string;
readonly taskType: string | undefined;
readonly status: string | undefined;
readonly kind: "started" | "progress" | "updated" | "completed";
readonly agentId?: string | undefined;
}) => void;
/** Session death orphans all of a thread's background work. */
readonly clearThreadLiveness: (threadId: string) => void;
/**
* Two-state vocabulary by design: any live agent work is "working";
* "monitoring" only when watch loops are the ONLY live work.
*/
readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;
}
>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}
export function make(): ThreadBackgroundLivenessService["Service"] {
const stateByThreadId = new Map<string, ThreadLivenessState>();
const stateFor = (threadId: string): ThreadLivenessState => {
const existing = stateByThreadId.get(threadId);
if (existing) {
return existing;
}
const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };
stateByThreadId.set(threadId, created);
return created;
};
// Classification is per-transition, not sticky: a task first seen without
// a taskType may later reveal itself as a shell, become inert, or turn out
// to be agent-owned. Every path drops any prior entry for the taskId so a
// stale bucket assignment can't pin the thread's status (review finding).
const drop = (threadId: string, taskId: string) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return;
}
state.agents.delete(taskId);
state.monitors.delete(taskId);
if (state.agents.size === 0 && state.monitors.size === 0) {
stateByThreadId.delete(threadId);
}
};
return {
recordTaskLiveness: (input) => {
const taskType = input.taskType;
if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {
drop(input.threadId, input.taskId);
return;
}
// A subagent's internal non-agent work (its own shells/monitors) is
// covered by the owning agent's liveness. Nested agents fall through:
// they can outlive their parent (review finding).
if (
input.agentId !== undefined &&
(taskType === undefined || MONITOR_TASK_TYPES.has(taskType))
) {
drop(input.threadId, input.taskId);
return;
}
// Idle counts as not-live: a resting (resumable) Codex child isn't
// doing anything, and an all-idle fleet must not pin Working.
const terminal =
input.kind === "completed" ||
input.status === "idle" ||
(input.status !== undefined && TERMINAL_STATUSES.has(input.status));
if (terminal) {
drop(input.threadId, input.taskId);
return;
}
drop(input.threadId, input.taskId);
const state = stateFor(input.threadId);
const bucket =
taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;
bucket.add(input.taskId);
},
clearThreadLiveness: (threadId) => {
stateByThreadId.delete(threadId);
},
getThreadBackgroundLiveness: (threadId) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return null;
}
if (state.agents.size > 0) {
return "working";
}
if (state.monitors.size > 0) {
return "monitoring";
}
return null;
},
};
}
export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));
@@ -0,0 +1,226 @@
import {
CommandId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-01-01T00:00:00.000Z";
const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
readonly snoozedUntil?: string | null;
readonly snoozedAt?: string | null;
}): OrchestrationReadModel {
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: input.archivedAt ?? null,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? (input.settledOverride === "settled" ? NOW : null),
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
it.layer(NodeServices.layer)("pinned thread decider", (it) => {
it.effect("pins a thread, stamping pinnedAt and updatedAt together", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(events[0].payload.updatedAt);
}
}),
);
it.effect("re-pinning preserves the original pinnedAt and updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-again"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinnedAt).toBe(PINNED_AT);
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("unpins a pinned thread", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("unpinning an unpinned thread preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.unpin",
commandId: CommandId.make("cmd-unpin-noop"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.unpinned");
if (events[0]?.type === "thread.unpinned") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("pinning a settled thread also un-settles it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-settled"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ settledOverride: "settled" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsettled"]);
const unsettled = events.find((entry) => entry.type === "thread.unsettled");
if (unsettled?.type === "thread.unsettled") {
expect(unsettled.payload.reason).toBe("user");
}
}),
);
it.effect("pinning a snoozed thread also wakes it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-snoozed"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ snoozedUntil: "1970-01-02T09:00:00.000Z" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned", "thread.unsnoozed"]);
}),
);
it.effect("pinning an unparked thread emits only thread.pinned", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-plain"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.pinned"]);
}),
);
it.effect("settling a pinned thread also unpins it", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-pinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ pinnedAt: PINNED_AT }),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unpinned"]);
}),
);
it.effect("settling an unpinned thread emits no unpin event", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-unpinned"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events.map((entry) => entry.type)).toEqual(["thread.settled"]);
}),
);
it.effect("rejects pinning an archived thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-archived"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel({ archivedAt: NOW }),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
+117 -2
View File
@@ -487,14 +487,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// settledAt: the engine rejects zero-event commands, and bulk-settle /
// double-click must stay silent no-ops rather than surface errors.
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
return {
const settledEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.settled",
type: "thread.settled" as const,
payload: {
threadId: command.threadId,
settledAt: alreadySettled ? thread.settledAt : occurredAt,
@@ -504,6 +504,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
},
};
// Settling is "I'm done with this": it clears a pin the same way it
// parks the thread. Without this, settling a pinned thread would only
// stamp invisible state — the pin would hold the card in place until
// a separate unpin.
if (thread.pinnedAt == null) {
return settledEvent;
}
return [
settledEvent,
{
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned" as const,
payload: {
threadId: command.threadId,
updatedAt: occurredAt,
},
},
];
}
case "thread.unsettle": {
@@ -630,6 +653,98 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
// Re-pinning an already-pinned thread is a duplicate (double-click,
// raced clients): re-emit with the original timestamps so the
// projection is a no-op. Pinning has no lifecycle invariants — a pin
// only ever promotes visibility, so it can never hide pending work.
const existingPinnedAt = thread.pinnedAt ?? null;
const pinnedEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pinned" as const,
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
// Pinning is a promotion: it clears the parked states rather than
// silently outranking them. An explicit settle un-settles (reason
// "user", same override the un-settle button stamps), and a snooze's
// return ticket is spent — the thread is on top NOW, not on Tuesday.
const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (thread.settledOverride === "settled") {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
if (thread.snoozedUntil != null) {
promotionEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "user",
updatedAt: occurredAt,
},
});
}
return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
}
case "thread.unpin": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Idempotent by re-emission (see thread.settle): unpinning a thread
// that is not pinned lands on the same null state without churning
// updatedAt.
const alreadyUnpinned = thread.pinnedAt == null;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.unpinned",
payload: {
threadId: command.threadId,
updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
+11 -1
View File
@@ -66,7 +66,17 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(args.params.threadId)
.getThreadDetailSnapshot(
args.params.threadId,
args.payload.turnLimit === undefined
? undefined
: {
turnLimit: args.payload.turnLimit,
...(args.payload.beforeCursor !== undefined
? { beforeCursor: args.payload.beforeCursor }
: {}),
},
)
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),
@@ -0,0 +1,77 @@
import {
CommandId,
EventId,
ProjectId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
it.effect("projects pin lifecycle events", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinnedAt ?? null).toBeNull();
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(pinned.threads[0]?.pinnedAt).toBe(now);
const unpinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
@@ -23,7 +23,9 @@ import {
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
ThreadUnsettledPayload,
ThreadUnsnoozedPayload,
@@ -394,6 +396,28 @@ export function projectEvent(
})),
);
case "thread.pinned":
return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unpinned":
return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -5,6 +5,7 @@ import { OrchestrationEventStoreLive } from "../persistence/Layers/Orchestration
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
@@ -19,7 +20,10 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
// Shared background-liveness registry: written by runtime ingestion,
// read by the snapshot query. provideMerge feeds the same instance to
// the snapshot query here and re-exports it for runtime ingestion.
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
export const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff. Show more