feat(chat): attach files to question answers (#9871)
This commit is contained in:
1 parent
349ce30142
commit
7220dfe2c9
40 files changed
+2315
-153
No files matched your search
@@ -128,6 +128,7 @@
|
||||
"@effect/vitest": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@types/react": "~19.2.0",
|
||||
"@types/react-dom": "~19.2.3",
|
||||
"babel-preset-expo": "~57.0.9",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QuestionAttachments } from "./QuestionAttachments";
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
@@ -15,7 +16,7 @@ import Animated, {
|
||||
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import {
|
||||
@@ -305,18 +306,17 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
{question.allowCustomAnswer !== false ? (
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
|
||||
/>
|
||||
) : null}
|
||||
<QuestionAttachments
|
||||
requestId={props.pendingUserInput.requestId}
|
||||
question={question}
|
||||
questions={props.pendingUserInput.questions}
|
||||
disabled={props.respondingUserInputId === props.pendingUserInput.requestId}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
onInputFocusChange={props.onInputFocusChange}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ApprovalRequestId, EnvironmentId } from "@t3tools/contracts";
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("react-native", () => ({
|
||||
View: "div",
|
||||
Pressable: ({ children }: { children: ReactNode }) => <button>{children}</button>,
|
||||
Image: "img",
|
||||
Linking: { openURL: vi.fn() },
|
||||
}));
|
||||
vi.mock("../../components/AppText", () => ({ AppText: "span" }));
|
||||
vi.mock("../../state/assets", () => ({ useAssetUrl: () => null }));
|
||||
|
||||
import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
|
||||
|
||||
describe("QuestionAnswerHistory", () => {
|
||||
it.each([{}, { text: "Text-only answer", file: "Answer with a file" }])(
|
||||
"renders attachment-only questions alongside text answers: %j",
|
||||
(answers) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<QuestionAnswerHistory
|
||||
environmentId={EnvironmentId.make("environment-local")}
|
||||
answer={{
|
||||
requestId: ApprovalRequestId.make("question-request"),
|
||||
answers,
|
||||
questionTextById: { file: "Provide a spec", image: "Provide a screenshot" },
|
||||
attachmentsByQuestionId: {
|
||||
file: [
|
||||
{
|
||||
type: "file",
|
||||
id: "spec",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
image: [
|
||||
{
|
||||
type: "image",
|
||||
id: "shot",
|
||||
name: "shot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(markup.match(/Provide a spec/g)).toHaveLength(1);
|
||||
expect(markup.match(/spec\.txt/g)).toHaveLength(1);
|
||||
expect(markup).toContain("Provide a screenshot");
|
||||
expect(markup).toContain("shot.png");
|
||||
for (const answer of Object.values(answers)) expect(markup).toContain(answer);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
UserInputAttachmentAnswerPayload,
|
||||
UserInputAttachments,
|
||||
} from "@t3tools/contracts";
|
||||
import { Image, Linking, Pressable, View } from "react-native";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
|
||||
function AnswerFile(props: {
|
||||
environmentId: EnvironmentId;
|
||||
attachment: UserInputAttachments[string][number];
|
||||
}) {
|
||||
const url = useAssetUrl(props.environmentId, {
|
||||
_tag: "attachment",
|
||||
attachmentId: props.attachment.id,
|
||||
});
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={props.attachment.name}
|
||||
disabled={!url}
|
||||
onPress={() => {
|
||||
if (url) void Linking.openURL(url);
|
||||
}}
|
||||
className="gap-1"
|
||||
>
|
||||
{props.attachment.type === "image" && url ? (
|
||||
<Image source={{ uri: url }} style={{ width: 160, height: 96 }} resizeMode="contain" />
|
||||
) : null}
|
||||
<Text className="text-sm text-foreground underline">{props.attachment.name}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function QuestionAnswerHistory(props: {
|
||||
environmentId: EnvironmentId;
|
||||
answer: UserInputAttachmentAnswerPayload;
|
||||
}) {
|
||||
return (
|
||||
<View className="gap-2">
|
||||
{[
|
||||
...new Set([
|
||||
...Object.keys(props.answer.answers),
|
||||
...Object.keys(props.answer.attachmentsByQuestionId),
|
||||
]),
|
||||
].map((questionId) => (
|
||||
<View key={questionId} className="gap-1">
|
||||
{props.answer.questionTextById?.[questionId] ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{props.answer.questionTextById[questionId]}
|
||||
</Text>
|
||||
) : null}
|
||||
<Text className="text-sm text-foreground">
|
||||
{[props.answer.answers[questionId]]
|
||||
.flat()
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.join(", ")}
|
||||
</Text>
|
||||
{(props.answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => (
|
||||
<AnswerFile
|
||||
key={attachment.id}
|
||||
environmentId={props.environmentId}
|
||||
attachment={attachment}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import { AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { useNativePaste } from "../../lib/useNativePaste";
|
||||
import { convertPastedImagesToAttachments } from "../../lib/composerImages";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
type ApprovalRequestId,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Alert, View } from "react-native";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { pickComposerFiles, pickComposerMedia } from "../../lib/composerImages";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useServerConfigs } from "../../state/entities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
composerDraftsAtom,
|
||||
removeComposerDraftAttachment,
|
||||
releaseUnusedComposerAttachmentFiles,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import {
|
||||
changeQuestionAttachmentPreparation,
|
||||
questionAttachmentDraftKey,
|
||||
questionAttachmentPreparationAtom,
|
||||
} from "../../state/question-attachments";
|
||||
|
||||
export function QuestionAttachments(props: {
|
||||
requestId: ApprovalRequestId;
|
||||
question: UserInputQuestion;
|
||||
questions: ReadonlyArray<UserInputQuestion>;
|
||||
disabled: boolean;
|
||||
value: string;
|
||||
onChangeText: (value: string) => void;
|
||||
onInputFocusChange?: ((focused: boolean) => void) | undefined;
|
||||
}) {
|
||||
const { selectedThread } = useThreadSelection();
|
||||
const configs = useServerConfigs();
|
||||
const drafts = useAtomValue(composerDraftsAtom);
|
||||
const scopeKey = JSON.stringify([
|
||||
selectedThread?.environmentId,
|
||||
selectedThread?.id,
|
||||
props.requestId,
|
||||
props.question.id,
|
||||
]);
|
||||
const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
|
||||
useEffect(() => {
|
||||
const scope = { key: scopeKey, active: true };
|
||||
pickerScope.current = scope;
|
||||
return () => {
|
||||
scope.active = false;
|
||||
};
|
||||
}, [scopeKey]);
|
||||
const append = (
|
||||
key: string,
|
||||
attachments: Parameters<typeof appendComposerDraftAttachments>[1],
|
||||
) => {
|
||||
if (!selectedThread) return 0;
|
||||
const current = appAtomRegistry.get(composerDraftsAtom);
|
||||
const otherCount = props.questions.reduce((count, question) => {
|
||||
const target = questionAttachmentDraftKey(
|
||||
selectedThread.environmentId,
|
||||
selectedThread.id,
|
||||
props.requestId,
|
||||
question.id,
|
||||
);
|
||||
return target === key ? count : count + (current[target]?.attachments.length ?? 0);
|
||||
}, 0);
|
||||
return appendComposerDraftAttachments(key, attachments, {
|
||||
maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
|
||||
});
|
||||
};
|
||||
const paste = useNativePaste((uris) => {
|
||||
const scope = pickerScope.current;
|
||||
if (
|
||||
!selectedThread ||
|
||||
props.disabled ||
|
||||
!configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
|
||||
)
|
||||
return;
|
||||
const key = questionAttachmentDraftKey(
|
||||
selectedThread.environmentId,
|
||||
selectedThread.id,
|
||||
props.requestId,
|
||||
props.question.id,
|
||||
);
|
||||
changeQuestionAttachmentPreparation(key, 1);
|
||||
void convertPastedImagesToAttachments({
|
||||
uris,
|
||||
existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
|
||||
})
|
||||
.then(async (images) => {
|
||||
if (
|
||||
scope?.active &&
|
||||
(appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
|
||||
) {
|
||||
if (append(key, images) > 0)
|
||||
Alert.alert("Could not paste image", "Too many attachments.");
|
||||
} else await releaseUnusedComposerAttachmentFiles(images);
|
||||
})
|
||||
.catch((error) =>
|
||||
Alert.alert("Could not paste image", error instanceof Error ? error.message : "Try again."),
|
||||
)
|
||||
.finally(() => changeQuestionAttachmentPreparation(key, -1));
|
||||
});
|
||||
if (!selectedThread || props.question.allowCustomAnswer === false) return null;
|
||||
const { environmentId, id: threadId } = selectedThread;
|
||||
const capabilities = configs.get(environmentId)?.environment.capabilities;
|
||||
const canAttach = capabilities?.questionAttachments === true;
|
||||
const key = questionAttachmentDraftKey(
|
||||
environmentId,
|
||||
threadId,
|
||||
props.requestId,
|
||||
props.question.id,
|
||||
);
|
||||
const attachments = drafts[key]?.attachments ?? [];
|
||||
const pick = async (kind: "media" | "files") => {
|
||||
const scope = pickerScope.current;
|
||||
changeQuestionAttachmentPreparation(key, 1);
|
||||
try {
|
||||
const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
|
||||
const result =
|
||||
kind === "files"
|
||||
? await pickComposerFiles({
|
||||
existingCount,
|
||||
maxBytes: capabilities?.fileAttachments?.maxUploadBytes,
|
||||
})
|
||||
: await pickComposerMedia({
|
||||
existingCount,
|
||||
maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
|
||||
});
|
||||
const picked = "files" in result ? result.files : result.attachments;
|
||||
// Resolution on another client clears the reservation while the picker is open.
|
||||
if (
|
||||
!scope?.active ||
|
||||
(appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
|
||||
) {
|
||||
await releaseUnusedComposerAttachmentFiles(picked);
|
||||
return;
|
||||
}
|
||||
const rejected = append(key, picked);
|
||||
if (result.error || rejected > 0)
|
||||
Alert.alert("Could not attach file", result.error ?? "Too many attachments.");
|
||||
} catch (error) {
|
||||
Alert.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
|
||||
} finally {
|
||||
changeQuestionAttachmentPreparation(key, -1);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<View className="gap-2">
|
||||
{canAttach ? (
|
||||
<ComposerAttachmentButton
|
||||
disabled={props.disabled}
|
||||
supportsFiles={Boolean(capabilities?.fileAttachments)}
|
||||
onPickMedia={() => pick("media")}
|
||||
onPickFiles={() => pick("files")}
|
||||
/>
|
||||
) : null}
|
||||
<ComposerAttachmentStrip
|
||||
environmentId={environmentId}
|
||||
attachments={attachments}
|
||||
onRemove={(id) => {
|
||||
if (!props.disabled) removeComposerDraftAttachment(key, id);
|
||||
}}
|
||||
/>
|
||||
<TextInputWrapper onPaste={paste}>
|
||||
<TextInput
|
||||
value={props.value}
|
||||
editable={!props.disabled}
|
||||
onChangeText={props.onChangeText}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
|
||||
/>
|
||||
</TextInputWrapper>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
@@ -849,13 +850,19 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{expanded && (fullDetail || viewedImagePath) ? (
|
||||
{expanded && (fullDetail || viewedImagePath || row.workEntry.questionAnswer) ? (
|
||||
<Animated.View
|
||||
entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
|
||||
exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
|
||||
layout={WORK_LOG_LAYOUT_TRANSITION}
|
||||
className="ml-7 border-l border-adaptive-neutral-300-a60-white-a12 pb-1 pl-3 pt-0.5"
|
||||
>
|
||||
{row.workEntry.questionAnswer ? (
|
||||
<QuestionAnswerHistory
|
||||
environmentId={props.environmentId}
|
||||
answer={row.workEntry.questionAnswer}
|
||||
/>
|
||||
) : null}
|
||||
{viewedImagePath ? (
|
||||
<View className="pb-1.5">
|
||||
{props.renderImage({ href: viewedImagePath, alt: null, title: null })}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
questionAttachmentDraftKey,
|
||||
questionAttachmentDraftPrefix,
|
||||
} from "../state/question-attachments";
|
||||
vi.mock("../state/atom-registry", () => ({ appAtomRegistry: {} }));
|
||||
|
||||
import {
|
||||
composerAttachmentUploadBlockReason,
|
||||
@@ -217,6 +222,26 @@ describe("composer attachment upload queue", () => {
|
||||
});
|
||||
|
||||
describe("draft upload scope and offline submission", () => {
|
||||
it("uploads question drafts in their environment without matching other thread prefixes", () => {
|
||||
const requestId = ApprovalRequestId.make("request:1");
|
||||
for (const environment of [environmentId, EnvironmentId.make("remote:server")]) {
|
||||
const threadId = ThreadId.make("thread:1");
|
||||
const prefix = questionAttachmentDraftPrefix(environment, threadId);
|
||||
const key = questionAttachmentDraftKey(environment, threadId, requestId, "question:1");
|
||||
expect(composerDraftEnvironmentId(key, [])).toBe(environment);
|
||||
expect(key.startsWith(prefix)).toBe(true);
|
||||
for (const suffix of ["-extra", ":extra", "/extra", "%extra"]) {
|
||||
const otherKey = questionAttachmentDraftKey(
|
||||
environment,
|
||||
ThreadId.make(`${threadId}${suffix}`),
|
||||
requestId,
|
||||
"question:1",
|
||||
);
|
||||
expect(otherKey.startsWith(prefix)).toBe(false);
|
||||
expect(composerDraftEnvironmentId(otherKey, [])).toBe(environment);
|
||||
}
|
||||
}
|
||||
});
|
||||
it("resolves thread, new-task, and queued-task drafts without crossing environments", () => {
|
||||
expect(composerDraftEnvironmentId("environment-1:thread", [])).toBe(environmentId);
|
||||
expect(composerDraftEnvironmentId("new-task:environment-1:project", [])).toBe(environmentId);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests"
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
@@ -3314,3 +3315,72 @@ describe("quiet timeline: nested agents", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts ready attachment-only answers while preserving selected options", () => {
|
||||
const question = {
|
||||
id: "q",
|
||||
header: "Spec",
|
||||
question: "Provide a specification",
|
||||
options: [{ label: "Yes", description: "Approve" }],
|
||||
multiSelect: false,
|
||||
};
|
||||
expect(buildPendingUserInputAnswers([question], { q: { attachmentCount: 1 } })).toEqual({
|
||||
q: "",
|
||||
});
|
||||
expect(
|
||||
buildPendingUserInputAnswers([question], {
|
||||
q: { attachmentCount: 1, selectedOptionValues: ["Yes"] },
|
||||
}),
|
||||
).toEqual({ q: "Yes" });
|
||||
expect(
|
||||
buildPendingUserInputAnswers([question], {
|
||||
q: { attachmentCount: 1, attachmentsBlocked: true },
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
buildPendingUserInputAnswers([{ ...question, allowCustomAnswer: false }], {
|
||||
q: { attachmentCount: 1 },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("makes attachment-only question answers expandable in the mobile feed", () => {
|
||||
const answer = {
|
||||
requestId: ApprovalRequestId.make("question-request"),
|
||||
answers: { q: "" },
|
||||
questionTextById: { q: "Attach the specification" },
|
||||
attachmentsByQuestionId: {
|
||||
q: [
|
||||
{
|
||||
type: "file" as const,
|
||||
id: "question-file",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-answer"),
|
||||
projectId: ProjectId.make("project-answer"),
|
||||
title: "Answer history",
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("answer-submitted"),
|
||||
createdAt: "2026-09-08T00:00:00.000Z",
|
||||
kind: "user-input.answer-submitted",
|
||||
summary: "Answered questions",
|
||||
payload: answer,
|
||||
}),
|
||||
],
|
||||
});
|
||||
const [group] = buildThreadFeed(thread);
|
||||
expect(group?.type).toBe("activity-group");
|
||||
if (group?.type !== "activity-group") return;
|
||||
expect(group.activities[0]).toMatchObject({
|
||||
canExpand: true,
|
||||
workEntry: { questionAnswer: answer },
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toBeNull();
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
requestKindFromRequestType,
|
||||
type PendingApproval,
|
||||
} from "@t3tools/client-runtime/pending-requests";
|
||||
import { isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import { UserInputAttachmentAnswerPayload, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
@@ -41,6 +43,8 @@ export type { PendingApproval, PendingUserInput } from "@t3tools/client-runtime/
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
readonly selectedOptionValues?: ReadonlyArray<string>;
|
||||
readonly customAnswer?: string;
|
||||
readonly attachmentCount?: number;
|
||||
readonly attachmentsBlocked?: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadFeedActivity {
|
||||
@@ -76,6 +80,7 @@ export interface ThreadFeedActivity {
|
||||
}
|
||||
|
||||
export interface WorkLogEntry {
|
||||
readonly questionAnswer?: UserInputAttachmentAnswerPayload;
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId | null;
|
||||
@@ -302,6 +307,7 @@ function resolvePendingUserInputAnswer(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
): string | ReadonlyArray<string> | null {
|
||||
if (draft?.attachmentsBlocked) return null;
|
||||
const customAnswer =
|
||||
question.allowCustomAnswer === false ? null : normalizeDraftAnswer(draft?.customAnswer);
|
||||
if (customAnswer) {
|
||||
@@ -310,9 +316,16 @@ function resolvePendingUserInputAnswer(
|
||||
|
||||
const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
|
||||
if (question.multiSelect) {
|
||||
return selectedOptionValues.length > 0 ? selectedOptionValues : null;
|
||||
return selectedOptionValues.length > 0
|
||||
? selectedOptionValues
|
||||
: question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0
|
||||
? ""
|
||||
: null;
|
||||
}
|
||||
return selectedOptionValues[0] ?? null;
|
||||
return (
|
||||
selectedOptionValues[0] ??
|
||||
(question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
|
||||
);
|
||||
}
|
||||
|
||||
/** Some providers settle agents through task.updated instead of task.completed. */
|
||||
@@ -435,6 +448,8 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
const decodeQuestionAttachmentAnswer = Schema.decodeUnknownOption(UserInputAttachmentAnswerPayload);
|
||||
|
||||
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
@@ -480,6 +495,11 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
? "info"
|
||||
: activity.tone,
|
||||
sourceActivityKind: activity.kind,
|
||||
...(() => {
|
||||
if (activity.kind !== "user-input.answer-submitted") return {};
|
||||
const answer = decodeQuestionAttachmentAnswer(activity.payload);
|
||||
return Option.isSome(answer) ? { questionAnswer: answer.value } : {};
|
||||
})(),
|
||||
};
|
||||
const toolCallId =
|
||||
asTrimmedString(payload?.toolCallId) ?? asTrimmedString(asRecord(payload?.data)?.toolCallId);
|
||||
@@ -969,6 +989,7 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
|
||||
* for every row (see the deferred-expansion test).
|
||||
*/
|
||||
function workEntryCanExpand(entry: WorkLogEntry): boolean {
|
||||
if (entry.questionAnswer) return true;
|
||||
if (entry.agentSpawn) return agentSpawnMembers(entry.agentSpawn).length > 0;
|
||||
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) return true;
|
||||
if (entry.changedFiles?.some((path) => path.trim().length > 0)) return true;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
export function questionAttachmentDraftPrefix(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
): string {
|
||||
return `${environmentId}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
|
||||
}
|
||||
export function questionAttachmentDraftKey(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
): string {
|
||||
return `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`;
|
||||
}
|
||||
export const questionAttachmentPreparationAtom = Atom.make<Record<string, number>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
);
|
||||
export function changeQuestionAttachmentPreparation(key: string, delta: number): void {
|
||||
const counts = appAtomRegistry.get(questionAttachmentPreparationAtom);
|
||||
if (delta < 0 && !(key in counts)) return;
|
||||
appAtomRegistry.set(questionAttachmentPreparationAtom, {
|
||||
...counts,
|
||||
[key]: Math.max(0, (counts[key] ?? 0) + delta),
|
||||
});
|
||||
}
|
||||
@@ -925,7 +925,7 @@ export function appendComposerDraftText(draftKey: string, value: string): void {
|
||||
export function appendComposerDraftAttachments(
|
||||
draftKey: string,
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
options?: { readonly allowOverflow?: boolean },
|
||||
options?: { readonly allowOverflow?: boolean; readonly maxAttachments?: number },
|
||||
): number {
|
||||
if (attachments.length === 0) {
|
||||
return 0;
|
||||
@@ -935,7 +935,13 @@ export function appendComposerDraftAttachments(
|
||||
const existing = normalizeDraft(current[draftKey]);
|
||||
const remaining = options?.allowOverflow
|
||||
? attachments.length
|
||||
: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
|
||||
: Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
) - existing.attachments.length,
|
||||
);
|
||||
const accepted = attachments.slice(0, remaining);
|
||||
rejected = attachments.slice(remaining);
|
||||
if (accepted.length === 0) {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const fixture = vi.hoisted(() => ({
|
||||
drafts: {} as Record<string, unknown>,
|
||||
uploads: {} as Record<string, unknown>,
|
||||
preparations: {} as Record<string, number>,
|
||||
preparationAtom: Symbol("preparation"),
|
||||
}));
|
||||
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
|
||||
vi.mock("@effect/atom-react", () => ({
|
||||
useAtomValue: (atom: unknown) =>
|
||||
atom === "drafts"
|
||||
? fixture.drafts
|
||||
: atom === "uploads"
|
||||
? fixture.uploads
|
||||
: atom === fixture.preparationAtom
|
||||
? fixture.preparations
|
||||
: {},
|
||||
}));
|
||||
vi.mock("./use-composer-drafts", () => ({
|
||||
composerDraftsAtom: "drafts",
|
||||
clearComposerDraft: vi.fn(),
|
||||
}));
|
||||
vi.mock("./composer-attachment-uploads", async () => ({
|
||||
...(await import("../lib/composerAttachmentUploadQueue")),
|
||||
composerAttachmentUploadsAtom: "uploads",
|
||||
}));
|
||||
vi.mock("./question-attachments", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("./question-attachments")>()),
|
||||
questionAttachmentPreparationAtom: fixture.preparationAtom,
|
||||
}));
|
||||
vi.mock("./entities", () => ({
|
||||
useServerConfigs: () =>
|
||||
new Map([
|
||||
[
|
||||
"environment-1",
|
||||
{
|
||||
environment: {
|
||||
capabilities: {
|
||||
questionAttachments: true,
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: 20_000_000 },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
}));
|
||||
vi.mock("./threads", () => ({ threadEnvironment: {} }));
|
||||
vi.mock("./use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
|
||||
vi.mock("./use-thread-selection", () => ({
|
||||
useThreadSelection: () => ({
|
||||
selectedThread: { environmentId: "environment-1", id: "thread-1" },
|
||||
}),
|
||||
}));
|
||||
vi.mock("./use-thread-detail", () => ({
|
||||
useSelectedThreadDetail: () => ({
|
||||
activities: [
|
||||
{
|
||||
id: "request-activity",
|
||||
kind: "user-input.requested",
|
||||
createdAt: "2026-09-08T00:00:00Z",
|
||||
payload: {
|
||||
requestId: "request-1",
|
||||
questions: ["first", "second"].map((id) => ({
|
||||
id,
|
||||
header: id,
|
||||
question: `Attach ${id} file`,
|
||||
options: [],
|
||||
allowCustomAnswer: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { questionAttachmentDraftKey } from "./question-attachments";
|
||||
import { useSelectedThreadRequests } from "./use-selected-thread-requests";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const key = (question: string) =>
|
||||
questionAttachmentDraftKey(
|
||||
environmentId,
|
||||
ThreadId.make("thread-1"),
|
||||
ApprovalRequestId.make("request-1"),
|
||||
question,
|
||||
);
|
||||
function submitButtonMarkup() {
|
||||
function Probe() {
|
||||
const { activePendingUserInputAnswers } = useSelectedThreadRequests();
|
||||
return <button disabled={activePendingUserInputAnswers === null}>Submit answers</button>;
|
||||
}
|
||||
return renderToStaticMarkup(<Probe />);
|
||||
}
|
||||
beforeEach(() => {
|
||||
fixture.preparations = {};
|
||||
fixture.drafts = Object.fromEntries(
|
||||
["first", "second"].map((id) => [
|
||||
key(id),
|
||||
{
|
||||
attachments: [
|
||||
{
|
||||
id,
|
||||
type: "file",
|
||||
name: `${id}.txt`,
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
fileUri: `file:///${id}.txt`,
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
fixture.uploads = { "environment-1:first": { status: "ready" } };
|
||||
});
|
||||
describe("question attachment submission readiness", () => {
|
||||
it.each([
|
||||
undefined,
|
||||
{ status: "uploading", progress: 0.5 },
|
||||
{ status: "failed", reason: "Offline" },
|
||||
])("keeps Submit disabled until all question uploads finish: %j", (state) => {
|
||||
if (state) fixture.uploads["environment-1:second"] = state;
|
||||
expect(submitButtonMarkup()).toContain("disabled");
|
||||
fixture.uploads["environment-1:second"] = { status: "ready" };
|
||||
expect(submitButtonMarkup()).not.toContain("disabled");
|
||||
});
|
||||
it("ignores an upload in another environment", () => {
|
||||
fixture.uploads["environment-1:second"] = { status: "ready" };
|
||||
fixture.uploads["environment-2:second"] = { status: "uploading", progress: 0.5 };
|
||||
expect(submitButtonMarkup()).not.toContain("disabled");
|
||||
});
|
||||
it("waits for attachment preparation even when uploads are ready", () => {
|
||||
fixture.uploads["environment-1:second"] = { status: "ready" };
|
||||
fixture.preparations[key("first")] = 1;
|
||||
expect(submitButtonMarkup()).toContain("disabled");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,19 @@
|
||||
import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
|
||||
import { useServerConfigs } from "./entities";
|
||||
import { Alert } from "react-native";
|
||||
import {
|
||||
questionAttachmentDraftKey,
|
||||
questionAttachmentDraftPrefix,
|
||||
questionAttachmentPreparationAtom,
|
||||
} from "./question-attachments";
|
||||
import { composerDraftsAtom, clearComposerDraft } from "./use-composer-drafts";
|
||||
import {
|
||||
composerAttachmentUploadsAtom,
|
||||
composerAttachmentUploadBlockReason,
|
||||
composerAttachmentsStillUploading,
|
||||
} from "./composer-attachment-uploads";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -81,6 +94,7 @@ export function useSelectedThreadRequests() {
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const userInputResponsesInFlight = useRef(new Set<string>());
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
@@ -91,11 +105,81 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const questionServerConfigs = useServerConfigs();
|
||||
const attachmentDrafts = useAtomValue(composerDraftsAtom);
|
||||
const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
|
||||
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
|
||||
useEffect(() => {
|
||||
if (!selectedThreadShell || !selectedThread) return;
|
||||
const prefix = questionAttachmentDraftPrefix(
|
||||
selectedThreadShell.environmentId,
|
||||
selectedThreadShell.id,
|
||||
);
|
||||
const retained = new Set(
|
||||
activePendingUserInputs.flatMap((request) =>
|
||||
request.questions.map((question) =>
|
||||
questionAttachmentDraftKey(
|
||||
selectedThreadShell.environmentId,
|
||||
selectedThreadShell.id,
|
||||
request.requestId,
|
||||
question.id,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
|
||||
let changed = false;
|
||||
for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {
|
||||
if (!key.startsWith(prefix) || retained.has(key)) continue;
|
||||
if (attachmentDrafts[key]) clearComposerDraft(key);
|
||||
if (key in counts) {
|
||||
delete counts[key];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
|
||||
}, [activePendingUserInputs, attachmentDrafts, selectedThread, selectedThreadShell]);
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedThreadShell
|
||||
? (userInputDraftsByRequestKey[
|
||||
scopedRequestKey(selectedThreadShell.environmentId, activePendingUserInput.requestId)
|
||||
] ?? {})
|
||||
? Object.fromEntries(
|
||||
activePendingUserInput.questions.map((question) => {
|
||||
const key = questionAttachmentDraftKey(
|
||||
selectedThreadShell.environmentId,
|
||||
selectedThreadShell.id,
|
||||
activePendingUserInput.requestId,
|
||||
question.id,
|
||||
);
|
||||
const attachments = attachmentDrafts[key]?.attachments ?? [];
|
||||
const uploadInput = {
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
attachments,
|
||||
serverConfig: questionServerConfigs.get(selectedThreadShell.environmentId) ?? null,
|
||||
states: uploadStates,
|
||||
};
|
||||
return [
|
||||
question.id,
|
||||
{
|
||||
...userInputDraftsByRequestKey[
|
||||
scopedRequestKey(
|
||||
selectedThreadShell.environmentId,
|
||||
activePendingUserInput.requestId,
|
||||
)
|
||||
]?.[question.id],
|
||||
attachmentCount: attachments.length,
|
||||
attachmentsBlocked:
|
||||
(attachments.length > 0 &&
|
||||
questionServerConfigs.get(selectedThreadShell.environmentId)?.environment
|
||||
.capabilities.questionAttachments !== true) ||
|
||||
(preparationCounts[key] ?? 0) > 0 ||
|
||||
composerAttachmentsStillUploading(uploadInput) ||
|
||||
composerAttachmentUploadBlockReason({
|
||||
...uploadInput,
|
||||
connected: true,
|
||||
}) !== null,
|
||||
},
|
||||
];
|
||||
}),
|
||||
)
|
||||
: {};
|
||||
const activePendingUserInputAnswers = activePendingUserInput
|
||||
? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
|
||||
@@ -154,6 +238,52 @@ export function useSelectedThreadRequests() {
|
||||
return;
|
||||
}
|
||||
|
||||
const responseKey = questionAttachmentDraftKey(
|
||||
selectedThreadShell.environmentId,
|
||||
selectedThreadShell.id,
|
||||
activePendingUserInput.requestId,
|
||||
"",
|
||||
);
|
||||
if (userInputResponsesInFlight.current.has(responseKey)) return;
|
||||
const attachmentsByQuestionId = new Map<
|
||||
string,
|
||||
import("@t3tools/contracts").UserInputAttachments[string]
|
||||
>();
|
||||
for (const question of activePendingUserInput.questions) {
|
||||
const key = questionAttachmentDraftKey(
|
||||
selectedThreadShell.environmentId,
|
||||
selectedThreadShell.id,
|
||||
activePendingUserInput.requestId,
|
||||
question.id,
|
||||
);
|
||||
if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0) return;
|
||||
const attachments = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments ?? [];
|
||||
if (attachments.length === 0) continue;
|
||||
if (
|
||||
attachments.some(
|
||||
(attachment) =>
|
||||
!attachment.uploadedAttachmentId ||
|
||||
attachment.uploadEnvironmentId !== selectedThreadShell.environmentId,
|
||||
)
|
||||
) {
|
||||
Alert.alert(
|
||||
"Attachments are not ready",
|
||||
"Wait for uploads to finish, or retry failed uploads.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
attachmentsByQuestionId.set(
|
||||
question.id,
|
||||
attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.uploadedAttachmentId!,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
);
|
||||
}
|
||||
userInputResponsesInFlight.current.add(responseKey);
|
||||
setRespondingUserInputId(activePendingUserInput.requestId);
|
||||
const result = await respondToUserInput({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
@@ -161,8 +291,12 @@ export function useSelectedThreadRequests() {
|
||||
threadId: selectedThreadShell.id,
|
||||
requestId: activePendingUserInput.requestId,
|
||||
answers: activePendingUserInputAnswers,
|
||||
...(attachmentsByQuestionId.size > 0
|
||||
? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
userInputResponsesInFlight.current.delete(responseKey);
|
||||
setRespondingUserInputId((current) =>
|
||||
current === activePendingUserInput.requestId ? null : current,
|
||||
);
|
||||
|
||||
@@ -215,6 +215,7 @@ export const make = Effect.gen(function* () {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
attachmentUploads: true,
|
||||
questionAttachments: true,
|
||||
fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES },
|
||||
pullRequests: true,
|
||||
threadSettlement: true,
|
||||
|
||||
@@ -239,6 +239,17 @@ describe("OrchestrationEngine", () => {
|
||||
threadId,
|
||||
requestId,
|
||||
answers: { "0": "pnpm", "1": "Example" },
|
||||
attachmentsByQuestionId: {
|
||||
"1": [
|
||||
{
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:02.000Z",
|
||||
};
|
||||
await expect(
|
||||
@@ -256,8 +267,9 @@ describe("OrchestrationEngine", () => {
|
||||
(message) => message.role === "user",
|
||||
);
|
||||
expect(userMessages).toHaveLength(1);
|
||||
expect(userMessages?.[0]?.attachments).toEqual(response.attachmentsByQuestionId["1"]);
|
||||
expect(userMessages?.[0]?.text).toBe(
|
||||
"Which package manager?\npnpm\n\nWhat should it be named?\nExample",
|
||||
"Which package manager?\npnpm\n\nWhat should it be named?\nExample\nAttached file: spec.txt (thread-1-00000000-0000-4000-8000-0000000000aa-txt)",
|
||||
);
|
||||
expect(
|
||||
after.threads[0]?.activities.find((activity) => activity.kind === "user-input.resolved")
|
||||
|
||||
@@ -411,7 +411,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
FROM projection_state
|
||||
ORDER BY projector ASC
|
||||
`;
|
||||
assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length);
|
||||
assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length + 1);
|
||||
for (const row of stateRows) {
|
||||
assert.equal(row.lastAppliedSequence, 3);
|
||||
}
|
||||
@@ -1164,14 +1164,18 @@ it.layer(
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
yield* projectionPipeline.bootstrap;
|
||||
assert.deepEqual(
|
||||
yield* projectionState.listAll(),
|
||||
cursorsBeforeFailure.map((cursor) => ({
|
||||
assert.deepEqual(yield* projectionState.listAll(), [
|
||||
{
|
||||
projector: "projection.attachment-cleanup",
|
||||
lastAppliedSequence: pendingEvent.sequence,
|
||||
updatedAt: pendingEvent.occurredAt,
|
||||
},
|
||||
...cursorsBeforeFailure.map((cursor) => ({
|
||||
...cursor,
|
||||
lastAppliedSequence: pendingEvent.sequence,
|
||||
updatedAt: pendingEvent.occurredAt,
|
||||
})),
|
||||
);
|
||||
]);
|
||||
const replayedMessages = yield* sql<{ readonly text: string }>`
|
||||
SELECT text FROM projection_thread_messages WHERE message_id = 'message-rollback'
|
||||
`;
|
||||
@@ -1364,10 +1368,53 @@ it.layer(
|
||||
},
|
||||
});
|
||||
|
||||
const answerKeepId = "thread-revert-files-00000000-0000-4000-8000-000000000006-txt";
|
||||
const answerRemoveId = "thread-revert-files-00000000-0000-4000-8000-000000000007-txt";
|
||||
for (const [id, turnId] of [
|
||||
[answerKeepId, "turn-keep"],
|
||||
[answerRemoveId, "turn-remove"],
|
||||
] as const) {
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make(`answer-${id}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make(`answer-${id}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`answer-${id}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
id: EventId.make(`answer-${id}`),
|
||||
kind: "user-input.answer-submitted",
|
||||
tone: "info",
|
||||
summary: "Answer with file",
|
||||
createdAt: now,
|
||||
turnId: TurnId.make(turnId),
|
||||
payload: {
|
||||
requestId: ApprovalRequestId.make(id),
|
||||
answers: { q: "See file" },
|
||||
attachmentsByQuestionId: {
|
||||
q: [
|
||||
{ type: "file", id, name: "answer.txt", mimeType: "text/plain", sizeBytes: 6 },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.png`);
|
||||
const keepFilePath = path.join(attachmentsDir, `${keepFileAttachmentId}.pdf`);
|
||||
const removePath = path.join(attachmentsDir, `${removeAttachmentId}.png`);
|
||||
yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(path.join(attachmentsDir, `${answerKeepId}.txt`), "answer");
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(attachmentsDir, `${answerRemoveId}.txt`),
|
||||
"answer",
|
||||
);
|
||||
yield* fileSystem.writeFileString(keepPath, "keep");
|
||||
yield* fileSystem.writeFileString(keepFilePath, "keep");
|
||||
yield* fileSystem.writeFileString(removePath, "remove");
|
||||
@@ -1460,9 +1507,33 @@ it.layer(
|
||||
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isTrue(yield* exists(keepFilePath));
|
||||
assert.isTrue(yield* exists(path.join(attachmentsDir, `${answerKeepId}.txt`)));
|
||||
assert.isFalse(yield* exists(path.join(attachmentsDir, `${answerRemoveId}.txt`)));
|
||||
assert.isFalse(yield* exists(removePath));
|
||||
assert.isTrue(yield* exists(laterPath));
|
||||
assert.isTrue(yield* exists(otherThreadPath));
|
||||
|
||||
// Replay message and activity history from different cursors, as during a projection rebuild.
|
||||
yield* sql`DELETE FROM projection_thread_messages WHERE thread_id = ${threadId}`;
|
||||
yield* sql`DELETE FROM projection_thread_activities WHERE thread_id = ${threadId}`;
|
||||
yield* sql`UPDATE projection_state SET last_applied_sequence = 0
|
||||
WHERE projector IN ('projection.thread-messages', 'projection.thread-activities', 'projection.threads')`;
|
||||
yield* fileSystem.writeFileString(removePath, "remove");
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(attachmentsDir, `${answerRemoveId}.txt`),
|
||||
"answer",
|
||||
);
|
||||
yield* sql`CREATE TRIGGER fail_bootstrap_thread BEFORE UPDATE ON projection_threads
|
||||
BEGIN SELECT RAISE(FAIL, 'forced bootstrap failure'); END`;
|
||||
yield* projectionPipeline.bootstrap.pipe(Effect.flip);
|
||||
assert.isTrue(yield* exists(removePath));
|
||||
yield* sql`DROP TRIGGER fail_bootstrap_thread`;
|
||||
yield* projectionPipeline.bootstrap;
|
||||
assert.isTrue(yield* exists(keepPath));
|
||||
assert.isTrue(yield* exists(laterPath));
|
||||
assert.isTrue(yield* exists(path.join(attachmentsDir, `${answerKeepId}.txt`)));
|
||||
assert.isFalse(yield* exists(removePath));
|
||||
assert.isFalse(yield* exists(path.join(attachmentsDir, `${answerRemoveId}.txt`)));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1934,6 +2005,15 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
},
|
||||
});
|
||||
|
||||
yield* sql`CREATE TRIGGER fail_later_stream_projector BEFORE UPDATE ON projection_state
|
||||
WHEN NEW.projector = 'projection.threads'
|
||||
BEGIN SELECT RAISE(FAIL, 'forced later projector failure'); END`;
|
||||
yield* projectionPipeline.bootstrap.pipe(Effect.flip);
|
||||
const committedMessage = yield* sql<{ readonly text: string }>`
|
||||
SELECT text FROM projection_thread_messages WHERE message_id = 'message-a'
|
||||
`;
|
||||
assert.deepEqual(committedMessage, [{ text: "hello world" }]);
|
||||
yield* sql`DROP TRIGGER fail_later_stream_projector`;
|
||||
yield* projectionPipeline.bootstrap;
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
@@ -3884,7 +3964,7 @@ const engineLayer = it.layer(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(ThreadBackgroundLiveness.layer),
|
||||
Layer.provide(ThreadPlanProgress.layer),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolver.layer),
|
||||
@@ -4236,7 +4316,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
yield* readCursors,
|
||||
cursorsBeforeFailure.map((cursor) => ({
|
||||
...cursor,
|
||||
lastAppliedSequence: result.sequence,
|
||||
lastAppliedSequence:
|
||||
cursor.projector === "projection.attachment-cleanup"
|
||||
? cursor.lastAppliedSequence
|
||||
: result.sequence,
|
||||
})),
|
||||
);
|
||||
assert.isFalse(yield* exists(attachmentPath));
|
||||
@@ -4266,6 +4349,25 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
WHERE command_id = ${cleanupFailureCommandId}
|
||||
`;
|
||||
assert.deepEqual(cleanupFailureReceipts, [{ status: "accepted" }]);
|
||||
|
||||
const pipeline = yield* OrchestrationProjectionPipeline;
|
||||
const cleanupCursor = sql<{ readonly lastAppliedSequence: number }>`
|
||||
SELECT last_applied_sequence AS "lastAppliedSequence" FROM projection_state
|
||||
WHERE projector = 'projection.attachment-cleanup'
|
||||
`;
|
||||
const cursorBeforeRetry = yield* cleanupCursor;
|
||||
yield* pipeline.bootstrap;
|
||||
assert.deepEqual(yield* cleanupCursor, cursorBeforeRetry);
|
||||
assert.isTrue(yield* exists(blockedAttachmentPath));
|
||||
|
||||
yield* fileSystem.remove(blockedAttachmentPath, { recursive: true });
|
||||
yield* fileSystem.writeFileString(blockedAttachmentPath, "retry this attachment");
|
||||
yield* pipeline.bootstrap;
|
||||
assert.isFalse(yield* exists(blockedAttachmentPath));
|
||||
assert.isAbove(
|
||||
(yield* cleanupCursor)[0]!.lastAppliedSequence,
|
||||
cursorBeforeRetry[0]!.lastAppliedSequence,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
isImportedAgentSessionMessageId,
|
||||
UserInputAttachmentAnswerPayload,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
@@ -12,6 +13,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
@@ -327,6 +329,8 @@ function retainProjectionProposedPlansAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
const decodeQuestionAttachmentAnswer = Schema.decodeUnknownOption(UserInputAttachmentAnswerPayload);
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -359,9 +363,9 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
|
||||
const path = yield* Effect.service(Path.Path);
|
||||
|
||||
const attachmentsRootDir = serverConfig.attachmentsDir;
|
||||
const readAttachmentRootEntries = fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
||||
const readAttachmentRootEntries = fileSystem.readDirectory(attachmentsRootDir, {
|
||||
recursive: false,
|
||||
});
|
||||
|
||||
const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
|
||||
function* (threadSegment: string, entry: string) {
|
||||
@@ -423,7 +427,7 @@ const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function*
|
||||
}
|
||||
|
||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||
const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));
|
||||
const fileInfo = yield* fileSystem.stat(absolutePath);
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
@@ -1156,7 +1160,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadActivitiesProjection",
|
||||
)(function* (event, _attachmentSideEffects) {
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
yield* projectionThreadActivityRepository.deleteByThreadId({
|
||||
@@ -1204,6 +1208,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
attachmentSideEffects.prunedThreadRelativePaths.set(event.payload.threadId, new Set());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1866,10 +1871,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
const messages = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
threadId: ThreadId.make(threadId),
|
||||
});
|
||||
prunedThreadRelativePaths.set(
|
||||
threadId,
|
||||
collectThreadAttachmentRelativePaths(threadId, messages),
|
||||
);
|
||||
const retainedPaths = collectThreadAttachmentRelativePaths(threadId, messages);
|
||||
const activities = yield* projectionThreadActivityRepository.listByThreadId({
|
||||
threadId: ThreadId.make(threadId),
|
||||
});
|
||||
for (const activity of activities) {
|
||||
if (activity.kind !== "user-input.answer-submitted") continue;
|
||||
const payload = decodeQuestionAttachmentAnswer(activity.payload);
|
||||
if (Option.isNone(payload)) continue;
|
||||
for (const attachment of Object.values(payload.value.attachmentsByQuestionId).flat()) {
|
||||
const relativePath = attachmentRelativePath(attachment);
|
||||
if (relativePath) retainedPaths.add(relativePath);
|
||||
}
|
||||
}
|
||||
prunedThreadRelativePaths.set(threadId, retainedPaths);
|
||||
}
|
||||
|
||||
yield* runAttachmentSideEffects({ deletedThreadIds, prunedThreadRelativePaths });
|
||||
@@ -1879,29 +1894,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
(effect, event) =>
|
||||
effect.pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||
sequence: event.sequence,
|
||||
eventType: event.type,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(Effect.as(false)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const applyProjectorForEvent = Effect.fn("applyProjectorForEvent")(function* (
|
||||
projector: ProjectorDefinition,
|
||||
event: OrchestrationEvent,
|
||||
attachmentSideEffects: AttachmentSideEffects,
|
||||
) {
|
||||
yield* projector.apply(event, attachmentSideEffects);
|
||||
yield* projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
});
|
||||
|
||||
const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
|
||||
projector: ProjectorDefinition,
|
||||
event: OrchestrationEvent,
|
||||
@@ -1911,8 +1914,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
};
|
||||
|
||||
yield* sql.withTransaction(applyProjectorForEvent(projector, event, attachmentSideEffects));
|
||||
yield* applyAttachmentSideEffects(event, attachmentSideEffects);
|
||||
yield* sql.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
yield* projector.apply(event, attachmentSideEffects);
|
||||
yield* projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
@@ -1958,7 +1969,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
);
|
||||
// Return the cleanup effect so the caller runs it after the outer transaction commits.
|
||||
// @effect-diagnostics-next-line returnEffectInGen:off
|
||||
return applyAttachmentSideEffects(event, attachmentSideEffects);
|
||||
return applyAttachmentSideEffects(event, attachmentSideEffects).pipe(Effect.asVoid);
|
||||
},
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
@@ -1975,11 +1986,58 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* cleanup;
|
||||
});
|
||||
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.gen(function* () {
|
||||
const cleanupProjector = "projection.attachment-cleanup";
|
||||
const states = yield* projectionStateRepository.listAll();
|
||||
const byProjector = new Map(states.map((state) => [state.projector, state]));
|
||||
const cleanupState = byProjector.get(cleanupProjector);
|
||||
const cleanupStart = Math.min(
|
||||
cleanupState?.lastAppliedSequence ?? 0,
|
||||
...projectors.map((projector) => byProjector.get(projector.name)?.lastAppliedSequence ?? 0),
|
||||
);
|
||||
// Persist this boundary before replay: a reset projector can encounter an old
|
||||
// revert, then fail after other projectors have committed past that event.
|
||||
yield* projectionStateRepository.upsert({
|
||||
projector: cleanupProjector,
|
||||
lastAppliedSequence: cleanupStart,
|
||||
updatedAt: cleanupState?.updatedAt ?? "1970-01-01T00:00:00.000Z",
|
||||
});
|
||||
yield* Effect.forEach(projectors, bootstrapProjector, { concurrency: 1, discard: true });
|
||||
|
||||
// Cleanup has its own cursor so retries never have to replay committed text.
|
||||
// All message and activity references are current before any files are removed.
|
||||
const pendingCleanup = new Map<string, OrchestrationEvent>();
|
||||
let lastEvent: OrchestrationEvent | undefined;
|
||||
yield* Stream.runForEach(
|
||||
eventStore.readFromSequence(cleanupStart, Number.MAX_SAFE_INTEGER),
|
||||
(event) =>
|
||||
Effect.sync(() => {
|
||||
lastEvent = event;
|
||||
if (event.type === "thread.reverted" || event.type === "thread.deleted") {
|
||||
pendingCleanup.set(`${event.type}:${event.payload.threadId}`, event);
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const event of pendingCleanup.values()) {
|
||||
if (event.type !== "thread.reverted" && event.type !== "thread.deleted") continue;
|
||||
const threadId = event.payload.threadId;
|
||||
const cleaned = yield* applyAttachmentSideEffects(event, {
|
||||
deletedThreadIds: new Set(event.type === "thread.deleted" ? [threadId] : []),
|
||||
prunedThreadRelativePaths: new Map(
|
||||
event.type === "thread.reverted" ? [[threadId, new Set<string>()]] : [],
|
||||
),
|
||||
});
|
||||
// Leave the cleanup cursor behind this event so the next bootstrap retries it.
|
||||
if (!cleaned) return;
|
||||
}
|
||||
if (lastEvent) {
|
||||
yield* projectionStateRepository.upsert({
|
||||
projector: cleanupProjector,
|
||||
lastAppliedSequence: lastEvent.sequence,
|
||||
updatedAt: lastEvent.occurredAt,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
|
||||
@@ -1609,6 +1609,9 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
requestId: event.payload.requestId,
|
||||
answers: event.payload.answers,
|
||||
...(event.payload.attachmentsByQuestionId
|
||||
? { attachmentsByQuestionId: event.payload.attachmentsByQuestionId }
|
||||
: {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
|
||||
@@ -5,13 +5,15 @@ import * as NodePath from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
ApprovalRequestId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
@@ -23,6 +25,7 @@ const testLayer = Layer.mergeAll(
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
const attachmentUuid = "00000000-0000-4000-8000-0000000000aa";
|
||||
const isClientCommand = Schema.is(ClientOrchestrationCommand);
|
||||
|
||||
function turnStartCommand(input: {
|
||||
readonly threadId?: string;
|
||||
@@ -358,3 +361,201 @@ describe("normalizeDispatchCommand attachments", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("question attachments", () => {
|
||||
it.effect("enforces the total response limit and claims duplicate filenames independently", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const id = `pending-${attachmentUuid}-txt`;
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.txt`), "report");
|
||||
const attachment = {
|
||||
type: "file" as const,
|
||||
id,
|
||||
name: 'notes "final" ü.txt',
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 6,
|
||||
};
|
||||
const command: ClientOrchestrationCommand = {
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make("answer-cap"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: ApprovalRequestId.make("request-cap"),
|
||||
answers: { first: "", second: "" },
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
attachmentsByQuestionId: {
|
||||
first: Array.from({ length: 4 }, () => attachment),
|
||||
second: Array.from({ length: 5 }, () => attachment),
|
||||
},
|
||||
};
|
||||
const failure = yield* normalizeDispatchCommand(command).pipe(Effect.flip);
|
||||
expect(failure.message).toContain("up to 8");
|
||||
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
|
||||
const accepted = {
|
||||
...command,
|
||||
attachmentsByQuestionId: {
|
||||
...command.attachmentsByQuestionId,
|
||||
second: Array.from({ length: 4 }, () => attachment),
|
||||
},
|
||||
};
|
||||
const normalized = yield* normalizeDispatchCommand(accepted);
|
||||
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
|
||||
const attachments = Object.values(normalized.attachmentsByQuestionId!).flat();
|
||||
expect(attachments).toHaveLength(8);
|
||||
expect(new Set(attachments.map((item) => item.id)).size).toBe(8);
|
||||
for (const item of attachments) {
|
||||
expect(item.name).toBe(attachment.name);
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${item.id}.txt`), "utf8"),
|
||||
).toBe("report");
|
||||
}
|
||||
yield* cleanupFailedUploadedAttachments(accepted, normalized);
|
||||
expect(NodeFS.readdirSync(config.attachmentsDir)).toEqual([`${id}.txt`]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
it("requires uploaded metadata for question images, including pasted images", () => {
|
||||
expect(
|
||||
isClientCommand({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: "answer",
|
||||
threadId: "thread-1",
|
||||
requestId: "request",
|
||||
answers: { q: "" },
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
attachmentsByQuestionId: {
|
||||
q: [
|
||||
{
|
||||
type: "image",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 6,
|
||||
dataUrl: "data:image/png;base64,cGl4ZWxz",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.effect("preserves a __proto__ question key and cleans up its claimed files", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const id = `pending-${attachmentUuid}`;
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
|
||||
const command: ClientOrchestrationCommand = {
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make("answer"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: ApprovalRequestId.make("request"),
|
||||
answers: { ["__proto__"]: "" },
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
attachmentsByQuestionId: {
|
||||
["__proto__"]: [
|
||||
{ type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 },
|
||||
],
|
||||
},
|
||||
};
|
||||
const normalized = yield* normalizeDispatchCommand(command);
|
||||
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
|
||||
expect(Object.keys(normalized.attachmentsByQuestionId!)).toEqual(["__proto__"]);
|
||||
const attachment = normalized.attachmentsByQuestionId!["__proto__"]![0]!;
|
||||
const claimedPath = NodePath.join(config.attachmentsDir, `${attachment.id}.png`);
|
||||
expect(NodeFS.existsSync(claimedPath)).toBe(true);
|
||||
yield* cleanupFailedUploadedAttachments(command, normalized);
|
||||
expect(NodeFS.existsSync(claimedPath)).toBe(false);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
it.effect(
|
||||
"claims images and files by question, preserves answers, and cleans up failed dispatches",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const imageId = `pending-${attachmentUuid}`;
|
||||
const fileId = `pending-${attachmentUuid}-txt`;
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${imageId}.png`), "pixels");
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${fileId}.txt`), "report");
|
||||
const command: ClientOrchestrationCommand = {
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make("answer"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: ApprovalRequestId.make("request"),
|
||||
answers: { q1: ["Selected option"], q2: "" },
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
attachmentsByQuestionId: {
|
||||
q1: [
|
||||
{
|
||||
type: "image",
|
||||
id: imageId,
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 6,
|
||||
},
|
||||
],
|
||||
q2: [
|
||||
{
|
||||
type: "file",
|
||||
id: fileId,
|
||||
name: "report.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 6,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const normalized = yield* normalizeDispatchCommand(command);
|
||||
if (normalized.type !== "thread.user-input.respond") throw new Error("Wrong command");
|
||||
expect(normalized.answers).toEqual(command.answers);
|
||||
const image = normalized.attachmentsByQuestionId!.q1![0]!;
|
||||
const file = normalized.attachmentsByQuestionId!.q2![0]!;
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${image.id}.png`), "utf8"),
|
||||
).toBe("pixels");
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`), "utf8"),
|
||||
).toBe("report");
|
||||
yield* cleanupFailedUploadedAttachments(command, normalized);
|
||||
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${image.id}.png`))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${file.id}.txt`))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${imageId}.png`))).toBe(
|
||||
true,
|
||||
);
|
||||
const retry = yield* normalizeDispatchCommand(command);
|
||||
expect(retry.type).toBe("thread.user-input.respond");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("removes all claimed copies if a later question upload is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const id = `pending-${attachmentUuid}`;
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${id}.png`), "pixels");
|
||||
const result = yield* normalizeDispatchCommand({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.make("answer"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: ApprovalRequestId.make("request"),
|
||||
answers: { q1: "", q2: "" },
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
attachmentsByQuestionId: {
|
||||
q1: [{ type: "image", id, name: "image.png", mimeType: "image/png", sizeBytes: 6 }],
|
||||
q2: [
|
||||
{
|
||||
type: "file",
|
||||
id: `${id}-txt`,
|
||||
name: "missing.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 6,
|
||||
},
|
||||
],
|
||||
},
|
||||
}).pipe(Effect.result);
|
||||
expect(result._tag).toBe("Failure");
|
||||
expect(
|
||||
NodeFS.readdirSync(config.attachmentsDir).filter((name) => name.startsWith("thread-1-")),
|
||||
).toEqual([]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -4,6 +4,8 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type UserInputAttachments,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
type IsoDateTime,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
@@ -129,13 +131,28 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (canonicalCommand.type !== "thread.turn.start") {
|
||||
if (
|
||||
canonicalCommand.type !== "thread.turn.start" &&
|
||||
canonicalCommand.type !== "thread.user-input.respond"
|
||||
) {
|
||||
return canonicalCommand as OrchestrationCommand;
|
||||
}
|
||||
|
||||
const attachments =
|
||||
canonicalCommand.type === "thread.turn.start"
|
||||
? canonicalCommand.message.attachments
|
||||
: Object.values(canonicalCommand.attachmentsByQuestionId ?? {}).flat();
|
||||
if (
|
||||
canonicalCommand.type === "thread.user-input.respond" &&
|
||||
attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS
|
||||
) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per question response.`,
|
||||
});
|
||||
}
|
||||
const claimedAttachmentPaths: string[] = [];
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
canonicalCommand.message.attachments,
|
||||
attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
if (!("dataUrl" in attachment)) {
|
||||
@@ -260,6 +277,25 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.tapError(() => removeClaimedAttachmentPaths(claimedAttachmentPaths)));
|
||||
|
||||
if (canonicalCommand.type === "thread.user-input.respond") {
|
||||
let index = 0;
|
||||
const attachmentsByQuestionId = Object.fromEntries(
|
||||
Object.entries(canonicalCommand.attachmentsByQuestionId ?? {}).map(
|
||||
([questionId, original]) => {
|
||||
const claimed = normalizedAttachments.slice(
|
||||
index,
|
||||
index + original.length,
|
||||
) as UserInputAttachments[string];
|
||||
index += original.length;
|
||||
return [questionId, claimed];
|
||||
},
|
||||
),
|
||||
);
|
||||
return {
|
||||
...canonicalCommand,
|
||||
...(attachments.length > 0 ? { attachmentsByQuestionId } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...canonicalCommand,
|
||||
message: {
|
||||
@@ -272,14 +308,24 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
export const cleanupFailedUploadedAttachments = Effect.fn(
|
||||
"Normalizer.cleanupFailedUploadedAttachments",
|
||||
)(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {
|
||||
if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {
|
||||
return;
|
||||
}
|
||||
const originalAttachments =
|
||||
command.type === "thread.turn.start"
|
||||
? command.message.attachments
|
||||
: command.type === "thread.user-input.respond"
|
||||
? Object.values(command.attachmentsByQuestionId ?? {}).flat()
|
||||
: [];
|
||||
const normalizedAttachments =
|
||||
normalizedCommand.type === "thread.turn.start"
|
||||
? normalizedCommand.message.attachments
|
||||
: normalizedCommand.type === "thread.user-input.respond"
|
||||
? Object.values(normalizedCommand.attachmentsByQuestionId ?? {}).flat()
|
||||
: [];
|
||||
if (normalizedAttachments.length === 0) return;
|
||||
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const claimedPaths: string[] = [];
|
||||
for (const [index, attachment] of normalizedCommand.message.attachments.entries()) {
|
||||
const original = command.message.attachments[index];
|
||||
for (const [index, attachment] of normalizedAttachments.entries()) {
|
||||
const original = originalAttachments[index];
|
||||
if (
|
||||
!original ||
|
||||
"dataUrl" in original ||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
CommandId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const UPDATED_AT = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const readModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Manual title",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: UPDATED_AT,
|
||||
updatedAt: UPDATED_AT,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: UPDATED_AT,
|
||||
};
|
||||
|
||||
const requestId = ApprovalRequestId.make("question-request");
|
||||
const command = {
|
||||
type: "thread.user-input.respond" as const,
|
||||
commandId: CommandId.make("answer"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId,
|
||||
answers: { q: "" },
|
||||
createdAt: UPDATED_AT,
|
||||
attachmentsByQuestionId: {
|
||||
q: [
|
||||
{
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const request = {
|
||||
id: EventId.make("question"),
|
||||
kind: "user-input.requested",
|
||||
summary: "Question",
|
||||
tone: "info" as const,
|
||||
turnId: null,
|
||||
createdAt: UPDATED_AT,
|
||||
payload: {
|
||||
requestId,
|
||||
questions: [
|
||||
{ id: "q", header: "Spec", question: "Provide a spec", options: [], allowCustomAnswer: true },
|
||||
],
|
||||
},
|
||||
};
|
||||
it.layer(NodeServices.layer)("question attachment answers", (it) => {
|
||||
it.effect("persists the original answer with its attachment and emits a provider response", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
readModel,
|
||||
command,
|
||||
userInputActivity: request,
|
||||
});
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"thread.activity-appended",
|
||||
"thread.user-input-response-requested",
|
||||
]);
|
||||
expect(events[0]?.payload).toMatchObject({
|
||||
activity: {
|
||||
kind: "user-input.answer-submitted",
|
||||
payload: { answers: { q: "" }, attachmentsByQuestionId: command.attachmentsByQuestionId },
|
||||
},
|
||||
});
|
||||
expect(events[1]?.payload).toMatchObject({
|
||||
answers: { q: "" },
|
||||
attachmentsByQuestionId: command.attachmentsByQuestionId,
|
||||
});
|
||||
}),
|
||||
);
|
||||
it.effect("rejects attachments for a resolved or unknown request", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* decideOrchestrationCommand({ readModel, command }).pipe(Effect.result);
|
||||
expect(result._tag).toBe("Failure");
|
||||
}),
|
||||
);
|
||||
it.effect("rejects unknown question IDs and predefined-choice-only protocols", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const question of [
|
||||
{ ...request.payload.questions[0], id: "other" },
|
||||
{ ...request.payload.questions[0], allowCustomAnswer: false },
|
||||
]) {
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
readModel,
|
||||
command,
|
||||
userInputActivity: { ...request, payload: { ...request.payload, questions: [question] } },
|
||||
}).pipe(Effect.result);
|
||||
expect(result._tag).toBe("Failure");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1222,6 +1222,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const request = userInputActivity;
|
||||
const attachments = Object.values(command.attachmentsByQuestionId ?? {}).flat();
|
||||
let questionTextById: Record<string, string> = {};
|
||||
if (attachments.length > 0) {
|
||||
const payload =
|
||||
request?.kind === "user-input.requested"
|
||||
? decodeUserInputRequestedPayload(request.payload)
|
||||
: Option.none();
|
||||
if (Option.isNone(payload)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail:
|
||||
request?.kind === "user-input.resolved"
|
||||
? "This question has already been answered."
|
||||
: "This question is no longer pending.",
|
||||
});
|
||||
}
|
||||
questionTextById = Object.fromEntries(
|
||||
payload.value.questions.map((question) => [question.id, question.question]),
|
||||
);
|
||||
for (const questionId of Object.keys(command.attachmentsByQuestionId ?? {})) {
|
||||
const question = payload.value.questions.find((question) => question.id === questionId);
|
||||
if (!question || question.allowCustomAnswer === false) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: "This question does not accept file references.",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
request &&
|
||||
Predicate.isObject(request.payload) &&
|
||||
@@ -1237,13 +1266,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
const replies: string[] = [];
|
||||
for (const question of payload.value.questions) {
|
||||
const answer = command.answers[question.id];
|
||||
if (typeof answer !== "string" || answer.trim().length === 0) {
|
||||
if (
|
||||
typeof answer !== "string" ||
|
||||
(answer.trim().length === 0 && !command.attachmentsByQuestionId?.[question.id]?.length)
|
||||
) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: "Answer each question before sending.",
|
||||
});
|
||||
}
|
||||
replies.push(`${question.question}\n${answer.trim()}`);
|
||||
const questionAttachments = command.attachmentsByQuestionId?.[question.id] ?? [];
|
||||
const attachmentLabels = questionAttachments
|
||||
.map((attachment) => `Attached file: ${attachment.name} (${attachment.id})`)
|
||||
.join("\n");
|
||||
replies.push(
|
||||
[`${question.question}\n${answer.trim()}`, attachmentLabels].filter(Boolean).join("\n"),
|
||||
);
|
||||
}
|
||||
// Commit the answer and its message together. The normal turn path
|
||||
// steers a running agent or resumes an idle session.
|
||||
@@ -1266,6 +1304,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
requestId: command.requestId,
|
||||
responseMode: "message",
|
||||
answers: command.answers,
|
||||
...(command.attachmentsByQuestionId
|
||||
? { attachmentsByQuestionId: command.attachmentsByQuestionId }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1280,30 +1321,57 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
messageId: MessageId.make(`async-answer:${command.requestId}`),
|
||||
role: "user",
|
||||
text: replies.join("\n\n"),
|
||||
attachments: [],
|
||||
attachments,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
return {
|
||||
const responseEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
metadata: { requestId: command.requestId },
|
||||
})),
|
||||
type: "thread.user-input-response-requested",
|
||||
type: "thread.user-input-response-requested" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
requestId: command.requestId,
|
||||
answers: command.answers,
|
||||
...(command.attachmentsByQuestionId
|
||||
? { attachmentsByQuestionId: command.attachmentsByQuestionId }
|
||||
: {}),
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
if (attachments.length === 0) return responseEvent;
|
||||
const historyEvent = yield* decideOrchestrationCommand({
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.activity.append",
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
createdAt: command.createdAt,
|
||||
activity: {
|
||||
id: EventId.make(`question-answer:${command.commandId}`),
|
||||
kind: "user-input.answer-submitted",
|
||||
summary: "Question answer submitted",
|
||||
tone: "info",
|
||||
turnId: request?.turnId ?? null,
|
||||
createdAt: command.createdAt,
|
||||
payload: {
|
||||
requestId: command.requestId,
|
||||
answers: command.answers,
|
||||
questionTextById,
|
||||
attachmentsByQuestionId: command.attachmentsByQuestionId,
|
||||
detail: attachments.map((attachment) => attachment.name).join("\n"),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return [...(Array.isArray(historyEvent) ? historyEvent : [historyEvent]), responseEvent];
|
||||
}
|
||||
|
||||
case "thread.user-input.dismiss": {
|
||||
|
||||
@@ -49,6 +49,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { appendUserInputAttachmentPaths } from "../userInputAttachments.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import {
|
||||
@@ -1919,7 +1920,11 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.request_id": input.requestId,
|
||||
});
|
||||
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
|
||||
const answers = yield* appendUserInputAttachmentPaths({
|
||||
...input,
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
}).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
|
||||
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, answers);
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
|
||||
|
||||
const layer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const attachment = {
|
||||
type: "file" as const,
|
||||
id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
|
||||
name: 'spec "final".txt',
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
describe("question answer paths", () => {
|
||||
it.effect("keeps selected values intact and appends an actual readable server path", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
|
||||
NodeFS.writeFileSync(path, "spec");
|
||||
const original = { q: ["First", "Second"], other: "No file" };
|
||||
const answers = yield* appendUserInputAttachmentPaths({
|
||||
answers: original,
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentsByQuestionId: { q: [attachment] },
|
||||
});
|
||||
expect(answers.q).toEqual([
|
||||
"First",
|
||||
"Second",
|
||||
`Attached file "spec \\"final\\".txt": "${path}"`,
|
||||
]);
|
||||
expect(answers.other).toBe("No file");
|
||||
expect(original.q).toEqual(["First", "Second"]);
|
||||
expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
|
||||
const specialKey = yield* appendUserInputAttachmentPaths({
|
||||
answers: {},
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentsByQuestionId: { ["__proto__"]: [attachment] },
|
||||
});
|
||||
expect(Object.keys(specialKey)).toEqual(["__proto__"]);
|
||||
expect(specialKey["__proto__"]).toContain(path);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
it.effect("does not send an unavailable attachment path", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const result = yield* appendUserInputAttachmentPaths({
|
||||
answers: { q: "" },
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentsByQuestionId: { q: [attachment] },
|
||||
}).pipe(Effect.result);
|
||||
expect(result._tag).toBe("Failure");
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { ProviderUserInputAnswers, UserInputAttachments } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import { resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { ProviderValidationError } from "./Errors.ts";
|
||||
|
||||
const quoteReference = Schema.encodeSync(Schema.fromJsonString(Schema.String));
|
||||
|
||||
/** Keep provider answer protocols unchanged; paths refer to files on the provider's server. */
|
||||
export const appendUserInputAttachmentPaths = Effect.fn("appendUserInputAttachmentPaths")(
|
||||
function* (input: {
|
||||
answers: ProviderUserInputAnswers;
|
||||
attachmentsByQuestionId?: UserInputAttachments | undefined;
|
||||
attachmentsDir: string;
|
||||
}) {
|
||||
const answers = new Map(Object.entries(input.answers));
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const [questionId, attachments] of Object.entries(input.attachmentsByQuestionId ?? {})) {
|
||||
if (attachments.length === 0) continue;
|
||||
const references: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
const path = resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment });
|
||||
if (
|
||||
!path ||
|
||||
!(yield* fs.exists(path).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderValidationError({
|
||||
operation: "respondToUserInput",
|
||||
issue: `Could not access attachment '${attachment.name}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
))
|
||||
) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "respondToUserInput",
|
||||
issue: `Attachment '${attachment.name}' is no longer available. Attach it again.`,
|
||||
});
|
||||
}
|
||||
references.push(
|
||||
`Attached ${attachment.type} ${quoteReference(attachment.name)}: ${quoteReference(path)}`,
|
||||
);
|
||||
}
|
||||
const answer = answers.get(questionId);
|
||||
const text = references.join("\n");
|
||||
answers.set(
|
||||
questionId,
|
||||
Array.isArray(answer)
|
||||
? [...answer, text]
|
||||
: typeof answer === "string" && answer.length > 0
|
||||
? `${answer}\n\n${text}`
|
||||
: text,
|
||||
);
|
||||
}
|
||||
return Object.fromEntries(answers);
|
||||
},
|
||||
);
|
||||
@@ -8,6 +8,13 @@ import {
|
||||
import { feedbackBannerItem } from "./chat/ComposerFeedback";
|
||||
import { usageLimitsBannerItem } from "./chat/ComposerUsageLimits";
|
||||
import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
|
||||
import {
|
||||
questionAttachmentDraftId,
|
||||
questionAttachmentDraftPrefix,
|
||||
clearQuestionAttachmentDraft,
|
||||
useQuestionAttachmentPreparation,
|
||||
} from "../questionAttachments";
|
||||
import { useAttachmentUploadStore } from "../lib/attachmentUploadQueue";
|
||||
import {
|
||||
type AssistantCitation,
|
||||
type ApprovalRequestId,
|
||||
@@ -264,7 +271,7 @@ import {
|
||||
finalizePromotedDraftThreadByRef,
|
||||
markPromotedDraftThreadByRef,
|
||||
useComposerDraftStore,
|
||||
type DraftId,
|
||||
DraftId,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
@@ -1610,6 +1617,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
null,
|
||||
);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const userInputResponsesInFlight = useRef(new Set<string>());
|
||||
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
|
||||
ApprovalRequestId[]
|
||||
>([]);
|
||||
@@ -2310,6 +2318,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true;
|
||||
const attachmentEnvironmentConfig = environmentById.get(environmentId)?.serverConfig ?? null;
|
||||
const attachmentUploadsCapabilityKnown = attachmentEnvironmentConfig !== null;
|
||||
const supportsQuestionAttachments =
|
||||
attachmentEnvironmentConfig?.environment.capabilities.questionAttachments === true;
|
||||
const supportsAttachmentUploads =
|
||||
attachmentEnvironmentConfig?.environment.capabilities.attachmentUploads === true;
|
||||
const advertisedFileAttachmentBytes =
|
||||
@@ -2627,16 +2637,120 @@ export default function ChatView(props: ChatViewProps) {
|
||||
[threadActivities],
|
||||
);
|
||||
const activePendingUserInput = pendingUserInputs[0] ?? null;
|
||||
const activePendingDraftAnswers = useMemo(
|
||||
const activePendingRequestKey = JSON.stringify([
|
||||
environmentId,
|
||||
activeThreadId,
|
||||
activePendingUserInput?.requestId,
|
||||
]);
|
||||
const pendingQuestionDraftKeys = useMemo(
|
||||
() =>
|
||||
activePendingUserInput
|
||||
? (pendingUserInputAnswersByRequestId[activePendingUserInput.requestId] ??
|
||||
EMPTY_PENDING_USER_INPUT_ANSWERS)
|
||||
: EMPTY_PENDING_USER_INPUT_ANSWERS,
|
||||
[activePendingUserInput, pendingUserInputAnswersByRequestId],
|
||||
activeThreadId
|
||||
? pendingUserInputs.flatMap((request) =>
|
||||
request.questions.map((question) =>
|
||||
questionAttachmentDraftId(
|
||||
environmentId,
|
||||
activeThreadId,
|
||||
request.requestId,
|
||||
question.id,
|
||||
),
|
||||
),
|
||||
)
|
||||
: [],
|
||||
[activeThreadId, environmentId, pendingUserInputs],
|
||||
);
|
||||
const questionComposerDrafts = useComposerDraftStore(
|
||||
useShallow((state) =>
|
||||
Object.fromEntries(
|
||||
pendingQuestionDraftKeys.map((key) => [key, state.draftsByThreadKey[key]]),
|
||||
),
|
||||
),
|
||||
);
|
||||
const questionUploadsBlocked = useAttachmentUploadStore(
|
||||
useShallow((state) =>
|
||||
Object.fromEntries(
|
||||
pendingQuestionDraftKeys.map((key) => {
|
||||
const draft = questionComposerDrafts[key];
|
||||
const attachments = draft ? [...draft.images, ...draft.files] : [];
|
||||
return [
|
||||
key,
|
||||
attachments.some((attachment) => {
|
||||
const upload = state.uploadsByImageId[attachment.id];
|
||||
return upload?.status !== "ready" || upload.environmentId !== environmentId;
|
||||
}),
|
||||
];
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const questionPreparations = useQuestionAttachmentPreparation(
|
||||
useShallow((state) =>
|
||||
Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),
|
||||
),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (routeThreadState.status !== "live" || routeThreadState.data._tag !== "Some") return;
|
||||
const questionThread = routeThreadState.data.value;
|
||||
const { userInputs: currentRequests } = derivePendingRequests(questionThread.activities);
|
||||
const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
|
||||
const retained = new Set(
|
||||
currentRequests.flatMap((request) =>
|
||||
request.questions.map((question) =>
|
||||
questionAttachmentDraftId(
|
||||
environmentId,
|
||||
questionThread.id,
|
||||
request.requestId,
|
||||
question.id,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const keys = new Set([
|
||||
...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
|
||||
...Object.keys(useQuestionAttachmentPreparation.getState().counts),
|
||||
]);
|
||||
for (const key of keys) {
|
||||
if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
|
||||
clearQuestionAttachmentDraft(DraftId.make(key));
|
||||
}
|
||||
}, [environmentId, routeThreadState.data, routeThreadState.status]);
|
||||
const activePendingDraftAnswers = useMemo(() => {
|
||||
if (!activePendingUserInput || !activeThreadId) return EMPTY_PENDING_USER_INPUT_ANSWERS;
|
||||
return Object.fromEntries(
|
||||
activePendingUserInput.questions.map((question) => {
|
||||
const key = questionAttachmentDraftId(
|
||||
environmentId,
|
||||
activeThreadId,
|
||||
activePendingUserInput.requestId,
|
||||
question.id,
|
||||
);
|
||||
const draft = questionComposerDrafts[key];
|
||||
const attachments = draft ? [...draft.images, ...draft.files] : [];
|
||||
return [
|
||||
question.id,
|
||||
{
|
||||
...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],
|
||||
attachmentCount: attachments.length,
|
||||
attachmentsBlocked:
|
||||
(attachments.length > 0 && !supportsQuestionAttachments) ||
|
||||
(questionPreparations[key] ?? 0) > 0 ||
|
||||
questionUploadsBlocked[key] === true,
|
||||
},
|
||||
];
|
||||
}),
|
||||
);
|
||||
}, [
|
||||
activePendingUserInput,
|
||||
activeThreadId,
|
||||
environmentId,
|
||||
questionComposerDrafts,
|
||||
questionUploadsBlocked,
|
||||
supportsQuestionAttachments,
|
||||
questionPreparations,
|
||||
pendingUserInputAnswersByRequestId,
|
||||
activePendingRequestKey,
|
||||
]);
|
||||
const activePendingQuestionIndex = activePendingUserInput
|
||||
? (pendingUserInputQuestionIndexByRequestId[activePendingUserInput.requestId] ?? 0)
|
||||
? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)
|
||||
: 0;
|
||||
const activePendingProgress = useMemo(
|
||||
() =>
|
||||
@@ -7061,8 +7175,38 @@ export default function ChatView(props: ChatViewProps) {
|
||||
|
||||
const onRespondToUserInput = useCallback(
|
||||
async (requestId: ApprovalRequestId, answers: Record<string, unknown>) => {
|
||||
if (!activeThreadId) return;
|
||||
|
||||
if (!activeThreadId || !activePendingUserInput || activePendingIsResponding) return;
|
||||
const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
|
||||
if (userInputResponsesInFlight.current.has(responseKey)) return;
|
||||
const attachmentsByQuestionId = new Map<
|
||||
string,
|
||||
import("@t3tools/contracts").UserInputAttachments[string]
|
||||
>();
|
||||
for (const question of activePendingUserInput.questions) {
|
||||
const target = questionAttachmentDraftId(
|
||||
environmentId,
|
||||
activeThreadId,
|
||||
requestId,
|
||||
question.id,
|
||||
);
|
||||
if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
|
||||
const draft = useComposerDraftStore.getState().getComposerDraft(target);
|
||||
const attachments = draft ? [...draft.images, ...draft.files] : [];
|
||||
if (attachments.length === 0) continue;
|
||||
const uploaded = getUploadedAttachments({ environmentId, images: attachments });
|
||||
if (!uploaded) {
|
||||
setThreadError(
|
||||
activeThreadId,
|
||||
"Wait for attachments to finish uploading, or remove failed uploads.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
attachmentsByQuestionId.set(
|
||||
question.id,
|
||||
uploaded as import("@t3tools/contracts").UserInputAttachments[string],
|
||||
);
|
||||
}
|
||||
userInputResponsesInFlight.current.add(responseKey);
|
||||
setRespondingUserInputRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
);
|
||||
@@ -7072,6 +7216,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadId: activeThreadId,
|
||||
requestId,
|
||||
answers,
|
||||
...(attachmentsByQuestionId.size > 0
|
||||
? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
@@ -7081,10 +7228,18 @@ export default function ChatView(props: ChatViewProps) {
|
||||
error instanceof Error ? error.message : "Failed to submit user input.",
|
||||
);
|
||||
}
|
||||
userInputResponsesInFlight.current.delete(responseKey);
|
||||
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
return result;
|
||||
},
|
||||
[activeThreadId, environmentId, respondToThreadUserInput, setThreadError],
|
||||
[
|
||||
activeThreadId,
|
||||
activePendingUserInput,
|
||||
activePendingIsResponding,
|
||||
environmentId,
|
||||
respondToThreadUserInput,
|
||||
setThreadError,
|
||||
],
|
||||
);
|
||||
|
||||
// Closes an async question without messaging the agent. The server records
|
||||
@@ -7120,10 +7275,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
setPendingUserInputQuestionIndexByRequestId((existing) => ({
|
||||
...existing,
|
||||
[activePendingUserInput.requestId]: nextQuestionIndex,
|
||||
[activePendingRequestKey]: nextQuestionIndex,
|
||||
}));
|
||||
},
|
||||
[activePendingUserInput],
|
||||
[activePendingUserInput, activePendingRequestKey],
|
||||
);
|
||||
|
||||
const onSelectActivePendingUserInputOption = useCallback(
|
||||
@@ -7143,11 +7298,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
|
||||
return {
|
||||
...existing,
|
||||
[activePendingUserInput.requestId]: {
|
||||
...existing[activePendingUserInput.requestId],
|
||||
[activePendingRequestKey]: {
|
||||
...existing[activePendingRequestKey],
|
||||
[questionId]: togglePendingUserInputOptionSelection(
|
||||
question,
|
||||
existing[activePendingUserInput.requestId]?.[questionId],
|
||||
existing[activePendingRequestKey]?.[questionId],
|
||||
optionValue,
|
||||
),
|
||||
},
|
||||
@@ -7156,7 +7311,12 @@ export default function ChatView(props: ChatViewProps) {
|
||||
promptRef.current = "";
|
||||
composerRef.current?.resetCursorState({ cursor: 0 });
|
||||
},
|
||||
[activePendingProgress?.activeQuestion, activePendingUserInput, composerRef],
|
||||
[
|
||||
activePendingProgress?.activeQuestion,
|
||||
activePendingUserInput,
|
||||
activePendingRequestKey,
|
||||
composerRef,
|
||||
],
|
||||
);
|
||||
|
||||
const onChangeActivePendingUserInputCustomAnswer = useCallback(
|
||||
@@ -7177,10 +7337,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
promptRef.current = value;
|
||||
setPendingUserInputAnswersByRequestId((existing) => ({
|
||||
...existing,
|
||||
[activePendingUserInput.requestId]: {
|
||||
...existing[activePendingUserInput.requestId],
|
||||
[activePendingRequestKey]: {
|
||||
...existing[activePendingRequestKey],
|
||||
[questionId]: setPendingUserInputCustomAnswer(
|
||||
existing[activePendingUserInput.requestId]?.[questionId],
|
||||
existing[activePendingRequestKey]?.[questionId],
|
||||
value,
|
||||
),
|
||||
},
|
||||
@@ -7194,11 +7354,16 @@ export default function ChatView(props: ChatViewProps) {
|
||||
composerRef.current?.focusAt(nextCursor);
|
||||
}
|
||||
},
|
||||
[activePendingUserInput, composerRef],
|
||||
[activePendingUserInput, activePendingRequestKey, composerRef],
|
||||
);
|
||||
|
||||
const onAdvanceActivePendingUserInput = useCallback(() => {
|
||||
if (!activePendingUserInput || !activePendingProgress) {
|
||||
if (
|
||||
!activePendingUserInput ||
|
||||
!activePendingProgress ||
|
||||
!activePendingProgress.canAdvance ||
|
||||
activePendingIsResponding
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (activePendingProgress.isLastQuestion) {
|
||||
@@ -7212,6 +7377,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
activePendingProgress,
|
||||
activePendingResolvedAnswers,
|
||||
activePendingUserInput,
|
||||
activePendingIsResponding,
|
||||
onRespondToUserInput,
|
||||
setActivePendingUserInputQuestionIndex,
|
||||
]);
|
||||
@@ -8119,6 +8285,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
environmentId={environmentId}
|
||||
attachmentUploadsCapabilityKnown={attachmentUploadsCapabilityKnown}
|
||||
supportsAttachmentUploads={supportsAttachmentUploads}
|
||||
supportsQuestionAttachments={supportsQuestionAttachments}
|
||||
maxFileAttachmentBytes={maxFileAttachmentBytes}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { RefreshIcon } from "~/components/ui/refresh-icon";
|
||||
import {
|
||||
questionAttachmentDraftId,
|
||||
useQuestionAttachmentPreparation,
|
||||
changeQuestionAttachmentPreparation,
|
||||
} from "../../questionAttachments";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
AssistantCitation,
|
||||
@@ -1227,6 +1232,7 @@ export interface ChatComposerProps {
|
||||
environmentId: EnvironmentId;
|
||||
attachmentUploadsCapabilityKnown: boolean;
|
||||
supportsAttachmentUploads: boolean;
|
||||
supportsQuestionAttachments: boolean;
|
||||
maxFileAttachmentBytes: number | null;
|
||||
routeKind: "server" | "draft";
|
||||
routeThreadRef: ScopedThreadRef;
|
||||
@@ -1376,6 +1382,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
environmentId,
|
||||
attachmentUploadsCapabilityKnown,
|
||||
supportsAttachmentUploads,
|
||||
supportsQuestionAttachments,
|
||||
maxFileAttachmentBytes,
|
||||
routeKind,
|
||||
routeThreadRef,
|
||||
@@ -1468,9 +1475,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// happened while they awaited.
|
||||
const composerDraftTargetKeyRef = useRef("");
|
||||
composerDraftTargetKeyRef.current = composerTargetKey(composerDraftTarget);
|
||||
const questionAttachmentTarget =
|
||||
pendingUserInputs[0] && activePendingProgress?.activeQuestion
|
||||
? questionAttachmentDraftId(
|
||||
environmentId,
|
||||
activeThreadId!,
|
||||
pendingUserInputs[0].requestId,
|
||||
activePendingProgress.activeQuestion.id,
|
||||
)
|
||||
: null;
|
||||
const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget;
|
||||
const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget);
|
||||
const attachmentTargetKey = composerTargetKey(attachmentDraftTarget);
|
||||
const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const composerFiles = composerDraft.files;
|
||||
const composerImages = attachmentDraft.images;
|
||||
const composerFiles = attachmentDraft.files;
|
||||
const composerVideos = composerFiles.filter((file) =>
|
||||
isPreviewableComposerVideo(file, environmentId),
|
||||
);
|
||||
@@ -1500,7 +1520,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
return composerImages.filter((image) => !previewAnnotationIds.has(image.id));
|
||||
}, [composerImages, composerPreviewAnnotations]);
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds;
|
||||
const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
|
||||
const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length;
|
||||
const fileStagingLimit = fileAttachmentStagingLimit({
|
||||
@@ -1515,6 +1535,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
maxFileAttachmentBytes,
|
||||
});
|
||||
const attachmentBlockReason =
|
||||
(questionAttachmentTarget &&
|
||||
!supportsQuestionAttachments &&
|
||||
(composerImages.length > 0 || composerFiles.length > 0)
|
||||
? "Update this server to send files with question answers"
|
||||
: null) ??
|
||||
fileCapabilityBlockReason ??
|
||||
(supportsAttachmentUploads
|
||||
? needsReattachFileCount > 0
|
||||
@@ -1528,7 +1553,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
})
|
||||
: null);
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
|
||||
const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
|
||||
@@ -1596,11 +1620,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
if (attachment.type === "file" && composerFileNeedsReattach(attachment)) {
|
||||
continue;
|
||||
}
|
||||
startAttachmentUpload({ environmentId, image: attachment, draftTarget: composerDraftTarget });
|
||||
startAttachmentUpload({
|
||||
environmentId,
|
||||
image: attachment,
|
||||
draftTarget: attachmentDraftTarget,
|
||||
});
|
||||
}
|
||||
}, [
|
||||
attachmentUploadsCapabilityKnown,
|
||||
composerDraftTarget,
|
||||
attachmentDraftTarget,
|
||||
composerFiles,
|
||||
composerImages,
|
||||
environmentId,
|
||||
@@ -1621,7 +1649,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const upload = uploadsByImageId[file.id];
|
||||
if (upload?.status === "ready" && upload.environmentId === environmentId) {
|
||||
setComposerDraftFileUpload(
|
||||
composerDraftTarget,
|
||||
attachmentDraftTarget,
|
||||
file.id,
|
||||
environmentId,
|
||||
upload.attachmentId,
|
||||
@@ -1630,7 +1658,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}
|
||||
}, [
|
||||
attachmentUploadsCapabilityKnown,
|
||||
composerDraftTarget,
|
||||
attachmentDraftTarget,
|
||||
composerFiles,
|
||||
environmentId,
|
||||
maxFileAttachmentBytes,
|
||||
@@ -1713,7 +1741,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
const sendDisabledReason =
|
||||
externalSendDisabledReason ??
|
||||
(activePendingProgress ? null : (attachmentBlockReason ?? providerSendBlockReason));
|
||||
(activePendingProgress
|
||||
? attachmentBlockReason
|
||||
: (attachmentBlockReason ?? providerSendBlockReason));
|
||||
const isSendDisabled = sendDisabledReason !== null;
|
||||
const selectedProviderStatus = useMemo(
|
||||
() => selectedProviderEntry?.snapshot ?? null,
|
||||
@@ -1938,7 +1968,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
* and checked before sending or compacting so an image cannot move into
|
||||
* the next draft.
|
||||
*/
|
||||
const pendingImageCompressionsRef = useRef<Map<ThreadId, number>>(new Map());
|
||||
const pendingImageCompressionsRef = useRef<Map<string, number>>(new Map());
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Derived: composer send state
|
||||
@@ -2127,7 +2157,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
(!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null);
|
||||
const showCollapsedMobilePromptRow =
|
||||
isComposerCollapsedMobile && !isComposerApprovalState && pendingUserInputs.length === 0;
|
||||
const showComposerAttachAction = fileStagingLimit !== null && pendingUserInputs.length === 0;
|
||||
const showComposerAttachAction =
|
||||
fileStagingLimit !== null &&
|
||||
(!activePendingProgress ||
|
||||
(supportsQuestionAttachments &&
|
||||
activePendingProgress.activeQuestion?.allowCustomAnswer !== false));
|
||||
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
|
||||
const composerFooterActionLayoutKey = useMemo(() => {
|
||||
if (activePendingProgress) {
|
||||
@@ -2219,12 +2253,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? {
|
||||
questionIndex: activePendingProgress.questionIndex,
|
||||
isLastQuestion: activePendingProgress.isLastQuestion,
|
||||
canAdvance: activePendingProgress.canAdvance,
|
||||
canAdvance:
|
||||
activePendingProgress.canAdvance &&
|
||||
!attachmentBlockReason &&
|
||||
!(questionPreparations[attachmentTargetKey] ?? 0),
|
||||
isResponding: activePendingIsResponding,
|
||||
isComplete: Boolean(activePendingResolvedAnswers),
|
||||
}
|
||||
: null,
|
||||
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
|
||||
[
|
||||
activePendingIsResponding,
|
||||
activePendingProgress,
|
||||
activePendingResolvedAnswers,
|
||||
attachmentBlockReason,
|
||||
questionPreparations,
|
||||
attachmentTargetKey,
|
||||
],
|
||||
);
|
||||
const collapsedComposerPrimaryActionDisabled =
|
||||
phase === "running" ||
|
||||
@@ -2251,35 +2295,42 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
const addComposerImage = useCallback(
|
||||
(image: ComposerImageAttachment) => {
|
||||
addComposerDraftImage(composerDraftTarget, image);
|
||||
addComposerDraftImages(attachmentDraftTarget, [image]);
|
||||
},
|
||||
[composerDraftTarget, addComposerDraftImage],
|
||||
[attachmentDraftTarget, addComposerDraftImages],
|
||||
);
|
||||
|
||||
const addComposerImagesToDraft = useCallback(
|
||||
(images: ComposerImageAttachment[]) => {
|
||||
addComposerDraftImages(composerDraftTarget, images);
|
||||
addComposerDraftImages(attachmentDraftTarget, images);
|
||||
},
|
||||
[composerDraftTarget, addComposerDraftImages],
|
||||
[attachmentDraftTarget, addComposerDraftImages],
|
||||
);
|
||||
|
||||
const addComposerFilesToDraft = useCallback(
|
||||
(files: ComposerFileAttachment[]) => {
|
||||
addComposerDraftFiles(composerDraftTarget, files);
|
||||
addComposerDraftFiles(attachmentDraftTarget, files);
|
||||
},
|
||||
[addComposerDraftFiles, composerDraftTarget],
|
||||
[addComposerDraftFiles, attachmentDraftTarget],
|
||||
);
|
||||
|
||||
const removeComposerImageFromDraft = useCallback(
|
||||
(imageId: string) => {
|
||||
if (questionAttachmentTarget && activePendingIsResponding) return;
|
||||
releaseAttachmentUpload(imageId);
|
||||
removeComposerDraftImage(composerDraftTarget, imageId);
|
||||
removeComposerDraftImage(attachmentDraftTarget, imageId);
|
||||
},
|
||||
[composerDraftTarget, removeComposerDraftImage],
|
||||
[
|
||||
attachmentDraftTarget,
|
||||
questionAttachmentTarget,
|
||||
activePendingIsResponding,
|
||||
removeComposerDraftImage,
|
||||
],
|
||||
);
|
||||
|
||||
const removeComposerFileFromDraft = useCallback(
|
||||
(fileId: string) => {
|
||||
if (questionAttachmentTarget && activePendingIsResponding) return;
|
||||
// Release by the draft attachment, not the bare queue key: a hydrated
|
||||
// file's upload lives server-side under its persisted attachment id.
|
||||
const file = composerFilesRef.current.find((candidate) => candidate.id === fileId);
|
||||
@@ -2288,9 +2339,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
} else {
|
||||
releaseAttachmentUpload(fileId);
|
||||
}
|
||||
removeComposerDraftFile(composerDraftTarget, fileId);
|
||||
removeComposerDraftFile(attachmentDraftTarget, fileId);
|
||||
},
|
||||
[composerDraftTarget, composerFilesRef, removeComposerDraftFile],
|
||||
[
|
||||
attachmentDraftTarget,
|
||||
questionAttachmentTarget,
|
||||
activePendingIsResponding,
|
||||
composerFilesRef,
|
||||
removeComposerDraftFile,
|
||||
],
|
||||
);
|
||||
|
||||
const removeComposerTerminalContextFromDraft = useCallback(
|
||||
@@ -2525,11 +2582,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
if (composerImages.length === 0) {
|
||||
clearComposerDraftPersistedAttachments(composerDraftTarget);
|
||||
clearComposerDraftPersistedAttachments(attachmentDraftTarget);
|
||||
return;
|
||||
}
|
||||
const getPersistedAttachmentsForThread = () =>
|
||||
getComposerDraft(composerDraftTarget)?.persistedAttachments ?? [];
|
||||
getComposerDraft(attachmentDraftTarget)?.persistedAttachments ?? [];
|
||||
try {
|
||||
const currentPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
const existingPersistedById = new Map(
|
||||
@@ -2558,7 +2615,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
const serialized = Array.from(stagedAttachmentById.values());
|
||||
if (cancelled) return;
|
||||
syncComposerDraftPersistedAttachments(composerDraftTarget, serialized);
|
||||
syncComposerDraftPersistedAttachments(attachmentDraftTarget, serialized);
|
||||
} catch {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
@@ -2573,14 +2630,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
fallbackPersistedIdSet.has(attachment.id),
|
||||
);
|
||||
if (cancelled) return;
|
||||
syncComposerDraftPersistedAttachments(composerDraftTarget, fallbackAttachments);
|
||||
syncComposerDraftPersistedAttachments(attachmentDraftTarget, fallbackAttachments);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [
|
||||
composerDraftTarget,
|
||||
attachmentDraftTarget,
|
||||
clearComposerDraftPersistedAttachments,
|
||||
composerImages,
|
||||
getComposerDraft,
|
||||
@@ -2946,7 +3003,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// image: the turn snapshot wouldn't include it, and it would surface
|
||||
// in the *next* draft instead. Only oversized images hit this — small
|
||||
// files clear the pending counter within a microtask.
|
||||
if (activeThreadId && (pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) {
|
||||
if (
|
||||
activeThreadId &&
|
||||
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0
|
||||
) {
|
||||
event?.preventDefault();
|
||||
toastManager.add({
|
||||
type: "info",
|
||||
@@ -2976,6 +3036,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
[
|
||||
activeThreadId,
|
||||
activePendingProgress,
|
||||
attachmentTargetKey,
|
||||
blurMobileComposerAfterSend,
|
||||
isSendDisabled,
|
||||
noProviderAvailable,
|
||||
@@ -3009,7 +3070,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// The compact buttons cannot see the compression counter (it lives in
|
||||
// a ref), so they render enabled during a paste; toast instead of
|
||||
// silently ignoring the click.
|
||||
if ((pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) {
|
||||
if ((pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0) {
|
||||
toastManager.add({
|
||||
type: "info",
|
||||
title: "Still compressing a pasted image.",
|
||||
@@ -4255,10 +4316,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// ------------------------------------------------------------------
|
||||
const addComposerAttachments = async (files: File[]) => {
|
||||
if (!activeThreadId || files.length === 0) return;
|
||||
if (pendingUserInputs.length > 0) {
|
||||
if (
|
||||
pendingUserInputs.length > 0 &&
|
||||
(!supportsQuestionAttachments ||
|
||||
activePendingProgress?.activeQuestion?.allowCustomAnswer === false ||
|
||||
activePendingIsResponding)
|
||||
) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Attach files after answering pending questions.",
|
||||
title: "This question cannot accept attachments.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -4270,9 +4336,31 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// Validation happens synchronously so concurrent pastes see each other:
|
||||
// accepted files reserve their attachment slots (via the pending counter)
|
||||
// before the first await, keeping the total under the limit.
|
||||
const pendingCount = pendingImageCompressionsRef.current.get(threadId) ?? 0;
|
||||
const pendingCount = pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0;
|
||||
const otherQuestionAttachments =
|
||||
questionAttachmentTarget && pendingUserInputs[0]
|
||||
? pendingUserInputs[0].questions.reduce((count, question) => {
|
||||
const target = questionAttachmentDraftId(
|
||||
environmentId,
|
||||
threadId,
|
||||
pendingUserInputs[0]!.requestId,
|
||||
question.id,
|
||||
);
|
||||
if (target === questionAttachmentTarget) return count;
|
||||
const draft = getComposerDraft(target);
|
||||
return (
|
||||
count +
|
||||
(draft?.images.length ?? 0) +
|
||||
(draft?.files.length ?? 0) +
|
||||
(useQuestionAttachmentPreparation.getState().counts[target] ?? 0)
|
||||
);
|
||||
}, 0)
|
||||
: 0;
|
||||
let reservedCount =
|
||||
composerImagesRef.current.length + composerFilesRef.current.length + pendingCount;
|
||||
composerImagesRef.current.length +
|
||||
composerFilesRef.current.length +
|
||||
pendingCount +
|
||||
otherQuestionAttachments;
|
||||
// A pick that matches a needs-reattach marker replaces it in the draft, so
|
||||
// it must not consume a slot; a draft full of markers would otherwise hit
|
||||
// the capacity error before the replacement path could run.
|
||||
@@ -4351,7 +4439,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}
|
||||
if (acceptedImages.length === 0) return;
|
||||
|
||||
pendingImageCompressionsRef.current.set(threadId, pendingCount + acceptedImages.length);
|
||||
pendingImageCompressionsRef.current.set(
|
||||
attachmentTargetKey,
|
||||
pendingCount + acceptedImages.length,
|
||||
);
|
||||
if (questionAttachmentTarget)
|
||||
changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
|
||||
try {
|
||||
const nextImages: ComposerImageAttachment[] = [];
|
||||
let compressionError: string | null = null;
|
||||
@@ -4381,6 +4474,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
file: attachmentFile,
|
||||
});
|
||||
}
|
||||
if (
|
||||
questionAttachmentTarget &&
|
||||
!useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget]
|
||||
) {
|
||||
for (const image of nextImages) URL.revokeObjectURL(image.previewUrl);
|
||||
return;
|
||||
}
|
||||
if (nextImages.length === 1 && nextImages[0]) {
|
||||
addComposerImage(nextImages[0]);
|
||||
} else if (nextImages.length > 1) {
|
||||
@@ -4394,12 +4494,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setThreadError(threadId, compressionError);
|
||||
}
|
||||
} finally {
|
||||
if (questionAttachmentTarget)
|
||||
changeQuestionAttachmentPreparation(questionAttachmentTarget, -acceptedImages.length);
|
||||
const remaining =
|
||||
(pendingImageCompressionsRef.current.get(threadId) ?? 0) - acceptedImages.length;
|
||||
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) - acceptedImages.length;
|
||||
if (remaining > 0) {
|
||||
pendingImageCompressionsRef.current.set(threadId, remaining);
|
||||
pendingImageCompressionsRef.current.set(attachmentTargetKey, remaining);
|
||||
} else {
|
||||
pendingImageCompressionsRef.current.delete(threadId);
|
||||
pendingImageCompressionsRef.current.delete(attachmentTargetKey);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -4909,7 +5011,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
) : !isComposerCollapsedMobile && pendingUserInputs.length > 0 ? (
|
||||
<ComposerPendingUserInputPanel
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
respondingRequestIds={
|
||||
activePendingIsResponding && activePendingUserInput
|
||||
? [...respondingRequestIds, activePendingUserInput.requestId]
|
||||
: respondingRequestIds
|
||||
}
|
||||
answers={activePendingDraftAnswers}
|
||||
questionIndex={activePendingQuestionIndex}
|
||||
onToggleOption={onSelectActivePendingUserInputOption}
|
||||
@@ -4925,7 +5031,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<div data-chat-composer-collapsed-controls="true">
|
||||
<ComposerPendingUserInputPanel
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
respondingRequestIds={
|
||||
activePendingIsResponding && activePendingUserInput
|
||||
? [...respondingRequestIds, activePendingUserInput.requestId]
|
||||
: respondingRequestIds
|
||||
}
|
||||
answers={activePendingDraftAnswers}
|
||||
questionIndex={activePendingQuestionIndex}
|
||||
onToggleOption={onSelectActivePendingUserInputOption}
|
||||
@@ -5148,7 +5258,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
retryAttachmentUpload({
|
||||
environmentId,
|
||||
image,
|
||||
draftTarget: composerDraftTarget,
|
||||
draftTarget: attachmentDraftTarget,
|
||||
}),
|
||||
}
|
||||
: {})}
|
||||
@@ -5192,7 +5302,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
{!isComposerCollapsedMobile &&
|
||||
!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
(uncommittedSnapShotIds.length > 0 ||
|
||||
composerVideos.length > 0 ||
|
||||
expandedComposerImages.length > 0) && (
|
||||
@@ -5310,7 +5419,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
retryAttachmentUpload({
|
||||
environmentId,
|
||||
image,
|
||||
draftTarget: composerDraftTarget,
|
||||
draftTarget: attachmentDraftTarget,
|
||||
})
|
||||
}
|
||||
aria-label={`Retry upload for ${image.name}`}
|
||||
@@ -5410,7 +5519,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
retryAttachmentUpload({
|
||||
environmentId,
|
||||
image: file,
|
||||
draftTarget: composerDraftTarget,
|
||||
draftTarget: attachmentDraftTarget,
|
||||
})
|
||||
}
|
||||
aria-label={`Retry upload for ${file.name}`}
|
||||
@@ -5444,7 +5553,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
|
||||
{!isComposerCollapsedMobile &&
|
||||
!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
composerOtherFiles.length > 0 && (
|
||||
<div className="mb-3 flex flex-col gap-1">
|
||||
{composerOtherFiles.map((file) => {
|
||||
@@ -5487,7 +5595,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
retryAttachmentUpload({
|
||||
environmentId,
|
||||
image: file,
|
||||
draftTarget: composerDraftTarget,
|
||||
draftTarget: attachmentDraftTarget,
|
||||
})
|
||||
}
|
||||
aria-label={`Retry upload for ${file.name}`}
|
||||
@@ -5587,7 +5695,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isConnecting ||
|
||||
isComposerApprovalState ||
|
||||
projectSelectionRequired ||
|
||||
isChoiceOnlyPendingQuestion
|
||||
isChoiceOnlyPendingQuestion ||
|
||||
activePendingIsResponding
|
||||
}
|
||||
/>
|
||||
{isComposerResting ? collapsedComposerImagePreviews : null}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CheckpointRef,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { act, createRef, useLayoutEffect, type ReactNode, type Ref } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
@@ -266,6 +272,75 @@ function buildSnapShotTimelineEntry(previewUrl?: string) {
|
||||
}
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
// Expanding history uses this suite's existing test renderer, deprecated in
|
||||
// React 19. Migrate these interaction tests together when a DOM test setup is added.
|
||||
it.each([{}, { text: "Text-only answer", file: "Answer with a file" }])(
|
||||
"renders attachment-only question history alongside text answers: %j",
|
||||
async (answers) => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("requestAnimationFrame", () => 0);
|
||||
vi.stubGlobal("cancelAnimationFrame", () => {});
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
try {
|
||||
await act(() => {
|
||||
renderer = create(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "answer-entry",
|
||||
kind: "work",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
entry: {
|
||||
id: "answer-work",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
label: "Question answer submitted",
|
||||
tone: "info",
|
||||
questionAnswer: {
|
||||
requestId: ApprovalRequestId.make("question-request"),
|
||||
answers,
|
||||
questionTextById: { file: "Provide a spec", image: "Provide a screenshot" },
|
||||
attachmentsByQuestionId: {
|
||||
file: [
|
||||
{
|
||||
type: "file",
|
||||
id: "spec",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
image: [
|
||||
{
|
||||
type: "image",
|
||||
id: "shot",
|
||||
name: "shot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const toggle = renderer!.root.findByProps({ "aria-expanded": false });
|
||||
await act(() => toggle.props.onClick());
|
||||
const markup = JSON.stringify(renderer!.toJSON());
|
||||
expect(markup.match(/Provide a spec/g)).toHaveLength(1);
|
||||
expect(markup.match(/spec\.txt/g)).toHaveLength(1);
|
||||
expect(markup).toContain("Provide a screenshot");
|
||||
expect(markup).toContain("shot.png");
|
||||
for (const answer of Object.values(answers)) expect(markup).toContain(answer);
|
||||
} finally {
|
||||
await act(() => renderer?.unmount());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ toolLifecycleStatus: "inProgress", isAtEnd: true },
|
||||
{ toolLifecycleStatus: "inProgress", isAtEnd: false },
|
||||
|
||||
@@ -3216,7 +3216,9 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
showWarningIndicator || showDestructiveRowStyle
|
||||
? undefined
|
||||
: (workEntry.toolIcon ?? workEntry.toolSource?.icon);
|
||||
const previewText = displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot);
|
||||
const previewText = workEntry.questionAnswer
|
||||
? "Question answer submitted"
|
||||
: (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));
|
||||
const viewedImagePath = workEntryViewedImagePath(workEntry);
|
||||
const viewedImage =
|
||||
viewedImagePath && threadRef
|
||||
@@ -3362,6 +3364,9 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{workEntry.questionAnswer ? (
|
||||
<QuestionAnswerHistory answer={workEntry.questionAnswer} />
|
||||
) : null}
|
||||
{expanded && canExpand && expandedBody ? (
|
||||
<div
|
||||
className="mt-1 ms-7 cursor-default rounded-md bg-muted/40 px-3 py-2"
|
||||
@@ -3374,3 +3379,67 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
function QuestionAnswerHistory({
|
||||
answer,
|
||||
}: {
|
||||
answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
|
||||
}) {
|
||||
const { activeThreadEnvironmentId } = use(TimelineRowCtx);
|
||||
const attachments = useMemo(() => Object.values(answer.attachmentsByQuestionId).flat(), [answer]);
|
||||
const resources = useMemo(
|
||||
() =>
|
||||
attachments.map((attachment) => ({
|
||||
_tag: "attachment" as const,
|
||||
attachmentId: attachment.id,
|
||||
})),
|
||||
[attachments],
|
||||
);
|
||||
const urls = useAssetUrls(activeThreadEnvironmentId, resources);
|
||||
return (
|
||||
<div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
|
||||
{[
|
||||
...new Set([
|
||||
...Object.keys(answer.answers),
|
||||
...Object.keys(answer.attachmentsByQuestionId),
|
||||
]),
|
||||
].map((questionId) => (
|
||||
<div key={questionId} className="space-y-1">
|
||||
{answer.questionTextById?.[questionId] ? (
|
||||
<p className="text-sm text-muted-foreground">{answer.questionTextById[questionId]}</p>
|
||||
) : null}
|
||||
<p className="whitespace-pre-wrap text-sm">
|
||||
{[answer.answers[questionId]]
|
||||
.flat()
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.join(", ")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {
|
||||
const url = urls[attachments.indexOf(attachment)];
|
||||
return (
|
||||
<a
|
||||
key={attachment.id}
|
||||
href={url ?? undefined}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-sm underline"
|
||||
>
|
||||
{attachment.type === "image" && url ? (
|
||||
<img
|
||||
src={url}
|
||||
alt={attachment.name}
|
||||
className="h-20 max-w-32 rounded object-contain"
|
||||
/>
|
||||
) : (
|
||||
attachment.name
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -339,6 +339,32 @@ describe("attachmentUploadQueue", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("persists a retried question upload without a mounted composer", async () => {
|
||||
const draftId = DraftId.make("question-retry-upload");
|
||||
const file = makeFile("question-retry");
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.addFiles(draftId, [file]);
|
||||
try {
|
||||
startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
|
||||
await Promise.resolve();
|
||||
let settled = awaitAttachmentUploads([file.id]);
|
||||
TestXmlHttpRequest.requests[0]!.complete(500);
|
||||
await settled;
|
||||
expect(store.getComposerDraft(draftId)?.files[0]?.uploadedAttachmentId).toBeUndefined();
|
||||
retryAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
|
||||
await Promise.resolve();
|
||||
settled = awaitAttachmentUploads([file.id]);
|
||||
TestXmlHttpRequest.requests[1]!.complete();
|
||||
await settled;
|
||||
expect(store.getComposerDraft(draftId)?.files[0]).toMatchObject({
|
||||
uploadedAttachmentId: "pending-environment-1-question-retry.pdf",
|
||||
uploadEnvironmentId: firstEnvironment,
|
||||
});
|
||||
} finally {
|
||||
store.clearComposerContent(draftId);
|
||||
}
|
||||
});
|
||||
|
||||
it("verifies an uploaded file reference before restoring it", async () => {
|
||||
const file: ComposerFileAttachment = {
|
||||
...makeFile("restored"),
|
||||
|
||||
@@ -302,3 +302,22 @@ describe("pending user input question progress", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts attachment-only answers after every upload finishes", () => {
|
||||
const questions = [
|
||||
{ id: "spec", header: "Spec", question: "Provide a spec", options: [], multiSelect: false },
|
||||
];
|
||||
expect(buildPendingUserInputAnswers(questions, { spec: { attachmentCount: 1 } })).toEqual({
|
||||
spec: "",
|
||||
});
|
||||
expect(
|
||||
buildPendingUserInputAnswers(questions, {
|
||||
spec: { attachmentCount: 1, attachmentsBlocked: true },
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
buildPendingUserInputAnswers([{ ...questions[0]!, allowCustomAnswer: false }], {
|
||||
spec: { attachmentCount: 1 },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import type { UserInputQuestion } from "@t3tools/contracts";
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
selectedOptionValues?: string[];
|
||||
customAnswer?: string;
|
||||
attachmentCount?: number;
|
||||
attachmentsBlocked?: boolean;
|
||||
}
|
||||
|
||||
export interface PendingUserInputProgress {
|
||||
@@ -41,6 +43,7 @@ export function resolvePendingUserInputAnswer(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
): string | string[] | null {
|
||||
if (draft?.attachmentsBlocked) return null;
|
||||
const customAnswer =
|
||||
question.allowCustomAnswer === false ? null : normalizeDraftAnswer(draft?.customAnswer);
|
||||
if (customAnswer) {
|
||||
@@ -51,10 +54,17 @@ export function resolvePendingUserInputAnswer(
|
||||
(value) => question.options.some((option) => (option.value ?? option.label) === value),
|
||||
);
|
||||
if (question.multiSelect) {
|
||||
return selectedOptionValues.length > 0 ? selectedOptionValues : null;
|
||||
return selectedOptionValues.length > 0
|
||||
? selectedOptionValues
|
||||
: question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0
|
||||
? ""
|
||||
: null;
|
||||
}
|
||||
|
||||
return selectedOptionValues[0] ?? null;
|
||||
return (
|
||||
selectedOptionValues[0] ??
|
||||
(question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
|
||||
);
|
||||
}
|
||||
|
||||
export function setPendingUserInputCustomAnswer(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, expect, it, vi } from "vite-plus/test";
|
||||
import { useComposerDraftStore } from "./composerDraftStore";
|
||||
import {
|
||||
questionAttachmentDraftId,
|
||||
questionAttachmentDraftPrefix,
|
||||
changeQuestionAttachmentPreparation,
|
||||
clearQuestionAttachmentDraft,
|
||||
useQuestionAttachmentPreparation,
|
||||
} from "./questionAttachments";
|
||||
|
||||
const release = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./lib/attachmentUploadQueue", () => ({ releaseDraftAttachments: release }));
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const requestId = ApprovalRequestId.make("request-1");
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
|
||||
useQuestionAttachmentPreparation.setState({ counts: {} });
|
||||
release.mockClear();
|
||||
});
|
||||
it("keeps question files separate from the normal draft and other questions", () => {
|
||||
const revoke = vi.spyOn(URL, "revokeObjectURL");
|
||||
const store = useComposerDraftStore.getState();
|
||||
const first = questionAttachmentDraftId(environmentId, threadId, requestId, "first");
|
||||
const second = questionAttachmentDraftId(environmentId, threadId, requestId, "second");
|
||||
store.setPrompt({ environmentId, threadId }, "Unsent prompt");
|
||||
const image = {
|
||||
type: "image" as const,
|
||||
id: "image-1",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
previewUrl: "blob:question-image",
|
||||
file: new File(["image"], "image.png", { type: "image/png" }),
|
||||
};
|
||||
store.addImages(first, [image]);
|
||||
store.addFiles(second, [
|
||||
{
|
||||
type: "file",
|
||||
id: "file-1",
|
||||
name: "spec.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
file: new File(["spec"], "spec.txt", { type: "text/plain" }),
|
||||
},
|
||||
]);
|
||||
changeQuestionAttachmentPreparation(first, 1);
|
||||
expect(store.getComposerDraft(first)?.images).toHaveLength(1);
|
||||
expect(store.getComposerDraft(second)?.files).toHaveLength(1);
|
||||
clearQuestionAttachmentDraft(first);
|
||||
expect(store.getComposerDraft(first)).toBeNull();
|
||||
expect(store.getComposerDraft(second)?.files).toHaveLength(1);
|
||||
expect(store.getComposerDraft({ environmentId, threadId })?.prompt).toBe("Unsent prompt");
|
||||
expect(useQuestionAttachmentPreparation.getState().counts[first]).toBeUndefined();
|
||||
expect(release).toHaveBeenCalledWith([image]);
|
||||
expect(revoke).toHaveBeenCalledWith(image.previewUrl);
|
||||
revoke.mockRestore();
|
||||
});
|
||||
it("scopes provider request ids to their environment and thread", () => {
|
||||
const keys = [
|
||||
questionAttachmentDraftId(environmentId, threadId, requestId, "q"),
|
||||
questionAttachmentDraftId(EnvironmentId.make("environment-2"), threadId, requestId, "q"),
|
||||
questionAttachmentDraftId(environmentId, ThreadId.make("thread-2"), requestId, "q"),
|
||||
];
|
||||
expect(new Set(keys).size).toBe(3);
|
||||
});
|
||||
it("does not match drafts belonging to threads with a shared id prefix", () => {
|
||||
const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
|
||||
expect(
|
||||
questionAttachmentDraftId(environmentId, threadId, requestId, "q").startsWith(prefix),
|
||||
).toBe(true);
|
||||
for (const suffix of ["-extra", ":extra", "/extra", "%extra"]) {
|
||||
expect(
|
||||
questionAttachmentDraftId(
|
||||
environmentId,
|
||||
ThreadId.make(`${threadId}${suffix}`),
|
||||
requestId,
|
||||
"q",
|
||||
).startsWith(prefix),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not clear another environment whose id contains a question prefix", () => {
|
||||
const otherEnvironment = EnvironmentId.make(
|
||||
`${environmentId}:question-${encodeURIComponent(JSON.stringify(threadId))}-nested`,
|
||||
);
|
||||
const otherKey = questionAttachmentDraftId(otherEnvironment, threadId, requestId, "q");
|
||||
const ownKey = questionAttachmentDraftId(environmentId, threadId, requestId, "q");
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setPrompt(otherKey, "Keep this answer");
|
||||
store.setPrompt(ownKey, "Discard this answer");
|
||||
const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
|
||||
for (const key of [ownKey, otherKey]) {
|
||||
if (key.startsWith(prefix)) clearQuestionAttachmentDraft(key);
|
||||
}
|
||||
expect(store.getComposerDraft(ownKey)).toBeNull();
|
||||
expect(store.getComposerDraft(otherKey)?.prompt).toBe("Keep this answer");
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { DraftId, useComposerDraftStore } from "./composerDraftStore";
|
||||
import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
|
||||
|
||||
export function questionAttachmentDraftPrefix(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
): string {
|
||||
return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
|
||||
}
|
||||
|
||||
export function questionAttachmentDraftId(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
): DraftId {
|
||||
return DraftId.make(
|
||||
`${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
|
||||
);
|
||||
}
|
||||
|
||||
export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
|
||||
counts: {},
|
||||
}));
|
||||
|
||||
export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
|
||||
useQuestionAttachmentPreparation.setState((state) =>
|
||||
delta < 0 && !(key in state.counts)
|
||||
? state
|
||||
: {
|
||||
counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function clearQuestionAttachmentDraft(key: DraftId): void {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const draft = store.getComposerDraft(key);
|
||||
if (draft) {
|
||||
releaseDraftAttachments([...draft.images, ...draft.files]);
|
||||
for (const image of draft.images) {
|
||||
if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
|
||||
}
|
||||
}
|
||||
store.clearComposerContent(key);
|
||||
useQuestionAttachmentPreparation.setState(({ counts }) => {
|
||||
const next = { ...counts };
|
||||
delete next[key];
|
||||
return { counts: next };
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,9 @@ import {
|
||||
requestKindFromRequestType,
|
||||
type PendingApproval,
|
||||
} from "@t3tools/client-runtime/pending-requests";
|
||||
import { UserInputAttachmentAnswerPayload } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Arr from "effect/Array";
|
||||
import { shallow } from "zustand/vanilla/shallow";
|
||||
import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";
|
||||
@@ -51,6 +53,7 @@ export {
|
||||
} from "@t3tools/client-runtime/work-log/presentation";
|
||||
|
||||
export interface WorkLogEntry {
|
||||
questionAnswer?: UserInputAttachmentAnswerPayload;
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId?: TurnId | null;
|
||||
@@ -492,6 +495,8 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
const decodeQuestionAttachmentAnswer = Schema.decodeUnknownOption(UserInputAttachmentAnswerPayload);
|
||||
|
||||
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
|
||||
const cachedEntry = derivedWorkLogEntryByActivity.get(activity);
|
||||
if (cachedEntry) {
|
||||
@@ -543,6 +548,10 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
: activity.tone,
|
||||
sourceActivityKind: activity.kind,
|
||||
};
|
||||
if (activity.kind === "user-input.answer-submitted") {
|
||||
const answer = decodeQuestionAttachmentAnswer(payload);
|
||||
if (Option.isSome(answer)) entry.questionAnswer = answer.value;
|
||||
}
|
||||
const itemType = extractWorkLogItemType(payload);
|
||||
const requestKind = extractWorkLogRequestKind(payload);
|
||||
const viewedImagePath = asTrimmedString(asRecord(payload?.data)?.imagePath);
|
||||
|
||||
Reference in new issue
Block a user