Files
deerflow-code/frontend-web/src/core/artifacts/write-file-in-flight.ts
T

283 lines
9.0 KiB
TypeScript

import { isInterceptedWritingReportWrite } from "../threads/writing-mode";
import { isImageFile } from "../utils/files";
import {
listStreamingWriteFileCalls,
resolveStreamingWriteFileArgs,
} from "./parse-partial-json";
import {
buildWriteFileVirtualUrl,
isAutoPreviewableArtifactPath,
languageOfStreamingArtifact,
normalizeStreamingArtifactPath,
namedStreamingWriteFilePath,
} from "./streaming-write-preview";
export { resolveStreamingWriteFileArgs } from "./parse-partial-json";
export function isWriteFileStreamingUrl(filepath: string): boolean {
if (!filepath.startsWith("write-file:")) {
return false;
}
try {
const url = new URL(filepath);
const path = decodeURIComponent(url.pathname);
return !isImageFile(path);
} catch {
return true;
}
}
export function resolveWriteFilePath(filepath: string): string {
if (filepath.startsWith("write-file:")) {
try {
return decodeURIComponent(new URL(filepath).pathname).trim();
} catch {
const rest = filepath.slice("write-file:".length);
return rest.split(/[?#]/, 1)[0]?.trim() ?? filepath;
}
}
return filepath.trim();
}
type WriteFileThreadLike = {
messages: Array<{
id?: string;
type?: string;
name?: string;
content?: unknown;
tool_call_id?: string;
additional_kwargs?: Record<string, unknown>;
tool_calls?: Array<{
id?: string;
name?: string;
args?: unknown;
index?: number;
}>;
tool_call_chunks?: Array<{
id?: string;
name?: string;
args?: unknown;
index?: number;
}>;
}>;
};
function parseToolJson(content: unknown): Record<string, unknown> | null {
let value = content;
if (Array.isArray(value)) {
const textBlock = value.find(
(item) =>
item &&
typeof item === "object" &&
"text" in item &&
typeof (item as { text?: unknown }).text === "string",
) as { text?: string } | undefined;
value = textBlock?.text;
}
if (typeof value === "string") {
try {
value = JSON.parse(value) as unknown;
} catch {
return null;
}
}
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function hasLaterOutputHtmlWrite(
messages: WriteFileThreadLike["messages"],
preparedMessageIndex: number,
): boolean {
for (
let messageIndex = preparedMessageIndex + 1;
messageIndex < messages.length;
messageIndex += 1
) {
const message = messages[messageIndex];
if (message?.type !== "ai") continue;
for (const write of listStreamingWriteFileCalls(message)) {
const path = write.path
? normalizeStreamingArtifactPath(write.path)
: "";
if (/^\/mnt\/user-data\/outputs\/.+\.html?$/i.test(path)) {
return true;
}
}
}
return false;
}
/**
* A successful page-template prepare already creates a previewable HTML file
* under outputs. Open it before the first edit arrives so the user sees the
* sandbox as soon as page generation starts when the model edits it in place.
*
* A later write_file to outputs is a new final artifact, not a reason to keep
* the prepared template selected. Let the write preview take over instead;
* otherwise the template's cached content can reappear until a manual refresh.
*/
export function latestPreparedHtmlArtifact(
messages: WriteFileThreadLike["messages"],
): { artifactPath: string; previewKey: string } | null {
for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
const message = messages[messageIndex];
if (message?.type !== "ai" || !message.tool_calls) continue;
for (let toolIndex = message.tool_calls.length - 1; toolIndex >= 0; toolIndex -= 1) {
const toolCall = message.tool_calls[toolIndex];
if (toolCall?.name !== "page_report_template" || !toolCall.id) continue;
const args = toolCall.args as { action?: unknown } | undefined;
if (String(args?.action ?? "").toLowerCase() !== "prepare") continue;
const resultMessage = messages.find(
(candidate) =>
candidate.type === "tool" && candidate.tool_call_id === toolCall.id,
);
const result = parseToolJson(resultMessage?.content);
if (result?.ok !== true) continue;
const candidate =
typeof result.working_copy === "string"
? result.working_copy
: typeof result.final_output === "string"
? result.final_output
: "";
const artifactPath = candidate.trim();
if (!/^\/mnt\/user-data\/outputs\/.+\.html?$/i.test(artifactPath)) continue;
if (hasLaterOutputHtmlWrite(messages, messageIndex)) continue;
return {
artifactPath,
previewKey: `page-template:${toolCall.id}`,
};
}
}
return null;
}
function hasToolResult(thread: WriteFileThreadLike, toolCallId?: string) {
if (!toolCallId) {
return false;
}
return thread.messages.some(
(message) => message.type === "tool" && message.tool_call_id === toolCallId,
);
}
/**
* A completed write_file or str_replace changes the server-side artifact even
* when its path stays the same. The id becomes a React Query revision key so a
* previously prepared template cannot remain cached after the final HTML lands.
*/
export function latestCompletedArtifactMutationKey(
thread: WriteFileThreadLike,
filepath: string,
): string | null {
const targetPath = normalizeStreamingArtifactPath(filepath);
if (!targetPath) return null;
for (let messageIndex = thread.messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
const message = thread.messages[messageIndex];
if (message?.type !== "ai" || !message.tool_calls) continue;
for (let toolIndex = message.tool_calls.length - 1; toolIndex >= 0; toolIndex -= 1) {
const toolCall = message.tool_calls[toolIndex];
if (
(toolCall?.name !== "write_file" && toolCall?.name !== "str_replace") ||
!toolCall.id ||
!hasToolResult(thread, toolCall.id)
) {
continue;
}
const { path: rawPath } = resolveStreamingWriteFileArgs(message, toolCall);
const path = rawPath ? normalizeStreamingArtifactPath(rawPath) : "";
if (path === targetPath) {
return `${toolCall.name}:${toolCall.id}`;
}
}
}
return null;
}
/** True only while THIS file's write_file call has not yet returned a tool result. */
export function isWriteFileInFlight(
thread: WriteFileThreadLike,
filepath: string,
): boolean {
const path = resolveWriteFilePath(filepath);
if (!path) {
return false;
}
for (const message of thread.messages) {
if (message.type !== "ai") {
continue;
}
for (const write of listStreamingWriteFileCalls(message)) {
const callPath = write.path.trim();
if (callPath !== path) {
continue;
}
if (!hasToolResult(thread, write.id)) {
return true;
}
}
}
return false;
}
/**
* Latest in-flight `write_file` that the sandbox can live-preview.
* Scans all messages (not just the last CoT step) so a write that is
* followed by `present_files` / bash in the same turn still opens the panel
* while arguments stream in — same idea as position-roundtable's
* `latestStreamingWriteFile`.
*/
export function latestInFlightWriteFilePreview(
messages: WriteFileThreadLike["messages"],
writingMode = false,
): { artifactPath: string; previewKey: string } | null {
const thread = { messages };
for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
const message = messages[messageIndex];
if (message?.type !== "ai" || !message.id) {
continue;
}
const writes = listStreamingWriteFileCalls(message);
for (let toolIndex = writes.length - 1; toolIndex >= 0; toolIndex -= 1) {
const toolCall = writes[toolIndex];
if (!toolCall?.id) {
continue;
}
if (hasToolResult(thread, toolCall.id)) {
continue;
}
const sourcePath = namedStreamingWriteFilePath(toolCall.path);
if (!sourcePath) {
continue;
}
// Writing mode rewrites custom outputs/*.md to deep_research_report.
// Opening that filename would 404-poll until report.md lands. Normal
// mode never skips: the write is a real deliverable, not a rewrite.
if (isInterceptedWritingReportWrite(sourcePath, message.id, messages, writingMode)) {
continue;
}
// JSON (e.g. agentfx task-reports.json) is too large to live-preview:
// switching the sandbox onto it freezes the main thread, then the rest
// of the turn appears to dump at once. Keep showing markdown instead.
if (!languageOfStreamingArtifact(sourcePath)) {
continue;
}
if (!isAutoPreviewableArtifactPath(sourcePath)) {
continue;
}
return {
artifactPath: buildWriteFileVirtualUrl({
path: sourcePath,
messageId: message.id,
toolCallId: toolCall.id,
}),
previewKey: `${message.id}:${toolCall.id}`,
};
}
}
return null;
}