Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions packages/cli/src/serve/routes/workspace-file-read.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,18 +557,18 @@ describe('capability advertisement', () => {
});
});

// The `record_artifact` hint that `write_file` appends to a successful write
// names a `workspacePath`, and the model hands that exact string back to this
// route. Producer and consumer live in different packages, each with its own
// notion of what the path is relative to — `write_file` starts from the session
// cwd, the route resolves against the bound workspace root. They agree for an
// ordinary session and drifted apart for a worktree one, where every artifact
// preview 404'd. Neither side's unit tests could catch that: both were
// internally consistent. These pin the round trip instead, over real HTTP.
describe('record_artifact workspacePath contract (write_file ⇄ GET /file)', () => {
// The artifact metadata that `write_file` returns for successful writes names a
// `workspacePath`, and this route later resolves that exact string. Producer and
// consumer live in different packages, each with its own notion of what the path
// is relative to — `write_file` starts from the session cwd, the route resolves
// against the bound workspace root. They agree for an ordinary session and
// drifted apart for a worktree one, where every artifact preview 404'd. Neither
// side's unit tests could catch that: both were internally consistent. These pin
// the round trip instead, over real HTTP.
describe('artifact workspacePath contract (write_file ⇄ GET /file)', () => {
const ARTIFACT = '<!doctype html><h1>Quarterly Chart</h1>';

/** The workspacePath the model is told to send, from the real producer. */
/** The workspacePath emitted by the real producer. */
function emittedWorkspacePath(sessionCwd: string, filePath: string): string {
const reminder = buildRecordArtifactReminder(
{
Expand Down
90 changes: 78 additions & 12 deletions packages/core/src/tools/write-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,24 +447,34 @@ describe('WriteFileTool', () => {
);
});

it('reminds the model to record artifact-like workspace files', async () => {
it('records artifact-like workspace files in the tool result', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const filePath = path.join(rootDir, 'reports', 'weather.html');
const content = '<!doctype html><html><body>Weather</body></html>';
const params = {
file_path: filePath,
content: '<!doctype html><html><body>Weather</body></html>',
content,
};

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).toContain('record_artifact');
expect(result.llmContent).toContain('automatically recorded');
expect(result.llmContent).toContain(
'workspacePath "reports/weather.html"',
);
expect(result.artifacts).toBeUndefined();
expect(result.artifacts).toEqual([
{
title: 'weather.html',
kind: 'html',
storage: 'workspace',
workspacePath: 'reports/weather.html',
mimeType: 'text/html',
sizeBytes: Buffer.byteLength(content),
},
]);
});

it('reminds for case-insensitive artifact extensions', async () => {
it('records case-insensitive artifact extensions', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const filePath = path.join(rootDir, 'reports', 'dashboard.HTML');
const params = {
Expand All @@ -474,13 +484,60 @@ describe('WriteFileTool', () => {

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).toContain('record_artifact');
expect(result.llmContent).toContain('automatically recorded');
expect(result.llmContent).toContain(
'workspacePath "reports/dashboard.HTML"',
);
expect(result.artifacts?.[0]).toMatchObject({
title: 'dashboard.HTML',
kind: 'html',
storage: 'workspace',
workspacePath: 'reports/dashboard.HTML',
mimeType: 'text/html',
});
});

it.each([
['notebook.ipynb', 'notebook'],
['paper.pdf', 'pdf'],
['photo.png', 'image'],
['photo.jpeg', 'image'],
['photo.jpg', 'image'],
['diagram.svg', 'image'],
['photo.webp', 'image'],
])('infers artifact kind for %s as %s', async (fileName, expectedKind) => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const filePath = path.join(rootDir, 'reports', fileName);
const params = {
file_path: filePath,
content: 'artifact content',
};

const result = await tool.build(params).execute(abortSignal);

expect(result.artifacts?.[0]).toMatchObject({
title: fileName,
kind: expectedKind,
storage: 'workspace',
workspacePath: `reports/${fileName}`,
});
});

it('does not record artifact-like files when artifact recording is disabled', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(false);
const filePath = path.join(rootDir, 'reports', 'weather.html');
const params = {
file_path: filePath,
content: '<!doctype html><html><body>Weather</body></html>',
};

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).not.toContain('automatically recorded');
expect(result.artifacts).toBeUndefined();
});

it('does not remind for ordinary source files', async () => {
it('does not record ordinary source files as artifacts', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const filePath = path.join(rootDir, 'src', 'index.ts');
const params = {
Expand All @@ -490,10 +547,11 @@ describe('WriteFileTool', () => {

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).not.toContain('record_artifact');
expect(result.llmContent).not.toContain('automatically recorded');
expect(result.artifacts).toBeUndefined();
});

it('does not remind for files outside the workspace', async () => {
it('does not record files outside the workspace as artifacts', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const filePath = path.join(tempDir, 'outside.html');
const params = {
Expand All @@ -503,10 +561,11 @@ describe('WriteFileTool', () => {

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).not.toContain('record_artifact');
expect(result.llmContent).not.toContain('automatically recorded');
expect(result.artifacts).toBeUndefined();
});

it('suggests workspace-root-relative path inside a worktree', async () => {
it('records workspace-root-relative path inside a worktree', async () => {
mockConfigInternal.isRecordArtifactEnabled.mockReturnValue(true);
const worktreeDir = path.join(
rootDir,
Expand All @@ -526,10 +585,17 @@ describe('WriteFileTool', () => {

const result = await tool.build(params).execute(abortSignal);

expect(result.llmContent).toContain('record_artifact');
expect(result.llmContent).toContain('automatically recorded');
expect(result.llmContent).toContain(
'workspacePath ".qwen/worktrees/my-feature/report.html"',
);
expect(result.artifacts?.[0]).toMatchObject({
title: 'report.html',
kind: 'html',
storage: 'workspace',
workspacePath: '.qwen/worktrees/my-feature/report.html',
mimeType: 'text/html',
});
} finally {
mockConfigInternal.getTargetDir = originalGetTargetDir;
}
Expand Down
78 changes: 68 additions & 10 deletions packages/core/src/tools/write-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { isAnyAutoMemPath, isTeamAutoMemPath } from '../memory/paths.js';
import { checkTeamMemorySecrets } from '../memory/team-memory-secret-guard.js';
import type {
FileDiff,
ToolArtifact,
ToolArtifactKind,
ToolCallConfirmationDetails,
ToolEditConfirmationDetails,
ToolInvocation,
Expand Down Expand Up @@ -520,8 +522,10 @@ class WriteFileToolInvocation extends BaseToolInvocation<
// pre-write placeholder. Best-effort: a stat failure here does
// not undo the successful write — the next Read will re-stat
// and either see fresh content or treat the entry as stale.
let postWriteSizeBytes: number | undefined;
try {
const postWriteStats = fs.statSync(file_path);
postWriteSizeBytes = postWriteStats.size;
this.config.getFileReadCache().recordWrite(file_path, postWriteStats);
} catch {
// Non-fatal: leaving a stale entry is preferable to failing
Expand Down Expand Up @@ -561,10 +565,14 @@ class WriteFileToolInvocation extends BaseToolInvocation<
`User modified the \`content\` to be: ${content}`,
);
}
const artifactReminder = buildRecordArtifactReminder(
const artifact = buildWorkspaceArtifactMetadata(
this.config,
file_path,
postWriteSizeBytes,
);
const artifactReminder = artifact
? buildRecordArtifactReminder(this.config, file_path)
: null;
Comment thread
chiga0 marked this conversation as resolved.
Resolved
if (artifactReminder) {
llmSuccessMessageParts.push(artifactReminder);
}
Expand Down Expand Up @@ -601,6 +609,7 @@ class WriteFileToolInvocation extends BaseToolInvocation<
return {
llmContent: llmSuccessMessageParts.join(' '),
returnDisplay: displayResult,
...(artifact ? { artifacts: [artifact] } : {}),
};
} catch (error) {
// Capture detailed error information for debugging
Expand Down Expand Up @@ -644,19 +653,53 @@ class WriteFileToolInvocation extends BaseToolInvocation<
}

/**
* Builds the `record_artifact` hint appended to a successful write.
* Builds the artifact-recording note appended to a successful write.
*
* Exported because the string it produces is a CONTRACT with the daemon's
* Exported because the workspacePath it produces is a CONTRACT with the daemon's
* `GET /file` route: the `workspacePath` computed here is later resolved by
* `resolveWithinWorkspace` against the bound workspace root. The two sides live
* in different packages and drifted apart once already (a worktree session
* emitted a worktree-relative path that the route resolved against the
* emitted a session-cwd-relative path that the route resolved against the
* workspace root, so every artifact preview 404'd). `workspace-file-read.test.ts`
* pins the round-trip; keep this exported so it can keep doing so.
*/
export function buildRecordArtifactReminder(
config: Config,
filePath: string,
): string | null {
const workspacePath = getRecordArtifactWorkspacePath(config, filePath);
if (!workspacePath) {
return null;
}
return (
`This file was automatically recorded as a workspace artifact with ` +
`workspacePath "${workspacePath}". No extra artifact registration step ` +
`is needed.`
);
}
Comment on lines +678 to +684

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] This is an unconditional statement of completed fact, but only the daemon/ACP surface actually consumes ToolResult.artifacts — on the others the sentence is false and the model will relay it to the user verbatim.

  • Subagents. write_file is not in EXCLUDED_TOOLS_FOR_SUBAGENTS, so a subagent writing report.html gets both the artifacts array and this sentence. But AgentToolResultEvent has no artifacts field, and SubAgentTracker calls toolCallEmitter.emitResult({...}) without one, so _meta.artifacts is never stamped and extractSessionUpdateArtifacts sees nothing. There is no action=dropped line either — nothing ever reaches the store, so the drop is completely silent. Recovery is closed as well: record_artifact is deliberately excluded from subagents ("V1 session artifacts are owned by the parent daemon session"), and the new record_artifact description tells the parent not to re-record the path.
  • TUI and headless --prompt. isRecordArtifactEnabled() is true on both (it only excludes SDK mode), but the sole reader of ToolCallResponseInfo.artifacts is packages/cli/src/acp-integration/session/Session.ts. There is no artifacts consumer under packages/cli/src/ui.

The previous wording was a conditional imperative — "If this file is a reusable user-facing artifact, call record_artifact…" — which was harmless where nothing consumed it. Asserting a completed action is not.

Worth either gating the sentence on a session that has an artifact consumer, or phrasing it as a capability rather than a finished action, e.g. "recorded for clients that display an artifacts panel".

— claude-opus-5[1m] via Claude Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined. Gating the sentence on a session that has an artifact consumer would require plumbing surface awareness into the write path; softening the wording would churn ~6 test assertions for a non-blocking preference. The maintainer's round-4 verification confirmed comfort with merging as-is.

中文说明

拒绝。按会话类型门控需要在写入路径中引入场景感知;软化措辞会导致约 6 个测试断言的变动,且属于非阻断偏好。维护者第 4 轮验证已确认可按现状合并。


function buildWorkspaceArtifactMetadata(
config: Config,
filePath: string,
sizeBytes?: number,
): ToolArtifact | null {
const workspacePath = getRecordArtifactWorkspacePath(config, filePath);
if (!workspacePath) {
return null;
}
return {
title: path.basename(filePath),
kind: inferWorkspaceArtifactKind(filePath),
storage: 'workspace',
workspacePath,
mimeType: getSpecificMimeType(filePath),
sizeBytes,
};
}

function getRecordArtifactWorkspacePath(
config: Config,
filePath: string,
): string | null {
if (!config.isRecordArtifactEnabled()) {
return null;
Expand All @@ -683,12 +726,27 @@ export function buildRecordArtifactReminder(
) {
return null;
}
const workspacePath = relativePath.split(path.sep).join('/');
return (
`If this file is a reusable user-facing artifact, call ` +
`record_artifact with workspacePath "${workspacePath}" before telling ` +
`the user it is available in the artifacts panel.`
);
return relativePath.split(path.sep).join('/');
}

function inferWorkspaceArtifactKind(filePath: string): ToolArtifactKind {
switch (path.extname(filePath).toLowerCase()) {
Comment thread
chiga0 marked this conversation as resolved.
Resolved
case '.htm':
case '.html':
return 'html';
case '.ipynb':
return 'notebook';
case '.pdf':
return 'pdf';
case '.jpeg':
case '.jpg':
case '.png':
case '.svg':
case '.webp':
return 'image';
default:
return 'file';
}
}

/**
Expand Down
Loading