Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e94ab704bb | ||
|
|
ef388d8ec6 | ||
|
|
7551e7d7a8 | ||
|
|
05e6ead25a | ||
|
|
a279bca0f8 | ||
|
|
5e805ec7f8 | ||
|
|
bd934136c4 | ||
|
|
21ca57b213 | ||
|
|
ae2610b8c1 | ||
|
|
9382e9024c |
No files matched your search
@@ -65,6 +65,9 @@ export interface ThreadDetailScreenProps {
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly hasMoreOlderActivities: boolean;
|
||||
readonly loadingOlderActivities: boolean;
|
||||
readonly onLoadOlderActivities: () => void;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -422,6 +425,9 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
hasMoreOlder={props.hasMoreOlderActivities}
|
||||
loadingOlder={props.loadingOlderActivities}
|
||||
onLoadOlder={props.onLoadOlderActivities}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
|
||||
@@ -139,6 +139,10 @@ export interface ThreadFeedProps {
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Older history beyond the live activity window can be lazy-loaded on scroll-up. */
|
||||
readonly hasMoreOlder?: boolean;
|
||||
readonly loadingOlder?: boolean;
|
||||
readonly onLoadOlder?: () => void;
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -1459,6 +1463,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
// Reaching the top (oldest) lazy-loads older history. The hook keys an
|
||||
// in-flight guard by thread, so repeated fires during scroll coalesce.
|
||||
const { hasMoreOlder, loadingOlder, onLoadOlder } = props;
|
||||
const onStartReachedOlderHistory = useCallback(() => {
|
||||
if (hasMoreOlder && !loadingOlder) {
|
||||
onLoadOlder?.();
|
||||
}
|
||||
}, [hasMoreOlder, loadingOlder, onLoadOlder]);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1751,9 +1764,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
onStartReached={onStartReachedOlderHistory}
|
||||
onStartReachedThreshold={0.5}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
usesNativeAutomaticInsets && !loadingOlder ? null : (
|
||||
<View style={{ height: usesNativeAutomaticInsets ? undefined : topContentInset }}>
|
||||
{loadingOlder ? <ActivityIndicator style={{ marginTop: 8 }} /> : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
@@ -1761,7 +1780,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
|
||||
{props.feed.length === 0 && hasMoreOlder ? (
|
||||
// The window can derive zero visible entries while older history
|
||||
// exists — without scrollable content `onStartReached` can never
|
||||
// fire, so give the user an explicit affordance instead of the
|
||||
// empty-state placeholder.
|
||||
<View style={StyleSheet.absoluteFill}>
|
||||
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
|
||||
{loadingOlder ? (
|
||||
<ActivityIndicator />
|
||||
) : (
|
||||
<TouchableOpacity accessibilityRole="button" onPress={() => onLoadOlder?.()}>
|
||||
<Text className="text-sm text-muted-foreground">Load older history</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
{props.feed.length === 0 && !hasMoreOlder && props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
|
||||
@@ -194,7 +194,9 @@ function ThreadRouteContent(
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
// Derive pending requests from the FULL loaded set (older pages + live
|
||||
// window) so a prompt the user scrolled back to load still surfaces.
|
||||
const requests = useSelectedThreadRequests(composer.mergedActivities);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const navigation = useNavigation();
|
||||
const params = props.route.params;
|
||||
@@ -767,6 +769,9 @@ function ThreadRouteContent(
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
hasMoreOlderActivities={composer.hasMoreOlderActivities}
|
||||
loadingOlderActivities={composer.loadingOlderActivities}
|
||||
onLoadOlderActivities={composer.onLoadOlderActivities}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderApprovalDecision,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
@@ -53,7 +57,18 @@ function setUserInputDraftCustomAnswer(
|
||||
});
|
||||
}
|
||||
|
||||
export function useSelectedThreadRequests() {
|
||||
/**
|
||||
* Pending approval / user-input requests for the selected thread.
|
||||
*
|
||||
* `activities` should be the FULL loaded set (lazy-loaded older pages + the
|
||||
* windowed live view, i.e. `useThreadComposerState().mergedActivities`): the
|
||||
* detail snapshot windows activities to the most recent page, so deriving from
|
||||
* `selectedThread.activities` alone would hide a prompt the user scrolled back
|
||||
* to load. Falls back to the live window when not provided. Deriving from the
|
||||
* merged set is sound — resolutions are always newer than their requests, so a
|
||||
* loaded request whose resolution exists always has that resolution loaded too.
|
||||
*/
|
||||
export function useSelectedThreadRequests(activities?: ReadonlyArray<OrchestrationThreadActivity>) {
|
||||
const respondToApproval = useAtomCommand(
|
||||
threadEnvironment.respondToApproval,
|
||||
"thread approval response",
|
||||
@@ -70,16 +85,20 @@ export function useSelectedThreadRequests() {
|
||||
null,
|
||||
);
|
||||
|
||||
const requestActivities = activities ?? selectedThread?.activities ?? null;
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
() => (requestActivities ? derivePendingApprovals(requestActivities) : []),
|
||||
[requestActivities],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
// The derivations sort ascending by createdAt; surface the NEWEST open
|
||||
// request. With lazy-loaded older pages in the set, index 0 could be an
|
||||
// ancient dangling request hijacking the prompt for the current one.
|
||||
const activePendingApproval = activePendingApprovals.at(-1) ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
() => (requestActivities ? derivePendingUserInputs(requestActivities) : []),
|
||||
[requestActivities],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInput = activePendingUserInputs.at(-1) ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedThreadShell
|
||||
? (userInputDraftsByRequestKey[
|
||||
|
||||
@@ -6,11 +6,17 @@ import {
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
useOlderThreadActivities,
|
||||
type OlderActivitiesCursor,
|
||||
} from "@t3tools/client-runtime/state/older-thread-activities";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
|
||||
@@ -36,11 +42,15 @@ import {
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
import { orchestrationEnvironment } from "../state/orchestration";
|
||||
import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
|
||||
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
@@ -89,9 +99,56 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
// ── Older-history lazy-load (shared engine; see useOlderThreadActivities) ──
|
||||
// The detail snapshot windows activities to the most recent page (the server
|
||||
// sets `hasMoreActivities`); older pages are fetched on demand and prepended.
|
||||
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const selectedEnvironmentIdForActivities = selectedThreadShell?.environmentId ?? null;
|
||||
const selectedThreadIdForActivities = selectedThreadShell?.id ?? null;
|
||||
const loadOlderActivitiesPage = useCallback(
|
||||
async (cursor: OlderActivitiesCursor) => {
|
||||
if (selectedEnvironmentIdForActivities === null || selectedThreadIdForActivities === null) {
|
||||
return null;
|
||||
}
|
||||
const result = await loadThreadActivities({
|
||||
environmentId: selectedEnvironmentIdForActivities,
|
||||
input: { threadId: selectedThreadIdForActivities, ...cursor },
|
||||
});
|
||||
if (result._tag !== "Success") {
|
||||
// Surface real failures (a spinner that quietly gives up reads as
|
||||
// missing history); keep `hasMore` so scrolling back retries.
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
setPendingConnectionError("Could not load older thread history.");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return result.value;
|
||||
},
|
||||
[selectedEnvironmentIdForActivities, selectedThreadIdForActivities, loadThreadActivities],
|
||||
);
|
||||
const {
|
||||
mergedActivities,
|
||||
hasMoreOlder: hasMoreOlderActivities,
|
||||
loadingOlder: loadingOlderActivities,
|
||||
loadOlder: onLoadOlderActivities,
|
||||
} = useOlderThreadActivities({
|
||||
threadKey: selectedThreadShell
|
||||
? `${selectedThreadShell.environmentId}\u0000${selectedThreadShell.id}`
|
||||
: null,
|
||||
liveActivities: selectedThreadDetail?.activities ?? EMPTY_ACTIVITIES,
|
||||
hasMoreLiveActivities: selectedThreadDetail?.hasMoreActivities ?? false,
|
||||
loadPage: loadOlderActivitiesPage,
|
||||
});
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed({ ...selectedThreadDetail, activities: mergedActivities })
|
||||
: [],
|
||||
[selectedThreadDetail, mergedActivities],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
@@ -299,6 +356,13 @@ export function useThreadComposerState() {
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
// Lazy-loaded older pages + the live window — the full loaded activity set.
|
||||
// Request derivations must run over this (not the windowed live set alone)
|
||||
// so prompts pulled in by scroll-up still surface, matching web.
|
||||
mergedActivities,
|
||||
hasMoreOlderActivities,
|
||||
loadingOlderActivities,
|
||||
onLoadOlderActivities,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPasteIntoDraft,
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
|
||||
|
||||
describe("buildAssetResponseHeaders", () => {
|
||||
it("forces non-image assets to download without overriding the client filename", () => {
|
||||
expect(buildAssetResponseHeaders({ download: true })).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"Content-Disposition": "attachment",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not force image assets to download", () => {
|
||||
expect(buildAssetResponseHeaders({ download: false })).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
export function buildAssetResponseHeaders(input: { readonly download?: boolean }) {
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(input.download ? { "Content-Disposition": "attachment" } : {}),
|
||||
};
|
||||
}
|
||||
@@ -198,32 +198,6 @@ describe("AssetAccess", () => {
|
||||
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: false,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("marks non-image attachment capabilities for download", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002";
|
||||
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
|
||||
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "attachment", attachmentId },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "ignored.pdf")).toEqual({
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: true,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
} from "../auth/utils.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import { SAFE_IMAGE_FILE_EXTENSIONS } from "../imageMime.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
@@ -92,11 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
|
||||
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
|
||||
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
|
||||
|
||||
export type ResolvedAsset = {
|
||||
readonly kind: "file";
|
||||
readonly path: string;
|
||||
readonly download?: boolean;
|
||||
};
|
||||
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
|
||||
|
||||
function decodeClaims(encodedPayload: string): AssetClaims | null {
|
||||
try {
|
||||
@@ -388,17 +383,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (!Option.isSome(info) || info.value.type !== "File") {
|
||||
return null;
|
||||
}
|
||||
// Non-image attachments are downloaded rather than rendered inline so the
|
||||
// same-origin asset route never interprets uploaded content (e.g. HTML/XML).
|
||||
const extension = attachmentPath.slice(attachmentPath.lastIndexOf(".")).toLowerCase();
|
||||
return {
|
||||
kind: "file",
|
||||
path: attachmentPath,
|
||||
download: !SAFE_IMAGE_FILE_EXTENSIONS.has(extension),
|
||||
} satisfies ResolvedAsset;
|
||||
return Option.isSome(info) && info.value.type === "File"
|
||||
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { appendFileAttachmentPromptText } from "./attachmentPrompt.ts";
|
||||
|
||||
const attachmentsDir = NodePath.join(NodePath.sep, "tmp", "t3-attachment-prompt");
|
||||
|
||||
describe("attachmentPrompt", () => {
|
||||
it("appends a prompt line for file attachments", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 2048,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000001.txt",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`hello\n\n[Attached file: ${attachmentPath} (notes.txt, text/plain, 2.0 KB). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns text unchanged when only image attachments are present", () => {
|
||||
expect(
|
||||
appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000002",
|
||||
name: "screen.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe("hello");
|
||||
});
|
||||
|
||||
it("returns only the prompt lines when the text is empty", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000003",
|
||||
name: "data.csv",
|
||||
mimeType: "text/csv",
|
||||
sizeBytes: 12,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000003.csv",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`[Attached file: ${attachmentPath} (data.csv, text/csv, 12 B). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
|
||||
it("strips control characters, brackets, and parentheses from attachment names", () => {
|
||||
const result = appendFileAttachmentPromptText({
|
||||
text: "hello",
|
||||
attachmentsDir,
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000004",
|
||||
name: "a(b)\u0001[c].txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
const attachmentPath = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000004.txt",
|
||||
);
|
||||
expect(result).toBe(
|
||||
`hello\n\n[Attached file: ${attachmentPath} (a b c .txt, text/plain, 5 B). Read it from disk when needed.]`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { resolveAttachmentPath } from "./attachmentStore.ts";
|
||||
|
||||
const SIZE_LABEL_UNITS = ["B", "KB", "MB"] as const;
|
||||
|
||||
function formatSizeLabel(sizeBytes: number): string {
|
||||
let value = sizeBytes;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < SIZE_LABEL_UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const rounded = unitIndex === 0 ? String(value) : value.toFixed(1);
|
||||
return `${rounded} ${SIZE_LABEL_UNITS[unitIndex]}`;
|
||||
}
|
||||
|
||||
function sanitizePromptFileName(name: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return name.replace(/[\u0000-\u001f\u007f()[\]]+/gu, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-image attachments are delivered by reference: the file already lives on
|
||||
* the server's disk, so the provider agent reads it with its own tools. Images
|
||||
* keep their native content-block path and are not mentioned here.
|
||||
*/
|
||||
export function appendFileAttachmentPromptText(input: {
|
||||
readonly text: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}): string {
|
||||
const lines: Array<string> = [];
|
||||
for (const attachment of input.attachments) {
|
||||
if (attachment.type !== "file") {
|
||||
continue;
|
||||
}
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
continue;
|
||||
}
|
||||
const name = sanitizePromptFileName(attachment.name);
|
||||
lines.push(
|
||||
`[Attached file: ${attachmentPath} (${name}, ${attachment.mimeType}, ${formatSizeLabel(attachment.sizeBytes)}). Read it from disk when needed.]`,
|
||||
);
|
||||
}
|
||||
if (lines.length === 0) {
|
||||
return input.text;
|
||||
}
|
||||
const joined = lines.join("\n");
|
||||
return input.text.trim().length > 0 ? `${input.text}\n\n${joined}` : joined;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import * as NodePath from "node:path";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
attachmentRelativePath,
|
||||
createAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
@@ -45,37 +44,6 @@ describe("attachmentStore", () => {
|
||||
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||
});
|
||||
|
||||
it("builds file attachment relative paths with the inferred file extension", () => {
|
||||
expect(
|
||||
attachmentRelativePath({
|
||||
type: "file",
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
}),
|
||||
).toBe("thread-1-00000000-0000-4000-8000-000000000001.pdf");
|
||||
});
|
||||
|
||||
it("resolves attachment path by id for a written file attachment extension", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
);
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const pdfPath = NodePath.join(attachmentsDir, `${attachmentId}.pdf`);
|
||||
NodeFS.writeFileSync(pdfPath, Buffer.from("hello"));
|
||||
|
||||
const resolved = resolveAttachmentPathById({
|
||||
attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pdfPath);
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
|
||||
@@ -8,16 +8,9 @@ import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import {
|
||||
inferFileExtension,
|
||||
inferImageExtension,
|
||||
SAFE_FILE_EXTENSIONS,
|
||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||
} from "./imageMime.ts";
|
||||
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [
|
||||
...new Set([...SAFE_IMAGE_FILE_EXTENSIONS, ...SAFE_FILE_EXTENSIONS, ".bin"]),
|
||||
];
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
@@ -70,13 +63,6 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
case "file": {
|
||||
const extension = inferFileExtension({
|
||||
mimeType: attachment.mimeType,
|
||||
fileName: attachment.name,
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,8 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getThreadActivitiesPage: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request thread activities"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
@@ -185,6 +187,8 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getThreadActivitiesPage: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request thread activities"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
@@ -268,6 +272,8 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getThreadActivitiesPage: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request thread activities"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
@@ -336,6 +342,8 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getThreadActivitiesPage: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request thread activities"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
@@ -389,6 +397,8 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getThreadActivitiesPage: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request thread activities"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
|
||||
@@ -337,7 +337,9 @@ const dispatchLiveOrchestrationCommand = (
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
// Project resolution only reads `.projects`; the command read model returns the
|
||||
// same shape without loading the heavy per-thread activity/message tables.
|
||||
return yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
|
||||
@@ -25,7 +25,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { buildAssetResponseHeaders } from "./assetResponseHeaders.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
@@ -195,7 +194,10 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: buildAssetResponseHeaders(asset),
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { inferFileExtension, inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
describe("imageMime", () => {
|
||||
it("parses base64 data URL with mime type", () => {
|
||||
@@ -92,39 +92,4 @@ describe("imageMime", () => {
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||
});
|
||||
|
||||
it("infers file extension from an allowlisted file name extension", () => {
|
||||
expect(
|
||||
inferFileExtension({ mimeType: "application/octet-stream", fileName: "report.PDF" }),
|
||||
).toBe(".pdf");
|
||||
});
|
||||
|
||||
it("infers file extension from the last segment of a multi-dot file name", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/octet-stream", fileName: "a.b.csv" })).toBe(
|
||||
".csv",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to an allowlisted mime extension when the file name extension is unsafe", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/pdf", fileName: "notes.exe" })).toBe(".pdf");
|
||||
});
|
||||
|
||||
it("falls back to an allowlisted mime extension when the file name has no extension", () => {
|
||||
expect(inferFileExtension({ mimeType: "text/plain", fileName: "notes" })).toBe(".txt");
|
||||
});
|
||||
|
||||
it("defaults file extension to .bin when neither file name nor mime is allowlisted", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "payload.exe" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: "notes" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults dotfile names without an allowlisted mime to .bin", () => {
|
||||
expect(inferFileExtension({ mimeType: "application/x-unknown", fileName: ".env" })).toBe(
|
||||
".bin",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -112,48 +112,6 @@ export function parseBase64DataUrl(
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
export const SAFE_FILE_EXTENSIONS = new Set([
|
||||
".csv",
|
||||
".diff",
|
||||
".docx",
|
||||
".gz",
|
||||
".json",
|
||||
".jsonl",
|
||||
".log",
|
||||
".md",
|
||||
".patch",
|
||||
".pdf",
|
||||
".pptx",
|
||||
".tar",
|
||||
".toml",
|
||||
".tsv",
|
||||
".txt",
|
||||
".xlsx",
|
||||
".xml",
|
||||
".yaml",
|
||||
".yml",
|
||||
".zip",
|
||||
]);
|
||||
|
||||
export function inferFileExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const fileName = input.fileName?.trim() ?? "";
|
||||
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||
if (SAFE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||
return fileNameExtension;
|
||||
}
|
||||
|
||||
// Mime.getExtension returns dot-less extensions ("pdf"), the sets hold
|
||||
// dotted ones (".pdf").
|
||||
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||
const dottedMimeExtension = fromMimeExtension ? `.${fromMimeExtension}` : null;
|
||||
if (dottedMimeExtension && SAFE_FILE_EXTENSIONS.has(dottedMimeExtension)) {
|
||||
return dottedMimeExtension;
|
||||
}
|
||||
|
||||
return ".bin";
|
||||
}
|
||||
|
||||
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const key = input.mimeType.toLowerCase();
|
||||
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||
|
||||
@@ -201,6 +201,7 @@ describe("OrchestrationEngine", () => {
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
|
||||
@@ -928,214 +928,6 @@ it.layer(
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-file-gc-")),
|
||||
)("OrchestrationProjectionPipeline", (it) => {
|
||||
it.effect("keeps referenced file attachments and prunes orphans when a thread is reverted", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("Thread Revert.Docs");
|
||||
const keepAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000001";
|
||||
const removeAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000002";
|
||||
const orphanAttachmentId = "thread-revert-docs-00000000-0000-4000-8000-000000000003";
|
||||
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-revert-docs-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-revert-docs"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-revert-docs"),
|
||||
title: "Project Revert Docs",
|
||||
workspaceRoot: "/tmp/project-revert-docs",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-revert-docs-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-revert-docs"),
|
||||
title: "Thread Revert Docs",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.make("evt-revert-docs-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId: TurnId.make("turn-keep"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.make("message-keep"),
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-revert-docs-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-keep"),
|
||||
role: "assistant",
|
||||
text: "Keep",
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: keepAttachmentId,
|
||||
name: "keep.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
turnId: TurnId.make("turn-keep"),
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.make("evt-revert-docs-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnId: TurnId.make("turn-remove"),
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-docs/turn/2"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.make("message-remove"),
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-revert-docs-6"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-6"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-6"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-remove"),
|
||||
role: "assistant",
|
||||
text: "Remove",
|
||||
attachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: removeAttachmentId,
|
||||
name: "remove.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
turnId: TurnId.make("turn-remove"),
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.pdf`);
|
||||
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.pdf`);
|
||||
const orphanPath = path.join(attachmentsDir, `${orphanAttachmentId}.pdf`);
|
||||
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(keepPath, "keep");
|
||||
yield* fileSystem.writeFileString(removePath, "remove");
|
||||
yield* fileSystem.writeFileString(orphanPath, "orphan");
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isTrue(yield* exists(removePath));
|
||||
assert.isTrue(yield* exists(orphanPath));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.reverted",
|
||||
eventId: EventId.make("evt-revert-docs-7"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-revert-docs-7"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-revert-docs-7"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount: 1,
|
||||
},
|
||||
});
|
||||
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isFalse(yield* exists(removePath));
|
||||
assert.isFalse(yield* exists(orphanPath));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))(
|
||||
"OrchestrationProjectionPipeline",
|
||||
(it) => {
|
||||
|
||||
@@ -338,6 +338,9 @@ function collectThreadAttachmentRelativePaths(
|
||||
const relativePaths = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
continue;
|
||||
|
||||
@@ -342,6 +342,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
],
|
||||
hasMoreActivities: false,
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: asTurnId("turn-1"),
|
||||
@@ -974,6 +975,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
|
||||
// Well under the window — nothing older to lazy-load.
|
||||
assert.equal(threadDetail.value.hasMoreActivities, false);
|
||||
}
|
||||
|
||||
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
|
||||
@@ -1153,6 +1156,254 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"windows thread-detail activities to the most recent 500 and pages older on demand",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id, title, workspace_root, default_model_selection_json,
|
||||
scripts_json, created_at, updated_at, deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1', 'Project 1', '/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
|
||||
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id, project_id, title, model_selection_json, runtime_mode,
|
||||
interaction_mode, branch, worktree_path, latest_turn_id,
|
||||
latest_user_message_at, pending_approval_count, pending_user_input_count,
|
||||
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1', 'project-1', 'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
|
||||
NULL, NULL, NULL, NULL, 0, 0, 0,
|
||||
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
|
||||
)
|
||||
`;
|
||||
|
||||
// 600 activities (sequence 1..600); the detail load must return only the
|
||||
// most recent 500 (sequence 101..600), re-sorted ascending for display.
|
||||
const total = 600;
|
||||
yield* Effect.forEach(
|
||||
Array.from({ length: total }, (_unused, index) => index + 1),
|
||||
(seq) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
)
|
||||
VALUES (
|
||||
${`activity-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
|
||||
'info', 'runtime.note', ${`act-${seq}`}, '{}', ${seq},
|
||||
'2026-04-01T00:01:00.000Z'
|
||||
)
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
const activities = threadDetail.value.activities;
|
||||
assert.equal(activities.length, 500);
|
||||
assert.equal(activities[0]?.summary, "act-101");
|
||||
assert.equal(activities[0]?.sequence, 101);
|
||||
assert.equal(activities.at(-1)?.summary, "act-600");
|
||||
// 600 > window, so the client is told older history can be lazy-loaded.
|
||||
assert.equal(threadDetail.value.hasMoreActivities, true);
|
||||
}
|
||||
|
||||
// Lazy-load the page immediately older than the windowed view (cursor =
|
||||
// oldest loaded sequence, 101): sequences 1..100, ascending, no more left.
|
||||
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
beforeSequence: 101,
|
||||
limit: 500,
|
||||
});
|
||||
assert.equal(olderPage.activities.length, 100);
|
||||
assert.equal(olderPage.activities[0]?.summary, "act-1");
|
||||
assert.equal(olderPage.activities.at(-1)?.summary, "act-100");
|
||||
assert.equal(olderPage.hasMore, false);
|
||||
|
||||
// A bounded page returns the newest `limit` of the older set and reports
|
||||
// that more remain (sequences 401..600, with 1..400 still older).
|
||||
const boundedPage = yield* snapshotQuery.getThreadActivitiesPage({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
beforeSequence: 601,
|
||||
limit: 200,
|
||||
});
|
||||
assert.equal(boundedPage.activities.length, 200);
|
||||
assert.equal(boundedPage.activities[0]?.summary, "act-401");
|
||||
assert.equal(boundedPage.activities.at(-1)?.summary, "act-600");
|
||||
assert.equal(boundedPage.hasMore, true);
|
||||
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
|
||||
// Legacy rows may not have a sequence. They are still windowed in the
|
||||
// detail load and must remain pageable by the deterministic created/id
|
||||
// ordering used by the snapshot query.
|
||||
yield* Effect.forEach(
|
||||
Array.from({ length: total }, (_unused, index) => index + 1),
|
||||
(seq) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
)
|
||||
VALUES (
|
||||
${`unsequenced-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
|
||||
'info', 'runtime.note', ${`legacy-act-${seq}`}, '{}', NULL,
|
||||
'2026-04-01T00:01:00.000Z'
|
||||
)
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const legacyThreadDetail = yield* snapshotQuery.getThreadDetailById(
|
||||
ThreadId.make("thread-1"),
|
||||
);
|
||||
assert.equal(legacyThreadDetail._tag, "Some");
|
||||
if (legacyThreadDetail._tag === "Some") {
|
||||
const activities = legacyThreadDetail.value.activities;
|
||||
assert.equal(activities.length, 500);
|
||||
assert.equal(activities[0]?.summary, "legacy-act-101");
|
||||
assert.equal(activities[0]?.sequence, undefined);
|
||||
assert.equal(activities.at(-1)?.summary, "legacy-act-600");
|
||||
|
||||
const legacyOlderPage = yield* snapshotQuery.getThreadActivitiesPage({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
beforeCreatedAt: activities[0]?.createdAt ?? "2026-04-01T00:01:00.000Z",
|
||||
beforeActivityId: activities[0]?.id ?? asEventId("unsequenced-0101"),
|
||||
limit: 500,
|
||||
});
|
||||
assert.equal(legacyOlderPage.activities.length, 100);
|
||||
assert.equal(legacyOlderPage.activities[0]?.summary, "legacy-act-1");
|
||||
assert.equal(legacyOlderPage.activities.at(-1)?.summary, "legacy-act-100");
|
||||
assert.equal(legacyOlderPage.hasMore, false);
|
||||
}
|
||||
|
||||
const legacyBoundedPage = yield* snapshotQuery.getThreadActivitiesPage({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
beforeCreatedAt: "2026-04-01T00:01:00.000Z",
|
||||
beforeActivityId: asEventId("unsequenced-0601"),
|
||||
limit: 200,
|
||||
});
|
||||
assert.equal(legacyBoundedPage.activities.length, 200);
|
||||
assert.equal(legacyBoundedPage.activities[0]?.summary, "legacy-act-401");
|
||||
assert.equal(legacyBoundedPage.activities.at(-1)?.summary, "legacy-act-600");
|
||||
assert.equal(legacyBoundedPage.hasMore, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unsequenced cursor reaches all older rows without stranding sequenced ones", () =>
|
||||
// Regression for the "unsequenced cursor hides sequenced history" concern:
|
||||
// sequenced rows always sort newer than NULL-sequence (legacy) rows, so when
|
||||
// the oldest loaded row is unsequenced every sequenced row is already in the
|
||||
// window — the `sequence IS NULL` cursor can't strand sequenced rows.
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id, title, workspace_root, default_model_selection_json,
|
||||
scripts_json, created_at, updated_at, deleted_at
|
||||
) VALUES (
|
||||
'project-1', 'Project 1', '/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
|
||||
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id, project_id, title, model_selection_json, runtime_mode,
|
||||
interaction_mode, branch, worktree_path, latest_turn_id,
|
||||
latest_user_message_at, pending_approval_count, pending_user_input_count,
|
||||
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
|
||||
) VALUES (
|
||||
'thread-1', 'project-1', 'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
|
||||
NULL, NULL, NULL, NULL, 0, 0, 0,
|
||||
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
|
||||
)
|
||||
`;
|
||||
// 600 legacy unsequenced rows (older) + 3 sequenced rows (newer). The
|
||||
// window keeps the 3 sequenced + the most-recent 497 unsequenced, so the
|
||||
// oldest loaded row is unsequenced and 103 older unsequenced remain.
|
||||
yield* Effect.forEach(
|
||||
Array.from({ length: 600 }, (_u, index) => index + 1),
|
||||
(n) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
) VALUES (
|
||||
${`unseq-${String(n).padStart(4, "0")}`}, 'thread-1', NULL,
|
||||
'info', 'runtime.note', ${`unseq-${n}`}, '{}', NULL,
|
||||
${`2026-04-01T00:00:01.${String(n).padStart(3, "0")}Z`}
|
||||
)
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
[1, 2, 3],
|
||||
(seq) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
) VALUES (
|
||||
${`seq-${seq}`}, 'thread-1', NULL, 'info', 'runtime.note',
|
||||
${`seq-${seq}`}, '{}', ${seq}, ${`2026-04-01T09:00:0${seq}.000Z`}
|
||||
)
|
||||
`,
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(detail._tag, "Some");
|
||||
if (detail._tag !== "Some") return;
|
||||
const windowed = detail.value.activities;
|
||||
assert.equal(windowed.length, 500);
|
||||
// Sequenced rows are the newest (end of the ascending window); the oldest
|
||||
// loaded row is unsequenced — exactly the case the concern is about.
|
||||
assert.equal(windowed.at(-1)?.summary, "seq-3");
|
||||
assert.equal(windowed[0]?.sequence, undefined);
|
||||
|
||||
// The client pages with the unsequenced cursor of the oldest loaded row.
|
||||
const oldest = windowed[0];
|
||||
assert.ok(oldest);
|
||||
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
beforeCreatedAt: oldest.createdAt,
|
||||
beforeActivityId: oldest.id,
|
||||
limit: 500,
|
||||
});
|
||||
// The 103 older unsequenced rows come back, none are sequenced, and no
|
||||
// sequenced row was stranded (all 3 are already in the window).
|
||||
assert.equal(olderPage.activities.length, 103);
|
||||
assert.equal(olderPage.hasMore, false);
|
||||
assert.ok(olderPage.activities.every((a) => a.sequence === undefined));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
@@ -117,6 +118,31 @@ const ProjectIdLookupInput = Schema.Struct({
|
||||
const ThreadIdLookupInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
/**
|
||||
* Maximum number of most-recent activities loaded into a thread-detail snapshot.
|
||||
* Bounds peak memory when opening a long-lived thread; older activities are
|
||||
* fetched on demand (lazy-load, planned) and live ones stream in via events.
|
||||
*/
|
||||
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
|
||||
|
||||
// `beforeSequence`/`limit` are NonNegativeInt (not bare Number) to match the
|
||||
// contract: the WHERE clause `(sequence < beforeSequence OR sequence IS NULL)`
|
||||
// is only equivalent to the old `COALESCE(sequence, -1) < beforeSequence` when
|
||||
// `beforeSequence` is non-negative — a negative cursor would silently match no
|
||||
// sequenced rows and return only unsequenced ones. Validating here (not just at
|
||||
// the RPC boundary) keeps any future non-RPC caller honest.
|
||||
const ThreadActivitiesBeforeSequenceInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
beforeSequence: NonNegativeInt,
|
||||
limit: NonNegativeInt,
|
||||
});
|
||||
const ThreadActivitiesBeforeActivityInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
beforeCreatedAt: IsoDateTime,
|
||||
beforeActivityId: EventId,
|
||||
limit: NonNegativeInt,
|
||||
});
|
||||
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
|
||||
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
@@ -254,6 +280,23 @@ function mapProposedPlanRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapThreadActivityRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
|
||||
): OrchestrationThreadActivity {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
// `sequence` is the pagination cursor; omit it when the (legacy) row is
|
||||
// unsequenced so the optional contract field stays absent.
|
||||
return row.sequence !== null ? Object.assign(activity, { sequence: row.sequence }) : activity;
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -808,6 +851,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
// The thread-detail timeline loads only the most recent window of activities so a
|
||||
// long-lived thread (tens of thousands of activities, hundreds of MB of payload)
|
||||
// can't blow the server heap. New activities still stream in live via the event
|
||||
// subscription; older history will be fetched on demand once lazy-load lands.
|
||||
// Select the most recent N (sequence DESC) then re-sort ascending for display.
|
||||
const listThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -823,8 +871,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
FROM (
|
||||
SELECT *
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
sequence DESC,
|
||||
created_at DESC,
|
||||
activity_id DESC
|
||||
-- One extra beyond the window so the caller can report hasMoreActivities.
|
||||
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
|
||||
)
|
||||
ORDER BY
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
@@ -832,6 +889,81 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
// Older-than-cursor page for lazy-load. Returns rows newest-first (DESC) so a
|
||||
// simple LIMIT yields the page adjacent to the cursor; the caller reverses to
|
||||
// ascending. `sequence IS NULL` (legacy unsequenced) rows sort last under
|
||||
// `sequence DESC` (SQLite orders NULLs last in DESC) — the very oldest — so
|
||||
// paging eventually reaches them. `beforeSequence` is a NonNegativeInt, so
|
||||
// `(sequence < beforeSequence OR sequence IS NULL)` is equivalent to the old
|
||||
// `COALESCE(sequence, -1) < beforeSequence` but lets the
|
||||
// (thread_id, sequence, created_at, activity_id) index satisfy the ORDER BY
|
||||
// directly instead of forcing a filesort over the whole thread.
|
||||
const listThreadActivityRowsBeforeSequence = SqlSchema.findAll({
|
||||
Request: ThreadActivitiesBeforeSequenceInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId, beforeSequence, limit }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
AND (sequence < ${beforeSequence} OR sequence IS NULL)
|
||||
ORDER BY
|
||||
sequence DESC,
|
||||
created_at DESC,
|
||||
activity_id DESC
|
||||
LIMIT ${limit}
|
||||
`,
|
||||
});
|
||||
|
||||
// Legacy unsequenced (sequence NULL) rows are paged by a (created_at,
|
||||
// activity_id) cursor. created_at is compared lexicographically as TEXT, which
|
||||
// equals chronological order only because timestamps are canonical ISO-8601
|
||||
// (always UTC `Z`, fixed millisecond precision) — the same invariant every
|
||||
// `ORDER BY created_at` in this layer (including the detail window above)
|
||||
// already relies on, so the cursor stays consistent with how rows are
|
||||
// displayed. activity_id breaks created_at ties; its ordering is arbitrary but
|
||||
// matches the window's `activity_id` tiebreak, so pages never skip or repeat.
|
||||
const listUnsequencedThreadActivityRowsBeforeActivity = SqlSchema.findAll({
|
||||
Request: ThreadActivitiesBeforeActivityInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId, beforeCreatedAt, beforeActivityId, limit }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
AND sequence IS NULL
|
||||
AND (
|
||||
created_at < ${beforeCreatedAt}
|
||||
OR (
|
||||
created_at = ${beforeCreatedAt}
|
||||
AND activity_id < ${beforeActivityId}
|
||||
)
|
||||
)
|
||||
ORDER BY
|
||||
created_at DESC,
|
||||
activity_id DESC
|
||||
LIMIT ${limit}
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadSessionRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
@@ -1076,16 +1208,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
threadActivities.push({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
threadActivities.push(mapThreadActivityRow(row));
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
@@ -1190,6 +1313,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
// The full snapshot is unwindowed, so there is never more to load.
|
||||
hasMoreActivities: false,
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
@@ -1998,21 +2123,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
// The query fetches WINDOW+1 ascending rows; if it returned the extra
|
||||
// one, older activities exist beyond the window — drop that oldest row
|
||||
// and flag it so clients can lazy-load older history.
|
||||
activities: (activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW
|
||||
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
|
||||
: activityRows
|
||||
).map(mapThreadActivityRow),
|
||||
hasMoreActivities: activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW,
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
@@ -2063,6 +2181,43 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getThreadActivitiesPage: ProjectionSnapshotQueryShape["getThreadActivitiesPage"] = (
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const limit = Math.min(
|
||||
Math.max(1, input.limit ?? THREAD_DETAIL_ACTIVITY_WINDOW),
|
||||
THREAD_DETAIL_ACTIVITY_WINDOW,
|
||||
);
|
||||
// Fetch one extra to detect whether older activities remain.
|
||||
const rowsEffect =
|
||||
"beforeSequence" in input
|
||||
? listThreadActivityRowsBeforeSequence({
|
||||
threadId: input.threadId,
|
||||
beforeSequence: input.beforeSequence,
|
||||
limit: limit + 1,
|
||||
})
|
||||
: listUnsequencedThreadActivityRowsBeforeActivity({
|
||||
threadId: input.threadId,
|
||||
beforeCreatedAt: input.beforeCreatedAt,
|
||||
beforeActivityId: input.beforeActivityId,
|
||||
limit: limit + 1,
|
||||
});
|
||||
const rows = yield* rowsEffect.pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadActivitiesPage:query",
|
||||
"ProjectionSnapshotQuery.getThreadActivitiesPage:decodeRows",
|
||||
),
|
||||
),
|
||||
);
|
||||
const hasMore = rows.length > limit;
|
||||
// Rows are newest-first; keep the page closest to the cursor, then reverse
|
||||
// to ascending for display.
|
||||
const page = (hasMore ? rows.slice(0, limit) : rows).map(mapThreadActivityRow).toReversed();
|
||||
return { activities: page, hasMore };
|
||||
});
|
||||
|
||||
return {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
@@ -2078,6 +2233,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
getThreadDetailSnapshot,
|
||||
getThreadActivitiesPage,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -466,58 +466,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
effectIt.effect(
|
||||
"sends only image attachments to the provider and appends file attachment prompt text",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* Effect.promise(() => createHarness());
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const imageAttachment = {
|
||||
type: "image" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000001",
|
||||
name: "screen.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
const fileAttachment = {
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-000000000002",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 5,
|
||||
};
|
||||
const attachmentsDir = NodePath.join(harness.stateDir, "attachments");
|
||||
const fileAttachmentPath = NodePath.join(attachmentsDir, `${fileAttachment.id}.txt`);
|
||||
NodeFS.mkdirSync(attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(fileAttachmentPath, "notes");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-file-attachments"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-file-attachments"),
|
||||
role: "user",
|
||||
text: "hello with attachments",
|
||||
attachments: [imageAttachment, fileAttachment],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
const request = harness.sendTurn.mock.calls[0]?.[0] as {
|
||||
readonly input?: string;
|
||||
readonly attachments?: ReadonlyArray<unknown>;
|
||||
};
|
||||
expect(request.attachments).toEqual([imageAttachment]);
|
||||
expect(request.input).toBe(
|
||||
`hello with attachments\n\n[Attached file: ${fileAttachmentPath} (notes.txt, text/plain, 5 B). Read it from disk when needed.]`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -25,9 +25,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { appendFileAttachmentPromptText } from "../../attachmentPrompt.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
@@ -198,7 +196,6 @@ const make = Effect.gen(function* () {
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverCommandId = (tag: string) =>
|
||||
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
|
||||
@@ -608,18 +605,8 @@ const make = Effect.gen(function* () {
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(
|
||||
appendFileAttachmentPromptText({
|
||||
text: input.messageText,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachments: input.attachments ?? [],
|
||||
}),
|
||||
);
|
||||
// Only image attachments go to the provider as content blocks; file
|
||||
// attachments are delivered by path in the prompt text above.
|
||||
const normalizedAttachments = (input.attachments ?? []).filter(
|
||||
(attachment) => attachment.type === "image",
|
||||
);
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService
|
||||
.listSessions()
|
||||
.pipe(
|
||||
|
||||
@@ -1,53 +1,17 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
type ClientOrchestrationCommand,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type ClientOrchestrationCommand,
|
||||
type UploadChatAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
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 Path from "effect/Path";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { canonicalizeClientCommandTimestamps, normalizeDispatchCommand } from "./Normalizer.ts";
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-test-" }),
|
||||
WorkspacePaths.layer,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
|
||||
|
||||
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
|
||||
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const turnStartCommand = (
|
||||
attachments: ReadonlyArray<UploadChatAttachment>,
|
||||
): ClientOrchestrationCommand => ({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("user-message-1"),
|
||||
role: "user",
|
||||
text: "hello normalizer",
|
||||
attachments,
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
const asDataUrl = (mimeType: string, bytes: Buffer) =>
|
||||
`data:${mimeType};base64,${bytes.toString("base64")}`;
|
||||
|
||||
describe("canonicalizeClientCommandTimestamps", () => {
|
||||
it("replaces a client command timestamp with the server receipt timestamp", () => {
|
||||
@@ -107,86 +71,3 @@ describe("canonicalizeClientCommandTimestamps", () => {
|
||||
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Normalizer", () => {
|
||||
it.effect("persists file attachments and writes their bytes to the attachments dir", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
|
||||
const bytes = Buffer.from("hello world");
|
||||
|
||||
const normalized = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "file",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: bytes.byteLength,
|
||||
dataUrl: asDataUrl("text/plain", bytes),
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(normalized.type).toBe("thread.turn.start");
|
||||
if (normalized.type !== "thread.turn.start") {
|
||||
return;
|
||||
}
|
||||
const attachment = normalized.message.attachments[0];
|
||||
expect(attachment).toMatchObject({
|
||||
type: "file",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: bytes.byteLength,
|
||||
});
|
||||
expect(attachment?.id).toMatch(
|
||||
/^thread-1-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
|
||||
);
|
||||
if (!attachment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachment.id}.txt`);
|
||||
expect(yield* fileSystem.readFileString(attachmentPath)).toBe("hello world");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects image attachments with a non-image data URL mime type", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "image",
|
||||
name: "fake.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: asDataUrl("text/plain", Buffer.from("hello")),
|
||||
},
|
||||
]),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toBe("Invalid image attachment payload for 'fake.png'.");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects file attachments over the maximum attachment size", () =>
|
||||
Effect.gen(function* () {
|
||||
const bytes = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, "a");
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand([
|
||||
{
|
||||
type: "file",
|
||||
name: "big.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
dataUrl: asDataUrl("text/plain", bytes),
|
||||
},
|
||||
]),
|
||||
).pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toBe("Attachment 'big.txt' is empty or too large.");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -109,16 +109,16 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || (attachment.type === "image" && !parsed.mimeType.startsWith("image/"))) {
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid ${attachment.type} attachment payload for '${attachment.name}'.`,
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Attachment '${attachment.name}' is empty or too large.`,
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: attachment.type,
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
|
||||
@@ -27,9 +27,8 @@ export interface OrchestrationEngineShape {
|
||||
*
|
||||
* @param fromSequenceExclusive - Sequence cursor (exclusive).
|
||||
* @param limit - Maximum number of events to read. Defaults to the event
|
||||
* store's page-bounded default; pass a higher value when the caller must
|
||||
* read every event after the cursor (e.g. per-thread catch-up that filters
|
||||
* a small subset out of a potentially larger global range).
|
||||
* store's page-bounded default. Callers must keep this bounded; use a
|
||||
* projection snapshot instead of replaying an arbitrarily stale cursor.
|
||||
* @returns Stream containing ordered events.
|
||||
*/
|
||||
readonly readEvents: (
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
import type {
|
||||
CheckpointRef,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationGetThreadActivitiesInput,
|
||||
OrchestrationGetThreadActivitiesResult,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationReadModel,
|
||||
@@ -168,6 +170,16 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadDetailSnapshot: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Cursor-paginated load of a thread's older activities (lazy-load / infinite
|
||||
* scroll). Returns the page of activities immediately older than the provided
|
||||
* sequence or unsequenced activity cursor, ascending, plus whether older ones
|
||||
* remain.
|
||||
*/
|
||||
readonly getThreadActivitiesPage: (
|
||||
input: OrchestrationGetThreadActivitiesInput,
|
||||
) => Effect.Effect<OrchestrationGetThreadActivitiesResult, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -31,8 +31,12 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
Effect.fn("environment.orchestration.snapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
// The only consumer (the `t3` CLI project resolver) reads just
|
||||
// `.projects`, so use the command read model — it returns the same
|
||||
// OrchestrationReadModel shape but never materialises the per-thread
|
||||
// activity/message/checkpoint tables (490MB+ on a busy DB → heap OOM).
|
||||
return yield* projectionSnapshotQuery
|
||||
.getSnapshot()
|
||||
.getCommandReadModel()
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
failEnvironmentInternal("orchestration_snapshot_failed", cause),
|
||||
|
||||
@@ -27,6 +27,7 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
|
||||
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
|
||||
@@ -210,6 +210,7 @@ describe("ProviderSessionReaper", () => {
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -5877,6 +5877,52 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeThread replaces a stale cursor with a fresh snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotSequence = 5_000;
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
let replayCalls = 0;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence }),
|
||||
getThreadDetailSnapshot: () =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
snapshotSequence,
|
||||
thread,
|
||||
}),
|
||||
),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
readEvents: () => {
|
||||
replayCalls += 1;
|
||||
return Stream.empty;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
afterSequence: 1,
|
||||
}).pipe(Stream.take(1), Stream.runCollect),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(replayCalls, 0);
|
||||
assert.equal(result[0]?.kind, "snapshot");
|
||||
if (result[0]?.kind === "snapshot") {
|
||||
assert.equal(result[0].snapshot.snapshotSequence, snapshotSequence);
|
||||
assert.equal(result[0].snapshot.thread.id, defaultThreadId);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeShell coalesces a per-thread burst without stalling other threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const busyThreadId = ThreadId.make("thread-busy");
|
||||
|
||||
@@ -97,6 +97,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(AnalyticsService.AnalyticsService, {
|
||||
record: () => Effect.void,
|
||||
@@ -160,6 +161,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
@@ -204,6 +206,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
@@ -254,6 +257,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
getThreadActivitiesPage: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
|
||||
+78
-5
@@ -34,6 +34,7 @@ import {
|
||||
type OrchestrationThreadStreamItem,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetThreadActivitiesError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ProjectId,
|
||||
@@ -115,6 +116,24 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
|
||||
import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
|
||||
const ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT = 1_000;
|
||||
|
||||
const subscriptionReplayLimit = (
|
||||
afterSequence: number,
|
||||
snapshotSequence: number,
|
||||
): number | null => {
|
||||
const eventCount = snapshotSequence - afterSequence;
|
||||
if (
|
||||
!Number.isSafeInteger(eventCount) ||
|
||||
eventCount < 0 ||
|
||||
eventCount > ORCHESTRATION_SUBSCRIPTION_REPLAY_LIMIT
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return eventCount;
|
||||
};
|
||||
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
@@ -287,6 +306,7 @@ const SHELL_RESUME_MAX_GAP = 1_000;
|
||||
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.getThreadActivities, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
|
||||
@@ -1183,6 +1203,20 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.getThreadActivities]: (input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.getThreadActivities,
|
||||
projectionSnapshotQuery.getThreadActivitiesPage(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetThreadActivitiesError({
|
||||
message: "Failed to load thread activities page",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
@@ -1382,14 +1416,53 @@ const makeWsRpcLayer = (
|
||||
// catch-up followed by the buffered/ongoing live events. Overlapping
|
||||
// events are deduped by sequence on the client.
|
||||
//
|
||||
// Read the full range after the cursor (not the store's default
|
||||
// page-bounded limit): the range is normally tiny (a fresh HTTP
|
||||
// snapshot sequence) and the per-thread filter runs after reading,
|
||||
// so a global cap could otherwise omit this thread's events.
|
||||
// A recent cursor replays the exact global range through the
|
||||
// per-thread filter. A stale cursor receives a current thread
|
||||
// snapshot instead, keeping catch-up bounded even when the global
|
||||
// event log is very large.
|
||||
if (input.afterSequence !== undefined) {
|
||||
const afterSequence = input.afterSequence;
|
||||
const { snapshotSequence } = yield* projectionSnapshotQuery
|
||||
.getSnapshotSequence()
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: "Failed to load orchestration snapshot sequence",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const replayLimit = subscriptionReplayLimit(afterSequence, snapshotSequence);
|
||||
|
||||
if (replayLimit === null) {
|
||||
const snapshot = yield* projectionSnapshotQuery
|
||||
.getThreadDetailSnapshot(input.threadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
message: `Failed to load thread ${input.threadId}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(snapshot)) {
|
||||
return yield* new OrchestrationGetSnapshotError({
|
||||
message: `Thread ${input.threadId} was not found`,
|
||||
cause: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({ kind: "snapshot" as const, snapshot: snapshot.value }),
|
||||
bufferedLiveStream,
|
||||
);
|
||||
}
|
||||
|
||||
const catchUpStream = orchestrationEngine
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.readEvents(afterSequence, replayLimit)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({ kind: "event" as const, event })),
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ChatMessage, Thread } from "../types";
|
||||
import type { Thread } from "../types";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
@@ -20,10 +20,6 @@ import {
|
||||
hasServerAcknowledgedLocalDispatch,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
reconcileRetainedMountedThreadIds,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
normalizeDataUrlMimeType,
|
||||
resolveComposerAttachmentMimeType,
|
||||
revokeUserMessagePreviewUrls,
|
||||
resolveSendEnvMode,
|
||||
shouldWriteThreadErrorToCurrentServerThread,
|
||||
} from "./ChatView.logic";
|
||||
@@ -81,81 +77,6 @@ const readySession = {
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
|
||||
function makeAttachmentMessage(): ChatMessage {
|
||||
return {
|
||||
id: MessageId.make("message-with-attachments"),
|
||||
role: "user",
|
||||
text: "Inspect these files",
|
||||
turnId: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
streaming: false,
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "image-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 10,
|
||||
previewUrl: "blob:image-preview",
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "debug.log",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 20,
|
||||
previewUrl: "blob:file-preview",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("attachment preview lifecycle", () => {
|
||||
it("collects and revokes blob previews for images and files", () => {
|
||||
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
|
||||
const message = makeAttachmentMessage();
|
||||
|
||||
expect(collectUserMessageBlobPreviewUrls(message)).toEqual([
|
||||
"blob:image-preview",
|
||||
"blob:file-preview",
|
||||
]);
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
|
||||
expect(revokeObjectURL).toHaveBeenCalledTimes(2);
|
||||
expect(revokeObjectURL).toHaveBeenNthCalledWith(1, "blob:image-preview");
|
||||
expect(revokeObjectURL).toHaveBeenNthCalledWith(2, "blob:file-preview");
|
||||
revokeObjectURL.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer attachment MIME types", () => {
|
||||
it("recovers image MIME types from names when the browser reports a generic type", () => {
|
||||
expect(resolveComposerAttachmentMimeType({ name: "capture.PNG", type: "" })).toBe("image/png");
|
||||
expect(
|
||||
resolveComposerAttachmentMimeType({
|
||||
name: "capture.webp",
|
||||
type: "application/octet-stream",
|
||||
}),
|
||||
).toBe("image/webp");
|
||||
});
|
||||
|
||||
it("preserves a specific browser MIME type and keeps unknown files generic", () => {
|
||||
expect(resolveComposerAttachmentMimeType({ name: "capture.png", type: "text/plain" })).toBe(
|
||||
"text/plain",
|
||||
);
|
||||
expect(resolveComposerAttachmentMimeType({ name: "payload.bin", type: "" })).toBe(
|
||||
"application/octet-stream",
|
||||
);
|
||||
});
|
||||
|
||||
it("rewrites a FileReader data URL with the resolved attachment MIME type", () => {
|
||||
expect(
|
||||
normalizeDataUrlMimeType("data:application/octet-stream;base64,iVBORw0KGgo=", "image/png"),
|
||||
).toBe("data:image/png;base64,iVBORw0KGgo=");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildThreadTurnInterruptInput", () => {
|
||||
it("targets the session's active running turn", () => {
|
||||
const activeTurnId = TurnId.make("turn-running");
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
|
||||
import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { environmentThreadDetails } from "../state/threads";
|
||||
@@ -144,6 +144,9 @@ export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
|
||||
return;
|
||||
}
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
revokeBlobPreviewUrl(attachment.previewUrl);
|
||||
}
|
||||
}
|
||||
@@ -154,78 +157,30 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
|
||||
}
|
||||
const previewUrls: string[] = [];
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") continue;
|
||||
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
|
||||
previewUrls.push(attachment.previewUrl);
|
||||
}
|
||||
return previewUrls;
|
||||
}
|
||||
|
||||
const FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
|
||||
".avif": "image/avif",
|
||||
".bmp": "image/bmp",
|
||||
".gif": "image/gif",
|
||||
".heic": "image/heic",
|
||||
".heif": "image/heif",
|
||||
".jpeg": "image/jpeg",
|
||||
".jpg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".svg": "image/svg+xml",
|
||||
".tif": "image/tiff",
|
||||
".tiff": "image/tiff",
|
||||
".webp": "image/webp",
|
||||
};
|
||||
|
||||
const GENERIC_BINARY_MIME_TYPES = new Set([
|
||||
"",
|
||||
"application/octet-stream",
|
||||
"application/unknown",
|
||||
"application/x-unknown",
|
||||
"binary/octet-stream",
|
||||
]);
|
||||
|
||||
export function resolveComposerAttachmentMimeType(file: {
|
||||
readonly name: string;
|
||||
readonly type: string;
|
||||
}): string {
|
||||
const declaredMimeType = file.type.trim().toLowerCase();
|
||||
if (!GENERIC_BINARY_MIME_TYPES.has(declaredMimeType)) {
|
||||
return declaredMimeType;
|
||||
}
|
||||
const normalizedName = file.name.trim().toLowerCase();
|
||||
const extensionIndex = normalizedName.lastIndexOf(".");
|
||||
const extension = extensionIndex >= 0 ? normalizedName.slice(extensionIndex) : "";
|
||||
return (
|
||||
FALLBACK_IMAGE_MIME_TYPE_BY_EXTENSION[extension] ||
|
||||
declaredMimeType ||
|
||||
"application/octet-stream"
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeDataUrlMimeType(dataUrl: string, mimeType: string): string {
|
||||
const separatorIndex = dataUrl.indexOf(",");
|
||||
if (!dataUrl.startsWith("data:") || separatorIndex < 0) {
|
||||
return dataUrl;
|
||||
}
|
||||
return `data:${mimeType};base64,${dataUrl.slice(separatorIndex + 1)}`;
|
||||
}
|
||||
|
||||
export interface PullRequestDialogState {
|
||||
initialReference: string | null;
|
||||
key: number;
|
||||
}
|
||||
|
||||
export function readFileAsDataUrl(file: File, mimeType?: string): Promise<string> {
|
||||
export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(mimeType ? normalizeDataUrlMimeType(reader.result, mimeType) : reader.result);
|
||||
resolve(reader.result);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Could not read attachment data."));
|
||||
reject(new Error("Could not read image data."));
|
||||
});
|
||||
reader.addEventListener("error", () => {
|
||||
reject(reader.error ?? new Error("Failed to read attachment."));
|
||||
reject(reader.error ?? new Error("Failed to read image."));
|
||||
});
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
@@ -238,7 +193,9 @@ export function resolveSendEnvMode(input: {
|
||||
return input.isGitRepo ? input.requestedEnvMode : "local";
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment {
|
||||
export function cloneComposerImageForRetry(
|
||||
image: ComposerImageAttachment,
|
||||
): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
}
|
||||
|
||||
@@ -63,6 +63,10 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
type AtomCommandResult,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
useOlderThreadActivities,
|
||||
type OlderActivitiesCursor,
|
||||
} from "@t3tools/client-runtime/state/older-thread-activities";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { isElectron } from "../env";
|
||||
@@ -162,7 +166,7 @@ import {
|
||||
} from "../logicalProject";
|
||||
import { buildDraftThreadRouteParams } from "../threadRoutes";
|
||||
import {
|
||||
type ComposerAttachment,
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
useComposerDraftStore,
|
||||
type DraftId,
|
||||
@@ -190,6 +194,7 @@ import {
|
||||
primaryServerKeybindingsAtom,
|
||||
serverEnvironment,
|
||||
} from "../state/server";
|
||||
import { orchestrationEnvironment } from "../state/orchestration";
|
||||
import { terminalEnvironment } from "../state/terminal";
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
@@ -261,8 +266,8 @@ import {
|
||||
} from "../versionSkew";
|
||||
import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]";
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
@@ -1190,7 +1195,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: null,
|
||||
);
|
||||
const promptRef = useRef("");
|
||||
const composerImagesRef = useRef<ComposerAttachment[]>([]);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
|
||||
const localComposerRef = useRef<ChatComposerHandle | null>(null);
|
||||
@@ -1860,7 +1865,45 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
|
||||
// ── Older-history lazy-load ────────────────────────────────────────────────
|
||||
// The detail snapshot windows activities to the most recent page (the server
|
||||
// sets `hasMoreActivities` when older ones exist); older pages are fetched on
|
||||
// demand (infinite scroll-up) and prepended by the shared engine. Messages
|
||||
// aren't windowed server-side, so this just back-fills the older tool
|
||||
// activity.
|
||||
const loadThreadActivities = useAtomCommand(orchestrationEnvironment.loadThreadActivities, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const activeThreadEnvironmentIdForActivities = activeThread?.environmentId ?? null;
|
||||
const activeThreadIdForActivities = activeThread?.id ?? null;
|
||||
const loadOlderActivitiesPage = useCallback(
|
||||
async (cursor: OlderActivitiesCursor) => {
|
||||
if (activeThreadEnvironmentIdForActivities === null || activeThreadIdForActivities === null) {
|
||||
return null;
|
||||
}
|
||||
const result = await loadThreadActivities({
|
||||
environmentId: activeThreadEnvironmentIdForActivities,
|
||||
input: { threadId: activeThreadIdForActivities, ...cursor },
|
||||
});
|
||||
// Failures stay silent on web (the "Load older history" affordance itself
|
||||
// is the retry surface); returning null keeps `hasMore` for the retry.
|
||||
return result._tag === "Success" ? result.value : null;
|
||||
},
|
||||
[activeThreadEnvironmentIdForActivities, activeThreadIdForActivities, loadThreadActivities],
|
||||
);
|
||||
const {
|
||||
mergedActivities: threadActivities,
|
||||
hasMoreOlder: hasMoreOlderActivities,
|
||||
loadingOlder: loadingOlderActivities,
|
||||
loadOlder: loadOlderActivities,
|
||||
} = useOlderThreadActivities({
|
||||
threadKey: activeThread ? `${activeThread.environmentId}\u0000${activeThread.id}` : null,
|
||||
liveActivities: activeThread?.activities ?? EMPTY_ACTIVITIES,
|
||||
hasMoreLiveActivities: activeThread?.hasMoreActivities ?? false,
|
||||
loadPage: loadOlderActivitiesPage,
|
||||
});
|
||||
|
||||
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
|
||||
const pendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(threadActivities),
|
||||
@@ -4179,19 +4222,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
model: ctxSelectedModel,
|
||||
models: ctxSelectedProviderModels,
|
||||
effort: ctxSelectedPromptEffort,
|
||||
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
type: image.type,
|
||||
type: "image" as const,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file, image.mimeType),
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
})),
|
||||
);
|
||||
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
||||
type: image.type,
|
||||
type: "image" as const,
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
@@ -4253,7 +4296,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
let titleSeed = trimmed;
|
||||
if (!titleSeed) {
|
||||
if (firstComposerImageName) {
|
||||
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
|
||||
titleSeed = `Image: ${firstComposerImageName}`;
|
||||
} else if (composerTerminalContextsSnapshot.length > 0) {
|
||||
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
|
||||
} else if (composerElementContextsSnapshot.length > 0) {
|
||||
@@ -5256,6 +5299,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
hasMoreOlder={hasMoreOlderActivities}
|
||||
loadingOlder={loadingOlderActivities}
|
||||
onLoadOlder={loadOlderActivities}
|
||||
latestTurn={activeLatestTurn}
|
||||
runningTurnId={
|
||||
activeThread.session?.status === "running"
|
||||
@@ -5404,7 +5450,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
// Merged set (older pages + live window), not the windowed
|
||||
// live slice: the context meter scans for the latest
|
||||
// context-window.updated event, which can sit in a
|
||||
// lazy-loaded page on long threads.
|
||||
activeThreadActivities={threadActivities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
|
||||
@@ -43,17 +43,13 @@ import {
|
||||
replaceTextRange,
|
||||
shouldSubmitComposerOnEnter,
|
||||
} from "../../composer-logic";
|
||||
import {
|
||||
deriveComposerSendState,
|
||||
readFileAsDataUrl,
|
||||
resolveComposerAttachmentMimeType,
|
||||
} from "../ChatView.logic";
|
||||
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
|
||||
import {
|
||||
dataTransferHasComposerMention,
|
||||
makeComposerMentionDragHandlers,
|
||||
} from "./composerMentionDrag";
|
||||
import {
|
||||
type ComposerAttachment,
|
||||
type ComposerImageAttachment,
|
||||
type DraftId,
|
||||
type PersistedComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
@@ -105,7 +101,6 @@ import {
|
||||
BotIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
FileTextIcon,
|
||||
ListTodoIcon,
|
||||
PencilRulerIcon,
|
||||
type LucideIcon,
|
||||
@@ -135,7 +130,6 @@ import {
|
||||
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
|
||||
import { searchProviderSkills } from "../../providerSkillSearch";
|
||||
import { useMediaQuery } from "../../hooks/useMediaQuery";
|
||||
import { formatAttachmentSizeLabel } from "../../lib/attachmentSize";
|
||||
import type { ReviewCommentContext } from "../../reviewCommentContext";
|
||||
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
@@ -431,7 +425,7 @@ export interface ChatComposerHandle {
|
||||
/** Get the current prompt/effort/model state for use in send. */
|
||||
getSendContext: () => {
|
||||
prompt: string;
|
||||
images: ComposerAttachment[];
|
||||
images: ComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
elementContexts: ElementContextDraft[];
|
||||
previewAnnotations: PreviewAnnotationPayload[];
|
||||
@@ -522,7 +516,7 @@ export interface ChatComposerProps {
|
||||
|
||||
// Refs the parent needs kept in sync
|
||||
promptRef: React.RefObject<string>;
|
||||
composerImagesRef: React.RefObject<ComposerAttachment[]>;
|
||||
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
|
||||
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
|
||||
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
|
||||
composerRef: React.RefObject<ChatComposerHandle | null>;
|
||||
@@ -1181,14 +1175,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
|
||||
const addComposerImage = useCallback(
|
||||
(image: ComposerAttachment) => {
|
||||
(image: ComposerImageAttachment) => {
|
||||
addComposerDraftImage(composerDraftTarget, image);
|
||||
},
|
||||
[composerDraftTarget, addComposerDraftImage],
|
||||
);
|
||||
|
||||
const addComposerImagesToDraft = useCallback(
|
||||
(images: ComposerAttachment[]) => {
|
||||
(images: ComposerImageAttachment[]) => {
|
||||
addComposerDraftImages(composerDraftTarget, images);
|
||||
},
|
||||
[composerDraftTarget, addComposerDraftImages],
|
||||
@@ -1396,9 +1390,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
await Promise.all(
|
||||
composerImages.map(async (image) => {
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(image.file, image.mimeType);
|
||||
const dataUrl = await readFileAsDataUrl(image.file);
|
||||
stagedAttachmentById.set(image.id, {
|
||||
type: image.type,
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
@@ -1799,30 +1792,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
if (pendingUserInputs.length > 0) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Attach files after answering plan questions.",
|
||||
title: "Attach images after answering plan questions.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const nextImages: ComposerAttachment[] = [];
|
||||
const nextImages: ComposerImageAttachment[] = [];
|
||||
let nextImageCount = composerImagesRef.current.length;
|
||||
let error: string | null = null;
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
|
||||
continue;
|
||||
}
|
||||
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
|
||||
continue;
|
||||
}
|
||||
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
|
||||
break;
|
||||
}
|
||||
const mimeType = resolveComposerAttachmentMimeType(file);
|
||||
const isImage = mimeType.startsWith("image/");
|
||||
const previewUrl = URL.createObjectURL(file);
|
||||
nextImages.push({
|
||||
type: isImage ? "image" : "file",
|
||||
type: "image",
|
||||
id: randomUUID(),
|
||||
name: file.name || (isImage ? "image" : "file"),
|
||||
mimeType,
|
||||
name: file.name || "image",
|
||||
mimeType: file.type,
|
||||
sizeBytes: file.size,
|
||||
previewUrl,
|
||||
file,
|
||||
@@ -1847,8 +1842,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
|
||||
const files = Array.from(event.clipboardData.files);
|
||||
if (files.length === 0) return;
|
||||
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
|
||||
if (imageFiles.length === 0) return;
|
||||
event.preventDefault();
|
||||
addComposerImages(files);
|
||||
addComposerImages(imageFiles);
|
||||
};
|
||||
|
||||
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
@@ -2355,10 +2352,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
|
||||
}
|
||||
onExpandImage={(imageId) => {
|
||||
const preview = buildExpandedImagePreview(
|
||||
composerImages.filter((attachment) => attachment.type === "image"),
|
||||
imageId,
|
||||
);
|
||||
const preview = buildExpandedImagePreview(composerImages, imageId);
|
||||
if (preview) onExpandImage(preview);
|
||||
}}
|
||||
className="mb-3"
|
||||
@@ -2409,34 +2403,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className={
|
||||
image.type === "file"
|
||||
? "relative flex h-16 w-40 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background px-2"
|
||||
: "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{image.type === "file" ? (
|
||||
<>
|
||||
<FileTextIcon className="size-5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 pr-5">
|
||||
<div className="truncate text-xs" title={image.name}>
|
||||
{image.name}
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground/70">
|
||||
{formatAttachmentSizeLabel(image.sizeBytes)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : image.previewUrl ? (
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(
|
||||
composerImages.filter((attachment) => attachment.type === "image"),
|
||||
image.id,
|
||||
);
|
||||
const preview = buildExpandedImagePreview(composerImages, image.id);
|
||||
if (!preview) return;
|
||||
onExpandImage(preview);
|
||||
}}
|
||||
|
||||
@@ -2,13 +2,13 @@ import type { PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import type { ComposerAttachment } from "~/composerDraftStore";
|
||||
import type { ComposerImageAttachment } from "~/composerDraftStore";
|
||||
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ComposerPreviewAnnotationCardsProps {
|
||||
annotations: ReadonlyArray<PreviewAnnotationPayload>;
|
||||
images: ReadonlyArray<ComposerAttachment>;
|
||||
images: ReadonlyArray<ComposerImageAttachment>;
|
||||
onRemove: (annotationId: string) => void;
|
||||
onExpandImage: (imageId: string) => void;
|
||||
className?: string;
|
||||
|
||||
@@ -5,8 +5,68 @@ import {
|
||||
deriveMessagesTimelineRows,
|
||||
normalizeCompactToolLabel,
|
||||
resolveAssistantMessageCopyState,
|
||||
resolveOlderHistoryAutoLoad,
|
||||
} from "./MessagesTimeline.logic";
|
||||
|
||||
describe("resolveOlderHistoryAutoLoad", () => {
|
||||
it("dispatches only once while a failed or successful load leaves the viewport at the top", () => {
|
||||
const first = resolveOlderHistoryAutoLoad({
|
||||
isAtStart: true,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: false,
|
||||
requestedAtStart: false,
|
||||
});
|
||||
expect(first).toEqual({ requestedAtStart: true, shouldLoad: true });
|
||||
|
||||
expect(
|
||||
resolveOlderHistoryAutoLoad({
|
||||
isAtStart: true,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: false,
|
||||
requestedAtStart: first.requestedAtStart,
|
||||
}),
|
||||
).toEqual({ requestedAtStart: true, shouldLoad: false });
|
||||
expect(
|
||||
resolveOlderHistoryAutoLoad({
|
||||
isAtStart: true,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: true,
|
||||
requestedAtStart: first.requestedAtStart,
|
||||
}),
|
||||
).toEqual({ requestedAtStart: true, shouldLoad: false });
|
||||
});
|
||||
|
||||
it("rearms automatic loading only after leaving the top", () => {
|
||||
const away = resolveOlderHistoryAutoLoad({
|
||||
isAtStart: false,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: false,
|
||||
requestedAtStart: true,
|
||||
});
|
||||
expect(away).toEqual({ requestedAtStart: false, shouldLoad: false });
|
||||
|
||||
expect(
|
||||
resolveOlderHistoryAutoLoad({
|
||||
isAtStart: true,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: false,
|
||||
requestedAtStart: away.requestedAtStart,
|
||||
}),
|
||||
).toEqual({ requestedAtStart: true, shouldLoad: true });
|
||||
});
|
||||
|
||||
it("does not reset the latch before list state is available", () => {
|
||||
expect(
|
||||
resolveOlderHistoryAutoLoad({
|
||||
isAtStart: undefined,
|
||||
hasMoreOlder: true,
|
||||
loadingOlder: false,
|
||||
requestedAtStart: true,
|
||||
}),
|
||||
).toEqual({ requestedAtStart: true, shouldLoad: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeMessageDurationStart", () => {
|
||||
it("returns message createdAt when there is no preceding user message", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
|
||||
@@ -21,6 +21,42 @@ export interface TimelineEndState {
|
||||
readonly isNearEnd?: boolean;
|
||||
}
|
||||
|
||||
export interface OlderHistoryAutoLoadInput {
|
||||
readonly isAtStart: boolean | undefined;
|
||||
readonly hasMoreOlder: boolean;
|
||||
readonly loadingOlder: boolean;
|
||||
readonly requestedAtStart: boolean;
|
||||
}
|
||||
|
||||
export interface OlderHistoryAutoLoadResult {
|
||||
readonly requestedAtStart: boolean;
|
||||
readonly shouldLoad: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permit at most one automatic older-history request per visit to the top.
|
||||
* Loading completion and prepended rows both retrigger timeline measurements;
|
||||
* neither should recursively request another page while the viewport remains
|
||||
* pinned at the start. Leaving the top rearms automatic loading, while the
|
||||
* explicit header control remains available for an immediate retry.
|
||||
*/
|
||||
export function resolveOlderHistoryAutoLoad(
|
||||
input: OlderHistoryAutoLoadInput,
|
||||
): OlderHistoryAutoLoadResult {
|
||||
if (input.isAtStart === false) {
|
||||
return { requestedAtStart: false, shouldLoad: false };
|
||||
}
|
||||
if (
|
||||
input.isAtStart !== true ||
|
||||
input.requestedAtStart ||
|
||||
!input.hasMoreOlder ||
|
||||
input.loadingOlder
|
||||
) {
|
||||
return { requestedAtStart: input.requestedAtStart, shouldLoad: false };
|
||||
}
|
||||
return { requestedAtStart: true, shouldLoad: true };
|
||||
}
|
||||
|
||||
export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
|
||||
return state?.isNearEnd ?? state?.isAtEnd;
|
||||
}
|
||||
|
||||
@@ -381,88 +381,6 @@ describe("MessagesTimeline", () => {
|
||||
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
|
||||
});
|
||||
|
||||
it("renders file attachments as chips with name and size instead of images", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const entry = {
|
||||
...buildUserTimelineEntry("Please review the attached report."),
|
||||
message: {
|
||||
...buildUserTimelineEntry("Please review the attached report.").message,
|
||||
attachments: [
|
||||
{
|
||||
type: "file" as const,
|
||||
id: "attachment-file-1",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 2_048,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain("report.pdf");
|
||||
expect(markup).toContain("2.0 KB");
|
||||
expect(markup).toContain("lucide-file-text");
|
||||
expect(markup).not.toContain("<img");
|
||||
});
|
||||
|
||||
it("renders downloadable file attachment chips when a preview URL is available", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const entry = {
|
||||
...buildUserTimelineEntry("Here is the file."),
|
||||
message: {
|
||||
...buildUserTimelineEntry("Here is the file.").message,
|
||||
attachments: [
|
||||
{
|
||||
type: "file" as const,
|
||||
id: "attachment-file-2",
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 512,
|
||||
previewUrl: "data:text/plain;base64,aGVsbG8=",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain('download="notes.txt"');
|
||||
expect(markup).toContain('href="data:text/plain;base64,aGVsbG8="');
|
||||
expect(markup).toContain("512 B");
|
||||
});
|
||||
|
||||
it("renders image attachments in the image grid without file chips", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const entry = {
|
||||
...buildUserTimelineEntry("Take a look."),
|
||||
message: {
|
||||
...buildUserTimelineEntry("Take a look.").message,
|
||||
attachments: [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: "attachment-image-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain('src="data:image/png;base64,iVBORw0KGgo="');
|
||||
expect(markup).toContain('alt="screenshot.png"');
|
||||
expect(markup).not.toContain("lucide-file-text");
|
||||
expect(markup).not.toContain("download=");
|
||||
});
|
||||
|
||||
it("renders collapse controls for long user messages", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
@@ -722,4 +640,37 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("lucide-x");
|
||||
expect(markup).toContain('aria-label="Tool call failed"');
|
||||
});
|
||||
|
||||
it("offers a 'Load older history' control when older activity remains", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[buildUserTimelineEntry("Hi")]}
|
||||
hasMoreOlder
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain("Load older history");
|
||||
});
|
||||
|
||||
it("shows a loading indicator while older history is being fetched", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[buildUserTimelineEntry("Hi")]}
|
||||
hasMoreOlder
|
||||
loadingOlder
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain("Loading older history");
|
||||
});
|
||||
|
||||
it("renders no older-history control when none remains", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline {...buildProps()} timelineEntries={[buildUserTimelineEntry("Hi")]} />,
|
||||
);
|
||||
expect(markup).not.toContain("older history");
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,6 @@ import {
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
FileDiffIcon,
|
||||
FileTextIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
MessageCircleIcon,
|
||||
@@ -65,7 +64,6 @@ import {
|
||||
} from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { formatAttachmentSizeLabel } from "~/lib/attachmentSize";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
@@ -75,6 +73,7 @@ import {
|
||||
deriveMessagesTimelineRows,
|
||||
normalizeCompactToolLabel,
|
||||
resolveAssistantMessageCopyState,
|
||||
resolveOlderHistoryAutoLoad,
|
||||
resolveTimelineIsAtEnd,
|
||||
resolveTimelineMinimapHasPersistentGutter,
|
||||
resolveTimelineMinimapHeightStyle,
|
||||
@@ -187,6 +186,10 @@ interface MessagesTimelineProps {
|
||||
onIsAtEndChange: (isAtEnd: boolean) => void;
|
||||
onManualNavigation: () => void;
|
||||
hideEmptyPlaceholder?: boolean;
|
||||
/** Older history beyond the live activity window can be lazy-loaded. */
|
||||
hasMoreOlder?: boolean;
|
||||
loadingOlder?: boolean;
|
||||
onLoadOlder?: () => void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -221,6 +224,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onIsAtEndChange,
|
||||
onManualNavigation,
|
||||
hideEmptyPlaceholder = false,
|
||||
hasMoreOlder = false,
|
||||
loadingOlder = false,
|
||||
onLoadOlder,
|
||||
}: MessagesTimelineProps) {
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
|
||||
@@ -332,6 +338,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
);
|
||||
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
|
||||
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
|
||||
const olderHistoryRequestedAtStartRef = useRef(false);
|
||||
useEffect(() => {
|
||||
olderHistoryRequestedAtStartRef.current = false;
|
||||
}, [routeThreadKey]);
|
||||
const requestOlderHistoryAtStart = useCallback(() => {
|
||||
olderHistoryRequestedAtStartRef.current = true;
|
||||
onLoadOlder?.();
|
||||
}, [onLoadOlder]);
|
||||
const handleAnchorReady = useCallback(
|
||||
(info: { anchorIndex: number | undefined }) => {
|
||||
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
|
||||
@@ -363,6 +377,20 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (isAtEnd !== undefined) {
|
||||
onIsAtEndChange(isAtEnd);
|
||||
}
|
||||
// Reaching the top lazy-loads one older page. Measurements rerun when the
|
||||
// request settles and when rows prepend, so keep the visit latched until
|
||||
// the user leaves the top; otherwise failures retry forever and successful
|
||||
// pages chain-load the whole history back into memory.
|
||||
const olderHistoryAutoLoad = resolveOlderHistoryAutoLoad({
|
||||
isAtStart: state?.isAtStart,
|
||||
hasMoreOlder: hasMoreOlder && onLoadOlder !== undefined,
|
||||
loadingOlder,
|
||||
requestedAtStart: olderHistoryRequestedAtStartRef.current,
|
||||
});
|
||||
olderHistoryRequestedAtStartRef.current = olderHistoryAutoLoad.requestedAtStart;
|
||||
if (olderHistoryAutoLoad.shouldLoad) {
|
||||
requestOlderHistoryAtStart();
|
||||
}
|
||||
if (!state || minimapItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -385,7 +413,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
strip.dataset.inView = inView ? "true" : "false";
|
||||
}
|
||||
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
|
||||
}, [
|
||||
listRef,
|
||||
minimapItems,
|
||||
minimapStripMap,
|
||||
onIsAtEndChange,
|
||||
hasMoreOlder,
|
||||
loadingOlder,
|
||||
onLoadOlder,
|
||||
requestOlderHistoryAtStart,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(handleScroll);
|
||||
@@ -417,6 +454,28 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
};
|
||||
}, [timelineViewportElement, rows.length]);
|
||||
|
||||
const listHeader = useMemo(() => {
|
||||
if (loadingOlder) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-2 text-xs text-muted-foreground">
|
||||
Loading older history…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (hasMoreOlder) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={requestOlderHistoryAtStart}
|
||||
className="flex w-full cursor-pointer items-center justify-center py-2 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
Load older history
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return TIMELINE_LIST_HEADER;
|
||||
}, [loadingOlder, hasMoreOlder, requestOlderHistoryAtStart]);
|
||||
|
||||
const sharedState = useMemo<TimelineRowSharedState>(
|
||||
() => ({
|
||||
timestampFormat,
|
||||
@@ -468,7 +527,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[],
|
||||
);
|
||||
|
||||
if (rows.length === 0 && !isWorking) {
|
||||
// Only short-circuit to the empty state when there is genuinely nothing to
|
||||
// fetch: the window can derive zero VISIBLE rows (e.g. only tool-neutral work
|
||||
// entries) while older history still exists — the list must render then so
|
||||
// its "Load older history" header stays reachable.
|
||||
if (rows.length === 0 && !isWorking && !hasMoreOlder && !loadingOlder) {
|
||||
if (hideEmptyPlaceholder) {
|
||||
return null;
|
||||
}
|
||||
@@ -513,7 +576,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}}
|
||||
onScroll={handleScroll}
|
||||
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
<TimelineMinimap
|
||||
@@ -883,10 +946,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
...elementContextState.contexts,
|
||||
];
|
||||
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
|
||||
const regularImages = userImages.filter(
|
||||
(image) => image.type === "image" && !image.name.startsWith("preview-annotation-"),
|
||||
);
|
||||
const fileAttachments = userImages.filter((attachment) => attachment.type === "file");
|
||||
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
|
||||
const canRevertAgentWork = typeof row.revertTurnCount === "number";
|
||||
|
||||
return (
|
||||
@@ -925,38 +985,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{fileAttachments.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-1.5">
|
||||
{fileAttachments.map((attachment) => {
|
||||
const chipContent = (
|
||||
<>
|
||||
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="max-w-48 truncate">{attachment.name}</span>
|
||||
<span className="text-muted-foreground/70">
|
||||
{formatAttachmentSizeLabel(attachment.sizeBytes)}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
const chipClassName =
|
||||
"inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-background/70 px-2 py-1 text-[11px]";
|
||||
return attachment.previewUrl ? (
|
||||
<a
|
||||
key={attachment.id}
|
||||
href={attachment.previewUrl}
|
||||
download={attachment.name}
|
||||
className={`${chipClassName} hover:bg-background`}
|
||||
aria-label={`Download ${attachment.name}`}
|
||||
>
|
||||
{chipContent}
|
||||
</a>
|
||||
) : (
|
||||
<span key={attachment.id} className={chipClassName}>
|
||||
{chipContent}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{previewAnnotations.map((annotation, index) => (
|
||||
<UserMessagePreviewAnnotationCard
|
||||
key={annotation.id}
|
||||
|
||||
@@ -65,7 +65,6 @@ import {
|
||||
markPromotedDraftThreadByRef,
|
||||
markPromotedDraftThreads,
|
||||
markPromotedDraftThreadsByRef,
|
||||
type ComposerFileAttachment,
|
||||
type ComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
DraftId,
|
||||
@@ -105,33 +104,6 @@ function makeImage(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function makeFile(input: {
|
||||
id: string;
|
||||
previewUrl: string;
|
||||
name?: string;
|
||||
mimeType?: string;
|
||||
sizeBytes?: number;
|
||||
lastModified?: number;
|
||||
}): ComposerFileAttachment {
|
||||
const name = input.name ?? "report.pdf";
|
||||
const mimeType = input.mimeType ?? "application/pdf";
|
||||
const sizeBytes = input.sizeBytes ?? 4;
|
||||
const lastModified = input.lastModified ?? 1_700_000_000_000;
|
||||
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
|
||||
type: mimeType,
|
||||
lastModified,
|
||||
});
|
||||
return {
|
||||
type: "file",
|
||||
id: input.id,
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes: file.size,
|
||||
previewUrl: input.previewUrl,
|
||||
file,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalContext(input: {
|
||||
id: string;
|
||||
text?: string;
|
||||
@@ -373,123 +345,6 @@ describe("composerDraftStore syncPersistedAttachments", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore file attachments", () => {
|
||||
const threadId = ThreadId.make("thread-file-attachments");
|
||||
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
|
||||
|
||||
beforeEach(() => {
|
||||
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
});
|
||||
|
||||
function mergePersistedDraft(attachment: Record<string, unknown>) {
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
merge: (
|
||||
persistedState: unknown,
|
||||
currentState: ReturnType<typeof useComposerDraftStore.getState>,
|
||||
) => ReturnType<typeof useComposerDraftStore.getState>;
|
||||
};
|
||||
};
|
||||
return persistApi.getOptions().merge(
|
||||
{
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [attachment],
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectKey: {},
|
||||
},
|
||||
useComposerDraftStore.getInitialState(),
|
||||
);
|
||||
}
|
||||
|
||||
it("hydrates persisted attachments without a type as images (legacy drafts)", () => {
|
||||
const mergedState = mergePersistedDraft({
|
||||
id: "img-legacy",
|
||||
name: "legacy.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "data:image/png;base64,aGVsbG8=",
|
||||
});
|
||||
|
||||
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
|
||||
{
|
||||
type: "image",
|
||||
id: "img-legacy",
|
||||
name: "legacy.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
previewUrl: "data:image/png;base64,aGVsbG8=",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("hydrates persisted attachments with type file as file attachments", () => {
|
||||
const mergedState = mergePersistedDraft({
|
||||
type: "file",
|
||||
id: "file-persisted",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "data:application/pdf;base64,aGVsbG8=",
|
||||
});
|
||||
|
||||
expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.images).toMatchObject([
|
||||
{
|
||||
type: "file",
|
||||
id: "file-persisted",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 5,
|
||||
previewUrl: "data:application/pdf;base64,aGVsbG8=",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("persists the file type for staged file attachments (round trip)", () => {
|
||||
const attachment = makeFile({
|
||||
id: "file-round-trip",
|
||||
previewUrl: "data:application/pdf;base64,aGVsbG8=",
|
||||
});
|
||||
useComposerDraftStore.getState().addImage(threadRef, attachment);
|
||||
useComposerDraftStore.getState().syncPersistedAttachments(threadRef, [
|
||||
{
|
||||
type: "file",
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
dataUrl: attachment.previewUrl,
|
||||
},
|
||||
]);
|
||||
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
|
||||
};
|
||||
};
|
||||
const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
|
||||
draftsByThreadKey?: Record<string, { attachments?: Array<Record<string, unknown>> }>;
|
||||
};
|
||||
|
||||
expect(
|
||||
persisted.draftsByThreadKey?.[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.attachments?.[0],
|
||||
).toMatchObject({
|
||||
type: "file",
|
||||
id: "file-round-trip",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore terminal contexts", () => {
|
||||
const threadId = ThreadId.make("thread-dedupe");
|
||||
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
|
||||
|
||||
@@ -33,12 +33,7 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
|
||||
import { useMemo } from "react";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type ChatFileAttachment,
|
||||
type ChatImageAttachment,
|
||||
} from "./types";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
ensureInlineTerminalContextPlaceholders,
|
||||
@@ -84,8 +79,6 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
|
||||
}
|
||||
|
||||
export const PersistedComposerImageAttachment = Schema.Struct({
|
||||
// Missing on drafts persisted before file attachments existed → "image".
|
||||
type: Schema.optionalKey(Schema.Literals(["image", "file"])),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
@@ -99,13 +92,6 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
file: File;
|
||||
}
|
||||
|
||||
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
|
||||
previewUrl: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment;
|
||||
|
||||
const PersistedTerminalContextDraft = Schema.Struct({
|
||||
id: Schema.String,
|
||||
threadId: ThreadId,
|
||||
@@ -263,7 +249,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
|
||||
*/
|
||||
export interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
images: ComposerAttachment[];
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
@@ -448,8 +434,8 @@ interface ComposerDraftStoreState {
|
||||
threadRef: ComposerThreadTarget,
|
||||
interactionMode: ProviderInteractionMode | null | undefined,
|
||||
) => void;
|
||||
addImage: (threadRef: ComposerThreadTarget, image: ComposerAttachment) => void;
|
||||
addImages: (threadRef: ComposerThreadTarget, images: ComposerAttachment[]) => void;
|
||||
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
|
||||
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
|
||||
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
|
||||
insertTerminalContext: (
|
||||
threadRef: ComposerThreadTarget,
|
||||
@@ -565,7 +551,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerAttachment[] = [];
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
||||
@@ -623,7 +609,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
};
|
||||
}
|
||||
|
||||
function composerImageDedupKey(image: ComposerAttachment): string {
|
||||
function composerImageDedupKey(image: ComposerImageAttachment): string {
|
||||
// Keep this independent from File.lastModified so dedupe is stable for hydrated
|
||||
// images reconstructed from localStorage (which get a fresh lastModified value).
|
||||
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
|
||||
@@ -1073,9 +1059,7 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const type = candidate.type;
|
||||
return {
|
||||
...(type === "image" || type === "file" ? { type } : {}),
|
||||
id,
|
||||
name,
|
||||
mimeType,
|
||||
@@ -2100,21 +2084,21 @@ function hydratePersistedComposerImageAttachment(
|
||||
|
||||
function hydrateImagesFromPersisted(
|
||||
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
|
||||
): ComposerAttachment[] {
|
||||
): ComposerImageAttachment[] {
|
||||
return attachments.flatMap((attachment) => {
|
||||
const file = hydratePersistedComposerImageAttachment(attachment);
|
||||
if (!file) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
type: attachment.type ?? ("image" as const),
|
||||
type: "image" as const,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
file,
|
||||
} satisfies ComposerAttachment,
|
||||
} satisfies ComposerImageAttachment,
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -2872,7 +2856,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
existing.images.map((image) => composerImageDedupKey(image)),
|
||||
);
|
||||
const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
|
||||
const dedupedIncoming: ComposerAttachment[] = [];
|
||||
const dedupedIncoming: ComposerImageAttachment[] = [];
|
||||
for (const image of images) {
|
||||
const dedupKey = composerImageDedupKey(image);
|
||||
if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
|
||||
|
||||
@@ -136,41 +136,4 @@ describe("buildBootstrapInput", () => {
|
||||
expect(result.text).toContain("Attached image");
|
||||
expect(result.text).toContain("screenshot.png");
|
||||
});
|
||||
|
||||
it("captures mixed image and file attachment context in transcript blocks", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: messageId("u-mixed"),
|
||||
role: "user",
|
||||
text: "Compare the screenshot with the report.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 2_048,
|
||||
},
|
||||
{
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 4_096,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
turnId: null,
|
||||
updatedAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"What differs?",
|
||||
1_500,
|
||||
);
|
||||
|
||||
expect(result.text).toContain("[Attached image: screenshot.png]");
|
||||
expect(result.text).toContain("[Attached file: report.pdf]");
|
||||
});
|
||||
});
|
||||
@@ -18,30 +18,18 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
|
||||
return message.role === "assistant" ? "ASSISTANT" : "USER";
|
||||
}
|
||||
|
||||
function attachmentSummaryOfType(
|
||||
message: ChatMessage,
|
||||
type: "image" | "file",
|
||||
label: string,
|
||||
): string | null {
|
||||
const typedAttachments = message.attachments?.filter((attachment) => attachment.type === type);
|
||||
const count = typedAttachments?.length ?? 0;
|
||||
function attachmentSummary(message: ChatMessage): string | null {
|
||||
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
|
||||
const count = imageAttachments?.length ?? 0;
|
||||
if (count === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const names = typedAttachments?.slice(0, 3).map((attachment) => attachment.name) ?? [];
|
||||
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
|
||||
const namesSummary = names.join(", ");
|
||||
const extraCount = count - names.length;
|
||||
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
|
||||
return `[Attached ${label}${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
|
||||
}
|
||||
|
||||
function attachmentSummary(message: ChatMessage): string | null {
|
||||
const summaries = [
|
||||
attachmentSummaryOfType(message, "image", "image"),
|
||||
attachmentSummaryOfType(message, "file", "file"),
|
||||
].filter((summary) => summary !== null);
|
||||
return summaries.length > 0 ? summaries.join("\n") : null;
|
||||
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
|
||||
}
|
||||
|
||||
function buildMessageBlock(message: ChatMessage): string {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { formatAttachmentSizeLabel } from "./attachmentSize";
|
||||
|
||||
describe("formatAttachmentSizeLabel", () => {
|
||||
it("formats sub-kilobyte sizes in bytes", () => {
|
||||
expect(formatAttachmentSizeLabel(0)).toBe("0 B");
|
||||
expect(formatAttachmentSizeLabel(512)).toBe("512 B");
|
||||
expect(formatAttachmentSizeLabel(1_023)).toBe("1023 B");
|
||||
});
|
||||
|
||||
it("formats kilobyte sizes with one decimal", () => {
|
||||
expect(formatAttachmentSizeLabel(1_024)).toBe("1.0 KB");
|
||||
expect(formatAttachmentSizeLabel(2_048)).toBe("2.0 KB");
|
||||
expect(formatAttachmentSizeLabel(1_024 * 1_024 - 1)).toBe("1024.0 KB");
|
||||
});
|
||||
|
||||
it("formats megabyte sizes with one decimal", () => {
|
||||
expect(formatAttachmentSizeLabel(1_024 * 1_024)).toBe("1.0 MB");
|
||||
expect(formatAttachmentSizeLabel(2_202_010)).toBe("2.1 MB");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
export function formatAttachmentSizeLabel(sizeBytes: number): string {
|
||||
if (sizeBytes >= 1024 * 1024) {
|
||||
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
if (sizeBytes >= 1024) {
|
||||
return `${(sizeBytes / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
return `${sizeBytes} B`;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type {
|
||||
ChatFileAttachment as ContractChatFileAttachment,
|
||||
ChatImageAttachment as ContractChatImageAttachment,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointSummary,
|
||||
@@ -36,11 +35,7 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
|
||||
readonly previewUrl?: string;
|
||||
}
|
||||
|
||||
export interface ChatFileAttachment extends ContractChatFileAttachment {
|
||||
readonly previewUrl?: string;
|
||||
}
|
||||
|
||||
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment;
|
||||
export type ChatAttachment = ChatImageAttachment;
|
||||
|
||||
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
|
||||
@@ -123,6 +123,14 @@
|
||||
"types": "./src/state/threads.ts",
|
||||
"default": "./src/state/threads.ts"
|
||||
},
|
||||
"./state/thread-reducer": {
|
||||
"types": "./src/state/threadReducer.ts",
|
||||
"default": "./src/state/threadReducer.ts"
|
||||
},
|
||||
"./state/older-thread-activities": {
|
||||
"types": "./src/state/olderThreadActivities.ts",
|
||||
"default": "./src/state/olderThreadActivities.ts"
|
||||
},
|
||||
"./state/thread-sort": {
|
||||
"types": "./src/state/threadSort.ts",
|
||||
"default": "./src/state/threadSort.ts"
|
||||
@@ -143,6 +151,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/react": "~19.2.14",
|
||||
"react": "19.2.6",
|
||||
"vite-plus": "catalog:"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,270 @@
|
||||
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
|
||||
import { liveWindowOldestActivityId, oldestActivityByChronology } from "./threadReducer.ts";
|
||||
|
||||
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = [];
|
||||
|
||||
/**
|
||||
* Pagination cursor for a thread's older activities. Sequenced rows page by
|
||||
* `beforeSequence`; legacy/unsequenced rows (the common case — `sequence` is
|
||||
* absent on most real rows) page by the `(createdAt, activityId)` keyset.
|
||||
*/
|
||||
export type OlderActivitiesCursor =
|
||||
| { readonly beforeSequence: number }
|
||||
| {
|
||||
readonly beforeCreatedAt: OrchestrationThreadActivity["createdAt"];
|
||||
readonly beforeActivityId: OrchestrationThreadActivity["id"];
|
||||
};
|
||||
|
||||
export interface OlderActivitiesPage {
|
||||
readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
|
||||
readonly hasMore: boolean;
|
||||
}
|
||||
|
||||
export interface UseOlderThreadActivitiesOptions {
|
||||
/**
|
||||
* Identity of the thread the live window belongs to (e.g.
|
||||
* `${environmentId}\0${threadId}`); null when no thread is selected.
|
||||
* Changing it resets the lazy-loaded pages.
|
||||
*/
|
||||
readonly threadKey: string | null;
|
||||
/** The server-windowed live activity set from the thread detail. */
|
||||
readonly liveActivities: ReadonlyArray<OrchestrationThreadActivity>;
|
||||
/** The server's `hasMoreActivities` flag from the detail snapshot. */
|
||||
readonly hasMoreLiveActivities: boolean;
|
||||
/**
|
||||
* Fetch the page immediately older than the cursor. Resolve `null` to skip
|
||||
* the page silently (a failure the caller already surfaced, or an
|
||||
* interrupted command) — `hasMore` is left true so the user can retry.
|
||||
* MUST be referentially stable (useCallback) for the load callback to be.
|
||||
*/
|
||||
readonly loadPage: (cursor: OlderActivitiesCursor) => Promise<OlderActivitiesPage | null>;
|
||||
}
|
||||
|
||||
export interface UseOlderThreadActivitiesResult {
|
||||
/** Lazy-loaded older pages + the live window, oldest first. */
|
||||
readonly mergedActivities: ReadonlyArray<OrchestrationThreadActivity>;
|
||||
/** Whether older history exists beyond everything loaded. */
|
||||
readonly hasMoreOlder: boolean;
|
||||
readonly loadingOlder: boolean;
|
||||
/** Dispatch a load of the next older page (no-op while one is in flight). */
|
||||
readonly loadOlder: () => void;
|
||||
}
|
||||
|
||||
// ── Pure decision kernel (exported for unit tests) ──────────────────────────
|
||||
|
||||
export interface LiveWindowShape {
|
||||
readonly key: string | null;
|
||||
/** Chronological-oldest activity id (an identity sentinel, not a lookup key). */
|
||||
readonly oldest: string | null;
|
||||
readonly count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the live window was RESHAPED rather than purely appended-to: a
|
||||
* different thread, a re-snapshot (reconnect) that changes the window's
|
||||
* chronological-oldest row, or a checkpoint revert that shrinks it. A pure
|
||||
* append (same thread, same oldest, count not smaller) is NOT a reshape.
|
||||
*/
|
||||
export function didLiveWindowReshape(previous: LiveWindowShape, next: LiveWindowShape): boolean {
|
||||
return (
|
||||
next.key !== previous.key || next.oldest !== previous.oldest || next.count < previous.count
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cursor for the page immediately older than `oldest`: sequenced rows page
|
||||
* by `beforeSequence`; unsequenced rows (the common case) by the
|
||||
* `(createdAt, activityId)` keyset.
|
||||
*/
|
||||
export function olderActivitiesCursorFor(
|
||||
oldest: OrchestrationThreadActivity,
|
||||
): OlderActivitiesCursor {
|
||||
return oldest.sequence !== undefined
|
||||
? { beforeSequence: oldest.sequence }
|
||||
: { beforeCreatedAt: oldest.createdAt, beforeActivityId: oldest.id };
|
||||
}
|
||||
|
||||
/**
|
||||
* The row the NEXT load should cursor from: the explicit cursor row already
|
||||
* paged past when one exists (so an all-overlap page keeps advancing), else
|
||||
* the chronologically-oldest loaded row — never index 0, which the reducer
|
||||
* can fill with a newer row (unsequenced rows sort to the end).
|
||||
*/
|
||||
export function nextOlderActivitiesCursorRow(
|
||||
pagedPast: OrchestrationThreadActivity | null,
|
||||
merged: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): OrchestrationThreadActivity | null {
|
||||
return pagedPast ?? oldestActivityByChronology(merged);
|
||||
}
|
||||
|
||||
/**
|
||||
* The page rows not already present in the loaded set (older pages + live
|
||||
* window) — boundary overlap and mid-flight appends must never produce
|
||||
* duplicate ids in the merged timeline.
|
||||
*/
|
||||
export function freshOlderActivities(
|
||||
page: OlderActivitiesPage,
|
||||
merged: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
const seen = new Set(merged.map((activity) => activity.id));
|
||||
return page.activities.filter((activity) => !seen.has(activity.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The older-history lazy-load engine, shared by every client (web ChatView,
|
||||
* the mobile composer, the TUI ChatView). The thread-detail snapshot windows
|
||||
* activities to the most recent page; older pages are fetched on demand and
|
||||
* prepended.
|
||||
*
|
||||
* One implementation holds all the hardening the per-client copies kept
|
||||
* drifting on:
|
||||
* - reset on live-window RESHAPE, not just thread switch: a reconnect
|
||||
* re-snapshot changes the window's chronological-oldest row and a checkpoint
|
||||
* revert shrinks it, but a plain append does neither (the reducer re-sorts
|
||||
* unsequenced rows, so index 0 is not a stable boundary — the sentinel is
|
||||
* {@link liveWindowOldestActivityId});
|
||||
* - a generation guard so a load resolving after a reset can't repopulate the
|
||||
* cleared state;
|
||||
* - a synchronous in-flight key so scroll-triggered duplicate dispatches
|
||||
* coalesce before the loading state commits;
|
||||
* - an explicit advancing cursor (the oldest row paged PAST), so an
|
||||
* all-overlap page keeps paging instead of dead-ending while the server
|
||||
* still reports more — the server cursor is strict, so it strictly
|
||||
* decreases and paging cannot loop;
|
||||
* - dedup against the LATEST merged set via a ref, so a live append or a
|
||||
* prior prepend settling mid-flight can't produce duplicate ids;
|
||||
* - `hasMore` stays true on a failed/skipped page (the history still exists;
|
||||
* scrolling back retries).
|
||||
*/
|
||||
export function useOlderThreadActivities(
|
||||
options: UseOlderThreadActivitiesOptions,
|
||||
): UseOlderThreadActivitiesResult {
|
||||
const { threadKey, liveActivities, hasMoreLiveActivities, loadPage } = options;
|
||||
|
||||
const [olderActivities, setOlderActivities] = useState<
|
||||
ReadonlyArray<OrchestrationThreadActivity>
|
||||
>([]);
|
||||
const [olderLoaded, setOlderLoaded] = useState(false);
|
||||
const [olderHasMore, setOlderHasMore] = useState(false);
|
||||
const [loadingOlder, setLoadingOlder] = useState(false);
|
||||
|
||||
// Order-independent oldest boundary: `liveActivities[0]` shifts when the
|
||||
// reducer re-sorts unsequenced rows on the first live append, which would
|
||||
// otherwise make a plain append look like a window reshape.
|
||||
const liveOldestActivityId = useMemo(
|
||||
() => liveWindowOldestActivityId(liveActivities),
|
||||
[liveActivities],
|
||||
);
|
||||
const liveActivityCount = liveActivities.length;
|
||||
|
||||
// Bumps on every reset so a late in-flight load can't repopulate the
|
||||
// freshly-cleared state (the thread key alone doesn't change on a
|
||||
// same-thread window reshape).
|
||||
const generationRef = useRef(0);
|
||||
// The thread key of an in-flight load — coalesces the duplicate dispatches a
|
||||
// fast scroll fires before the loading state updates.
|
||||
const inFlightKeyRef = useRef<string | null>(null);
|
||||
// The oldest row we've paged past; advances even when a page dedupes to
|
||||
// nothing. Reset on reshape.
|
||||
const cursorRef = useRef<OrchestrationThreadActivity | null>(null);
|
||||
const windowRef = useRef({
|
||||
key: threadKey,
|
||||
oldest: liveOldestActivityId,
|
||||
count: liveActivityCount,
|
||||
});
|
||||
|
||||
// useLayoutEffect (not useEffect) so the cleared state commits before paint:
|
||||
// otherwise a thread switch renders one frame with the previous thread's
|
||||
// lazy-loaded pages still merged in, flashing stale rows.
|
||||
useLayoutEffect(() => {
|
||||
const previous = windowRef.current;
|
||||
windowRef.current = {
|
||||
key: threadKey,
|
||||
oldest: liveOldestActivityId,
|
||||
count: liveActivityCount,
|
||||
};
|
||||
if (!didLiveWindowReshape(previous, windowRef.current)) {
|
||||
return;
|
||||
}
|
||||
generationRef.current += 1;
|
||||
inFlightKeyRef.current = null;
|
||||
cursorRef.current = null;
|
||||
setOlderActivities([]);
|
||||
setOlderLoaded(false);
|
||||
setOlderHasMore(false);
|
||||
setLoadingOlder(false);
|
||||
}, [threadKey, liveOldestActivityId, liveActivityCount]);
|
||||
|
||||
const mergedActivities = useMemo(
|
||||
() => (olderActivities.length > 0 ? [...olderActivities, ...liveActivities] : liveActivities),
|
||||
[olderActivities, liveActivities],
|
||||
);
|
||||
// Latest merged set, read inside the async load handler so dedup runs
|
||||
// against current state, not the snapshot captured at dispatch time.
|
||||
const mergedActivitiesRef = useRef(mergedActivities);
|
||||
useLayoutEffect(() => {
|
||||
mergedActivitiesRef.current = mergedActivities;
|
||||
}, [mergedActivities]);
|
||||
|
||||
// Before any page is loaded the server flag is authoritative; afterwards
|
||||
// the latest page's `hasMore` is.
|
||||
const hasMoreOlder = olderLoaded ? olderHasMore : threadKey !== null && hasMoreLiveActivities;
|
||||
|
||||
const loadOlder = useCallback(() => {
|
||||
if (threadKey === null || !hasMoreOlder) {
|
||||
return;
|
||||
}
|
||||
const oldest = nextOlderActivitiesCursorRow(cursorRef.current, mergedActivitiesRef.current);
|
||||
if (!oldest) {
|
||||
return;
|
||||
}
|
||||
if (inFlightKeyRef.current === threadKey) {
|
||||
return; // a load for this thread is already in flight
|
||||
}
|
||||
const cursor = olderActivitiesCursorFor(oldest);
|
||||
const generation = generationRef.current;
|
||||
inFlightKeyRef.current = threadKey;
|
||||
setLoadingOlder(true);
|
||||
void loadPage(cursor)
|
||||
.then((page) => {
|
||||
// The window/thread was reset while this was in flight — drop the page
|
||||
// so it can't repopulate state cleared by the reset.
|
||||
if (generationRef.current !== generation) {
|
||||
return;
|
||||
}
|
||||
if (page === null) {
|
||||
// Failed or interrupted (already surfaced by the caller). Keep
|
||||
// `hasMore` — the history still exists and retrying is valid.
|
||||
return;
|
||||
}
|
||||
// Advance the cursor even when every row dedupes away — the server
|
||||
// cursor is strict, so it strictly decreases and paging can't loop.
|
||||
const pageOldest = page.activities[0];
|
||||
if (pageOldest) {
|
||||
cursorRef.current = pageOldest;
|
||||
}
|
||||
const fresh = freshOlderActivities(page, mergedActivitiesRef.current);
|
||||
if (fresh.length > 0) {
|
||||
setOlderActivities((previous) => [...fresh, ...previous]);
|
||||
}
|
||||
setOlderLoaded(true);
|
||||
setOlderHasMore(page.hasMore);
|
||||
})
|
||||
.finally(() => {
|
||||
if (generationRef.current === generation) {
|
||||
inFlightKeyRef.current = null;
|
||||
setLoadingOlder(false);
|
||||
}
|
||||
});
|
||||
}, [threadKey, hasMoreOlder, loadPage]);
|
||||
|
||||
return {
|
||||
mergedActivities: threadKey === null ? EMPTY_ACTIVITIES : mergedActivities,
|
||||
hasMoreOlder,
|
||||
loadingOlder,
|
||||
loadOlder,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
|
||||
export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
@@ -12,6 +12,11 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
label: "environment-data:orchestration:turn-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
|
||||
}),
|
||||
// Imperative lazy-load of older thread activities (infinite scroll-up).
|
||||
loadThreadActivities: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:orchestration:thread-activities",
|
||||
tag: ORCHESTRATION_WS_METHODS.getThreadActivities,
|
||||
}),
|
||||
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:full-thread-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
|
||||
@@ -9,9 +9,25 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { OrchestrationThread } from "@t3tools/contracts";
|
||||
import type { OrchestrationThread, OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
|
||||
import { applyThreadDetailEvent } from "./threadReducer.ts";
|
||||
import {
|
||||
applyThreadDetailEvent,
|
||||
liveWindowOldestActivityId,
|
||||
oldestActivityByChronology,
|
||||
} from "./threadReducer.ts";
|
||||
|
||||
const activity = (id: string, createdAt: string, sequence?: number): OrchestrationThreadActivity =>
|
||||
({
|
||||
id,
|
||||
tone: "tool",
|
||||
kind: "command",
|
||||
summary: id,
|
||||
payload: {},
|
||||
turnId: TurnId.make("turn-1"),
|
||||
createdAt,
|
||||
...(sequence !== undefined ? { sequence } : {}),
|
||||
}) as unknown as OrchestrationThreadActivity;
|
||||
|
||||
const baseEventFields = {
|
||||
eventId: EventId.make("event-1"),
|
||||
@@ -697,4 +713,61 @@ describe("applyThreadDetailEvent", () => {
|
||||
expect(result.kind).toBe("unchanged");
|
||||
});
|
||||
});
|
||||
|
||||
describe("liveWindowOldestActivityId", () => {
|
||||
it("returns null for an empty window", () => {
|
||||
expect(liveWindowOldestActivityId([])).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the chronologically-oldest id regardless of array position", () => {
|
||||
// Reducer order places the unsequenced legacy row (oldest) LAST while the
|
||||
// server snapshot would list it first; the helper picks it either way.
|
||||
const window = [
|
||||
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
|
||||
activity("seq-2", "2026-04-01T10:00:02.000Z", 2),
|
||||
activity("legacy", "2026-04-01T09:00:00.000Z"),
|
||||
];
|
||||
expect(liveWindowOldestActivityId(window)).toBe("legacy");
|
||||
});
|
||||
|
||||
it("breaks createdAt ties by id", () => {
|
||||
const window = [
|
||||
activity("b", "2026-04-01T10:00:00.000Z", 2),
|
||||
activity("a", "2026-04-01T10:00:00.000Z", 1),
|
||||
];
|
||||
expect(liveWindowOldestActivityId(window)).toBe("a");
|
||||
});
|
||||
|
||||
it("is stable when a newer activity is appended (no false reshape)", () => {
|
||||
const before = [
|
||||
activity("legacy", "2026-04-01T09:00:00.000Z"),
|
||||
activity("seq-1", "2026-04-01T10:00:01.000Z", 1),
|
||||
];
|
||||
// A live append is the newest activity and is unsequenced in the payload;
|
||||
// it must not change the detected oldest boundary.
|
||||
const after = [...before, activity("appended", "2026-04-01T11:00:00.000Z")];
|
||||
expect(liveWindowOldestActivityId(after)).toBe(liveWindowOldestActivityId(before));
|
||||
expect(liveWindowOldestActivityId(after)).toBe("legacy");
|
||||
});
|
||||
});
|
||||
|
||||
describe("oldestActivityByChronology", () => {
|
||||
it("returns null for an empty set", () => {
|
||||
expect(oldestActivityByChronology([])).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the unsequenced legacy row so the pagination cursor agrees with the sentinel", () => {
|
||||
// The reducer placed the legacy (unsequenced, oldest) row at the END; paging
|
||||
// must cursor from it (createdAt cursor), not from index 0's sequenced row.
|
||||
const merged = [
|
||||
activity("seq-5", "2026-04-01T10:00:05.000Z", 5),
|
||||
activity("seq-6", "2026-04-01T10:00:06.000Z", 6),
|
||||
activity("legacy", "2026-04-01T09:00:00.000Z"),
|
||||
];
|
||||
const oldest = oldestActivityByChronology(merged);
|
||||
expect(oldest?.id).toBe("legacy");
|
||||
expect(oldest?.sequence).toBeUndefined(); // → drives the unsequenced cursor
|
||||
expect(liveWindowOldestActivityId(merged)).toBe(oldest?.id); // sentinel agrees
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,45 @@ const activityOrder = O.combineAll<OrchestrationThreadActivity>([
|
||||
O.mapInput(O.String, (a) => a.id),
|
||||
]);
|
||||
|
||||
/**
|
||||
* The oldest activity in a set, by chronology (`createdAt`, then `id`) rather
|
||||
* than array position.
|
||||
*
|
||||
* `activities[0]` is not a stable "oldest": {@link activityOrder} sorts
|
||||
* unsequenced rows to the end (a missing `sequence` is treated as newest) while
|
||||
* the server snapshot lists legacy unsequenced rows first, so the first live
|
||||
* append re-sorts the array and shifts index 0. Both the lazy-load *reshape*
|
||||
* sentinel ({@link liveWindowOldestActivityId}) and the lazy-load *pagination
|
||||
* cursor* derive from this so they agree on which row is oldest regardless of
|
||||
* the reducer's placement of unsequenced rows. Returns `null` when empty.
|
||||
*/
|
||||
export function oldestActivityByChronology(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): OrchestrationThreadActivity | null {
|
||||
let oldest: OrchestrationThreadActivity | null = null;
|
||||
for (const activity of activities) {
|
||||
if (
|
||||
oldest === null ||
|
||||
activity.createdAt < oldest.createdAt ||
|
||||
(activity.createdAt === oldest.createdAt && activity.id < oldest.id)
|
||||
) {
|
||||
oldest = activity;
|
||||
}
|
||||
}
|
||||
return oldest;
|
||||
}
|
||||
|
||||
/**
|
||||
* The id of {@link oldestActivityByChronology}, used as the lazy-load reshape
|
||||
* sentinel (a reconnect re-snapshot or checkpoint revert changes it; a plain
|
||||
* append does not). Returns `null` when empty.
|
||||
*/
|
||||
export function liveWindowOldestActivityId(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): OrchestrationThreadActivity["id"] | null {
|
||||
return oldestActivityByChronology(activities)?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a single orchestration event to an `OrchestrationThread`, returning
|
||||
* the updated thread, a deletion signal, or an "unchanged" marker when the
|
||||
|
||||
@@ -3,9 +3,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ChatAttachment,
|
||||
ChatFileAttachment,
|
||||
ChatImageAttachment,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
ModelSelection,
|
||||
@@ -746,80 +743,3 @@ it.effect("ModelSelection rejects malformed instance ids", () =>
|
||||
assert.strictEqual(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
|
||||
// ── ChatAttachment: image/file union ──────────────────────────────────
|
||||
|
||||
const decodeChatAttachment = Schema.decodeUnknownEffect(ChatAttachment);
|
||||
const decodeChatAttachmentArray = Schema.decodeUnknownEffect(Schema.Array(ChatAttachment));
|
||||
const decodeChatImageAttachment = Schema.decodeUnknownEffect(ChatImageAttachment);
|
||||
const decodeChatFileAttachment = Schema.decodeUnknownEffect(ChatFileAttachment);
|
||||
|
||||
it.effect("ChatAttachment decodes a file attachment with a non-image mime type", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeChatAttachment({
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 2_048,
|
||||
});
|
||||
assert.strictEqual(parsed.type, "file");
|
||||
assert.strictEqual(parsed.name, "report.pdf");
|
||||
assert.strictEqual(parsed.mimeType, "application/pdf");
|
||||
assert.strictEqual(parsed.sizeBytes, 2_048);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ChatAttachment arrays still decode legacy image-only attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeChatAttachmentArray([
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
id: "img-2",
|
||||
name: "diagram.jpeg",
|
||||
mimeType: "image/jpeg",
|
||||
sizeBytes: 4_096,
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(parsed.length, 2);
|
||||
assert.strictEqual(parsed[0]?.type, "image");
|
||||
assert.strictEqual(parsed[1]?.type, "image");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ChatImageAttachment rejects non-image mime types", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
decodeChatImageAttachment({
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 2_048,
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ChatFileAttachment rejects sizeBytes over the 10MB limit", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
decodeChatFileAttachment({
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "big.bin",
|
||||
mimeType: "application/octet-stream",
|
||||
sizeBytes: 10 * 1024 * 1024 + 1,
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
@@ -25,6 +25,7 @@ import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
export const ORCHESTRATION_WS_METHODS = {
|
||||
dispatchCommand: "orchestration.dispatchCommand",
|
||||
getTurnDiff: "orchestration.getTurnDiff",
|
||||
getThreadActivities: "orchestration.getThreadActivities",
|
||||
getFullThreadDiff: "orchestration.getFullThreadDiff",
|
||||
replayEvents: "orchestration.replayEvents",
|
||||
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
|
||||
@@ -173,29 +174,9 @@ const UploadChatImageAttachment = Schema.Struct({
|
||||
});
|
||||
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
|
||||
|
||||
export const ChatFileAttachment = Schema.Struct({
|
||||
type: Schema.Literal("file"),
|
||||
id: ChatAttachmentId,
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
|
||||
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
|
||||
});
|
||||
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
|
||||
|
||||
const UploadChatFileAttachment = Schema.Struct({
|
||||
type: Schema.Literal("file"),
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)),
|
||||
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
|
||||
dataUrl: TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
|
||||
),
|
||||
});
|
||||
export type UploadChatFileAttachment = typeof UploadChatFileAttachment.Type;
|
||||
|
||||
export const ChatAttachment = Schema.Union([ChatImageAttachment, ChatFileAttachment]);
|
||||
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
|
||||
export type ChatAttachment = typeof ChatAttachment.Type;
|
||||
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment, UploadChatFileAttachment]);
|
||||
const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
|
||||
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
|
||||
|
||||
export const ProjectScriptIcon = Schema.Literals([
|
||||
@@ -382,6 +363,10 @@ export const OrchestrationThread = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed([])),
|
||||
),
|
||||
activities: Schema.Array(OrchestrationThreadActivity),
|
||||
// The detail snapshot windows `activities` to the most recent page; this is
|
||||
// true when older activities exist beyond the window and can be lazy-loaded
|
||||
// via the getThreadActivities RPC. Absent on lightweight (shell) threads.
|
||||
hasMoreActivities: Schema.optional(Schema.Boolean),
|
||||
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
|
||||
session: Schema.NullOr(OrchestrationSession),
|
||||
});
|
||||
@@ -1258,6 +1243,37 @@ export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput
|
||||
export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
|
||||
export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
|
||||
|
||||
/**
|
||||
* Cursor-paginated load of a thread's OLDER activities (lazy-load / infinite
|
||||
* scroll). Sequenced activity uses `beforeSequence`, the `sequence` of the
|
||||
* oldest activity the client currently holds. Legacy unsequenced activity uses
|
||||
* the `(beforeCreatedAt, beforeActivityId)` pair from the oldest loaded
|
||||
* activity. The server returns the page of activities immediately older than the
|
||||
* cursor (chronological ascending) plus whether any remain beyond that.
|
||||
*/
|
||||
export const OrchestrationGetThreadActivitiesInput = Schema.Union([
|
||||
Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
beforeSequence: NonNegativeInt,
|
||||
limit: Schema.optional(NonNegativeInt),
|
||||
}),
|
||||
Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
beforeCreatedAt: IsoDateTime,
|
||||
beforeActivityId: EventId,
|
||||
limit: Schema.optional(NonNegativeInt),
|
||||
}),
|
||||
]);
|
||||
export type OrchestrationGetThreadActivitiesInput =
|
||||
typeof OrchestrationGetThreadActivitiesInput.Type;
|
||||
|
||||
export const OrchestrationGetThreadActivitiesResult = Schema.Struct({
|
||||
activities: Schema.Array(OrchestrationThreadActivity),
|
||||
hasMore: Schema.Boolean,
|
||||
});
|
||||
export type OrchestrationGetThreadActivitiesResult =
|
||||
typeof OrchestrationGetThreadActivitiesResult.Type;
|
||||
|
||||
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
toTurnCount: NonNegativeInt,
|
||||
@@ -1285,6 +1301,10 @@ export const OrchestrationRpcSchemas = {
|
||||
input: OrchestrationGetTurnDiffInput,
|
||||
output: OrchestrationGetTurnDiffResult,
|
||||
},
|
||||
getThreadActivities: {
|
||||
input: OrchestrationGetThreadActivitiesInput,
|
||||
output: OrchestrationGetThreadActivitiesResult,
|
||||
},
|
||||
getFullThreadDiff: {
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
output: OrchestrationGetFullThreadDiffResult,
|
||||
@@ -1331,6 +1351,14 @@ export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<Orche
|
||||
},
|
||||
) {}
|
||||
|
||||
export class OrchestrationGetThreadActivitiesError extends Schema.TaggedErrorClass<OrchestrationGetThreadActivitiesError>()(
|
||||
"OrchestrationGetThreadActivitiesError",
|
||||
{
|
||||
message: TrimmedNonEmptyString,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
|
||||
"OrchestrationGetFullThreadDiffError",
|
||||
{
|
||||
|
||||
@@ -52,6 +52,8 @@ import {
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetSnapshotError,
|
||||
OrchestrationGetThreadActivitiesError,
|
||||
OrchestrationGetThreadActivitiesInput,
|
||||
OrchestrationGetTurnDiffError,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationReplayEventsError,
|
||||
@@ -612,6 +614,15 @@ export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.g
|
||||
error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsOrchestrationGetThreadActivitiesRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.getThreadActivities,
|
||||
{
|
||||
payload: OrchestrationGetThreadActivitiesInput,
|
||||
success: OrchestrationRpcSchemas.getThreadActivities.output,
|
||||
error: Schema.Union([OrchestrationGetThreadActivitiesError, EnvironmentAuthorizationError]),
|
||||
},
|
||||
);
|
||||
|
||||
export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
|
||||
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
{
|
||||
@@ -753,6 +764,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeAuthAccessRpc,
|
||||
WsOrchestrationDispatchCommandRpc,
|
||||
WsOrchestrationGetTurnDiffRpc,
|
||||
WsOrchestrationGetThreadActivitiesRpc,
|
||||
WsOrchestrationGetFullThreadDiffRpc,
|
||||
WsOrchestrationReplayEventsRpc,
|
||||
WsOrchestrationGetArchivedShellSnapshotRpc,
|
||||
|
||||
Generated
+6
@@ -746,6 +746,12 @@ importers:
|
||||
'@effect/vitest':
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78(patch_hash=42b87cc47e70d74e62496e7a8261b3fd298ecad4464d209348ab04b96f853a5f)([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
|
||||
'@types/react':
|
||||
specifier: ~19.2.14
|
||||
version: 19.2.16
|
||||
react:
|
||||
specifier: 19.2.6
|
||||
version: 19.2.6
|
||||
vite-plus:
|
||||
specifier: 'catalog:'
|
||||
version: 0.2.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])
|
||||
|
||||
Reference in new issue
Block a user