Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 16 additions & 22 deletions packages/sdk-typescript/src/daemon/DaemonClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1798,22 +1798,21 @@ export class DaemonClient {
} = {},
clientId?: string,
): Promise<DaemonWorkspaceFile> {
const url = new URL(`${this.baseUrl}/file`);
url.searchParams.set('path', filePath);
const query = new URLSearchParams({ path: filePath });
if (opts.maxBytes !== undefined) {
url.searchParams.set('maxBytes', String(opts.maxBytes));
query.set('maxBytes', String(opts.maxBytes));
}
Comment on lines 1802 to 1804

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4c7da78 — and thank you for the mutation probe, it reproduced exactly.

Baseline on this branch: 35 files, 1659/1659 passed. Deleting the maxBytes branch from readWorkspaceFile leaves that identical — 35 files, 1659/1659 — so the branch really was invisible to the suite.

Worth noting why it hid: maxBytes does appear in two existing assertions (lines 578 and 602), but both belong to readWorkspaceFileBytes hitting GET /file/bytes. Different method, different endpoint. Of the four optional params readWorkspaceFile serialises, cursor is covered at line 533 and line/limit by the new relative-base test — maxBytes was the only one nothing pinned on either base URL.

The relative-base test now asserts a second call carrying it:

await expect(
  client.readWorkspaceFile('src/a.ts', { maxBytes: 100, line: 2, limit: 3 }),
).resolves.toEqual(payload);
expect(calls[1]?.url).toBe(
  '/daemon/file?path=src%2Fa.ts&maxBytes=100&line=2&limit=3',
);

I kept the original { line: 2, limit: 3 } assertion rather than replacing it, so the omitted case still proves the branch is conditional.

Re-running the same mutation with this in place now fails:

AssertionError: expected '/daemon/file?path=src%2Fa.ts&line=2&l…'
                to be '/daemon/file?path=src%2Fa.ts&maxBytes…'
Test Files  1 failed (1)
Tests  1 failed | 353 passed (354)

Full suite green with the branch restored: 35 files, 1659/1659.

中文说明

已在 4c7da78 中修复——感谢提供变异测试探针,本地完全复现。

本分支基线:35 files, 1659/1659 passed。从 readWorkspaceFile 中删除 maxBytes 分支后结果完全相同——35 files、1659/1659,说明该分支确实未被测试覆盖。

补充一点它为何被漏掉:maxBytes 确实出现在现有的两处断言中(第 578、602 行),但它们属于 readWorkspaceFileBytes 请求的 GET /file/bytes——方法不同,端点也不同。readWorkspaceFile 序列化的四个可选参数中,cursor 由第 533 行覆盖,line/limit 由新增的相对 base URL 测试覆盖,只有 maxBytes 在两种 base URL 下都无测试锚定。

相对 base URL 的测试现在增加了一次携带该参数的调用断言,并保留了原有的 { line: 2, limit: 3 } 断言,以便同时验证该分支是条件生效的。

在此改动下重跑同一变异测试会失败;恢复分支后全量测试通过:35 files、1659/1659。

if (opts.line !== undefined) {
url.searchParams.set('line', String(opts.line));
query.set('line', String(opts.line));
}
if (opts.limit !== undefined) {
url.searchParams.set('limit', String(opts.limit));
query.set('limit', String(opts.limit));
}
if (opts.cursor !== undefined) {
url.searchParams.set('cursor', opts.cursor);
query.set('cursor', opts.cursor);
}
return await this.fetchWithTimeout(
url.toString(),
`${this.baseUrl}/file?${query.toString()}`,
{ headers: this.headers({}, clientId) },
async (res) => {
if (!res.ok) throw await this.failOnError(res, 'GET /file');
Expand Down Expand Up @@ -1845,10 +1844,9 @@ export class DaemonClient {
}

async fileStat(filePath: string): Promise<unknown> {
const url = new URL(`${this.baseUrl}/stat`);
url.searchParams.set('path', filePath);
const query = new URLSearchParams({ path: filePath });
Comment on lines 1846 to +1847

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed on the diagnosis, and I'd rather not take it in this PR — reasoning below, happy to be overruled.

You're right that the duplication is what caused this: #9734 fixed one copy, six were left behind, and #9816 is the bill for that. A helper is the correct end state.

Two reasons to do it separately:

  1. It would widen the blast radius past the fix. Consolidating means touching readWorkspaceFileBytes too, which this PR doesn't otherwise modify and which is the one site that was already correct. A regression there would be caused by the cleanup, not by the bug — and it'd land in a PR whose stated scope is "make the six broken siblings work with a relative base."

  2. jsonRequest isn't a drop-in for all five. You scoped that carefully — "the bodyless GET-JSON path" — and that's right, but the five methods don't share a response shape or error string (GET /file, GET /stat, GET /list, GET /glob each call failOnError with their own label, and workspacePathSuggestions has a distinct !res.ok branch). Routing them through jsonRequest is a real refactor with its own test surface, not a mechanical extraction.

The smaller requestUrl(path, query) helper you sketched is the part I'd take first — it's mechanical, covers all seven sites, and closes the "any site missed ships broken" hole without touching response handling. Say the word and I'll open it as a follow-up against main once this lands, so the two are reviewable independently and the fix isn't gated on the cleanup.

中文说明

同意你的判断,但我倾向于不在本 PR 中处理——理由如下,如有异议我可以照办。

重复代码确实是根因:#9734 只修复了一处,遗留了六处,#9816 就是代价。抽取 helper 是正确的最终形态。

分开处理的两个理由:

  1. 会把影响面扩大到修复范围之外。 合并意味着还要改动 readWorkspaceFileBytes,而本 PR 并未涉及该方法,且它本就是唯一正确的一处。若在那里引入回归,原因将是这次清理而非原缺陷。

  2. jsonRequest 并非五处都能直接套用。 你的限定很准确——"无 body 的 GET-JSON 路径"——但这五个方法的响应结构和错误信息并不一致(GET /file、GET /stat、GET /list、GET /glob 各自以不同标签调用 failOnError,而 workspacePathSuggestions 有独立的 !res.ok 分支)。改用 jsonRequest 是一次带有独立测试面的真实重构,而非机械抽取。

你给出的较小的 requestUrl(path, query) helper 是我会优先采纳的部分:它是机械性的,可覆盖全部七处,且无需触碰响应处理。若你同意,本 PR 合并后我会针对 main 单独提交后续 PR,使二者可独立审查,修复也不必被清理工作阻塞。

return await this.fetchWithTimeout(
url.toString(),
`${this.baseUrl}/stat?${query.toString()}`,
{ headers: this.headers() },
async (res) => {
if (!res.ok) throw await this.failOnError(res, 'GET /stat');
Expand All @@ -1858,10 +1856,9 @@ export class DaemonClient {
}

async dirList(dirPath: string): Promise<unknown> {
const url = new URL(`${this.baseUrl}/list`);
url.searchParams.set('path', dirPath);
const query = new URLSearchParams({ path: dirPath });
return await this.fetchWithTimeout(
url.toString(),
`${this.baseUrl}/list?${query.toString()}`,
{ headers: this.headers() },
async (res) => {
if (!res.ok) throw await this.failOnError(res, 'GET /list');
Expand All @@ -1875,10 +1872,9 @@ export class DaemonClient {
* pick a path outside any registered workspace (e.g. "Add workspace").
*/
async workspacePathSuggestions(prefix: string): Promise<unknown> {
const url = new URL(`${this.baseUrl}/workspace-path-suggestions`);
url.searchParams.set('prefix', prefix);
const query = new URLSearchParams({ prefix });
return await this.fetchWithTimeout(
url.toString(),
`${this.baseUrl}/workspace-path-suggestions?${query.toString()}`,
{ headers: this.headers() },
async (res) => {
if (!res.ok) {
Expand All @@ -1903,10 +1899,9 @@ export class DaemonClient {
}

async glob(pattern: string): Promise<unknown> {
const url = new URL(`${this.baseUrl}/glob`);
url.searchParams.set('pattern', pattern);
const query = new URLSearchParams({ pattern });
return await this.fetchWithTimeout(
url.toString(),
`${this.baseUrl}/glob?${query.toString()}`,
{ headers: this.headers() },
async (res) => {
if (!res.ok) throw await this.failOnError(res, 'GET /glob');
Expand Down Expand Up @@ -1970,9 +1965,8 @@ export class DaemonClient {
req: DaemonWorkspaceFileUploadRequest,
clientId?: string,
): Promise<DaemonWorkspaceFileUploadResult> {
const target = new URL(`${this.baseUrl}${uploadPath}`);
target.searchParams.set('path', req.path);
const url = target.toString();
const query = new URLSearchParams({ path: req.path });
const url = `${this.baseUrl}${uploadPath}?${query.toString()}`;
const headers = this.headers(
{ 'Content-Type': 'application/octet-stream' },
clientId,
Expand Down
84 changes: 84 additions & 0 deletions packages/sdk-typescript/test/unit/DaemonClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,90 @@ describe('DaemonClient', () => {
);
});

it('reads text files with a relative base URL', async () => {
const payload = {
kind: 'file',
path: 'src/a.ts',
content: 'export {}\n',
encoding: 'utf-8',
bom: false,
lineEnding: 'lf',
sizeBytes: 10,
returnedBytes: 10,
truncated: false,
hash: 'sha256:' + 'a'.repeat(64),
matchedIgnore: null,
originalLineCount: null,
};
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(
client.readWorkspaceFile('src/a.ts', { line: 2, limit: 3 }),
).resolves.toEqual(payload);
expect(calls[0]?.url).toBe('/daemon/file?path=src%2Fa.ts&line=2&limit=3');
});

it('stats files with a relative base URL', async () => {
const payload = { kind: 'stat', path: 'src/a.ts', sizeBytes: 10 };
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(client.fileStat('src/a.ts')).resolves.toEqual(payload);
expect(calls[0]?.url).toBe('/daemon/stat?path=src%2Fa.ts');
});

it('lists directories with a relative base URL', async () => {
const payload = { kind: 'list', path: 'src', entries: [] };
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(client.dirList('src')).resolves.toEqual(payload);
expect(calls[0]?.url).toBe('/daemon/list?path=src');
});

it('suggests workspace paths with a relative base URL', async () => {
const payload = { suggestions: [] };
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(
client.workspacePathSuggestions('/home/user'),
).resolves.toEqual(payload);
expect(calls[0]?.url).toBe(
'/daemon/workspace-path-suggestions?prefix=%2Fhome%2Fuser',
);
});

it('globs with a relative base URL', async () => {
const payload = { matches: [] };
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(client.glob('**/*.ts')).resolves.toEqual(payload);
expect(calls[0]?.url).toBe('/daemon/glob?pattern=**%2F*.ts');
});

it('uploads files with a relative base URL', async () => {
const payload = {
kind: 'file_upload' as const,
path: 'bin.dat',
sizeBytes: 2,
hash: 'sha256:' + 'a'.repeat(64),
};
const { fetch, calls } = recordingFetch(() => jsonResponse(200, payload));
const client = new DaemonClient({ baseUrl: '/daemon', fetch });

await expect(
client.uploadWorkspaceFile({
path: 'bin.dat',
data: new Uint8Array([1, 2]),
}),
).resolves.toEqual(payload);
expect(calls[0]?.method).toBe('POST');
expect(calls[0]?.url).toBe('/daemon/file/upload?path=bin.dat');
});

it('writes and edits files with JSON bodies and client identity', async () => {
const writeResult = {
kind: 'file_write',
Expand Down
Loading