Files
PaperClipAI/server/src/services/task-workspace-tools.ts
T
DottaandClaude Opus 5.5 f7ddab8e94 fix(runner): give agent task and workspace reads the workspace page href (#21384)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People ask a chat agent where the files of a task are.
> - The answer must link the page of the workspace that holds the task's
files, when that page exists.
> - The agent reads the task with `get_task`. The task's
`currentExecutionWorkspace` had no `href`.
> - The chat directive tells the agent that a workspace without an
`href` has no page. So the agent said the page did not exist, although
isolated workspaces were on.
> - This pull request adds the workspace page `href` to the agent's task
and workspace reads, as `get_workspace` already does.
> - The benefit is that the agent links the real workspace page and does
not make a false claim.

## Linked Issues or Issue Description

**What happened?**
A person asked the CEO chat agent: "Where are the files for the website
task actually being worked on?" The agent named the task workspace and
linked the file. It did not link the workspace page. It also said "the
workspace has no separate page on this instance". The instance had
isolated workspaces on, so the page existed at
`/<prefix>/execution-workspaces/<id>`. The chat eval
`chat-features.runner-opencode.local.workspaces.locate-files` (OpenCode,
`openrouter/deepseek/deepseek-v4.1-flash-1017`) failed its
`bound-workspace-page-link` check in four cohorts and in one more paid
run for this reason.

**Expected behavior**
The agent reads the task, gets the workspace page link from the tool
result, and links that page in its reply.

**Steps to reproduce**

1. Turn on isolated workspaces (`enableIsolatedWorkspaces`).
2. Let an agent complete a projectless task, so the task has a bound
execution workspace.
3. In a different chat, ask the CEO where the files of that task are.
4. The agent calls `get_task` for the task.
`data.currentExecutionWorkspace` has no `href`. The agent reply names
the workspace and says it has no page.

**Additional context**
`get_workspace` and `list_workspaces` add the page `href` only for the
current task. The agent reads another task with `get_task` (`GET
/api/issues/{id}`) or with `call_api`. Those results did not get the
`href`. The run transcript shows the agent's reasoning: "The task API
includes currentExecutionWorkspace with no href", followed by the
directive rule "a workspace without an href has no page on this
instance".

## What Changed

- `server/src/services/task-workspace-tools.ts`: add
`withWorkspacePageHref` and `apiResultMayHaveWorkspace`. They add the
page `href` to the workspace in successful agent reads of `GET
/api/issues/{id}` (`currentExecutionWorkspace`), `GET
/api/issues/{id}/workspace` (`workspace`) and `GET
/api/execution-workspaces/{id}`. The function uses the same `href`
builder as `get_workspace`. It adds no `href` when the page is off, when
the read failed, or when the workspace is in a different company.
-
`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`:
apply the function to the results of the task bridge tools (`get_task`)
and `call_api`. The tool authority reads the page setting only for these
three operations.
- Tests: unit tests for the function, and an integration test through
the real tool authority and API. The integration test checks `get_task`
and `call_api` with workspace pages on (the `href` is present) and off
(no `href`).

## Verification

- Red/green: with the base tool authority, the new integration test
fails (`undefined` instead of `/<prefix>/execution-workspaces/<id>` for
both reads). With the fix, it passes. The unit tests fail on the base (4
failures) and pass with the fix.
- `cd server && npx vitest run src/__tests__/chat-project-tools.test.ts
src/__tests__/task-workspace-tools.test.ts
src/__tests__/agent-conversations.test.ts`: 110 passed.
- `cd server && npx tsc --noEmit -p .`: passes.
- Latency: the change runs only when the agent calls one of the three
reads. It does not touch run boot or time to first token. Local
`get_task` timing through the tool authority, 40 calls per sample, pages
on: base p50 51 ms and 74 ms; fix p50 49 ms and 54 ms. The difference is
in the noise.
- Paid eval: one narrow run of
`chat-features.runner-opencode.local.workspaces.locate-files` on this
branch:
https://github.com/paperclipai/paperclip/actions/runs/43436040405
(result in a comment below).

## Risks

- Low risk. The change only adds an `href` field to three agent read
results. It does not change REST responses for the board UI.
- The `href` appears only while isolated workspaces are on, because the
page route exists only then. This is the same rule `get_workspace` uses.
- An agent can now link a workspace page that it read through
`get_task`. The page itself still applies normal board access checks.

## Model Used

- Claude, Anthropic, model ID `claude-opus-5-5`, used through Claude
Code with tool use (shell, file edits, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:16:44 -06:00

141 lines
8.1 KiB
TypeScript

import { listTaskWorkspacesSchema, prepareWorkspaceRepositorySchema, selectTaskWorkspaceSchema } from "@paperclipai/shared";
import { badRequest } from "../errors.js";
import { executionWorkspaceRepositories, type Db } from "@paperclipai/db";
import { and, asc, eq, inArray } from "drizzle-orm";
export async function pendingTaskRepository(db: Pick<Db, "select">, input: {
companyId: string; issueId: string; workspaceId: string | null; repositoryIds?: string[];
}) {
if (input.repositoryIds?.length === 0) return null;
if (!input.workspaceId) return null;
const [repository] = await db.select({ id: executionWorkspaceRepositories.id }).from(executionWorkspaceRepositories)
.where(and(eq(executionWorkspaceRepositories.companyId, input.companyId),
eq(executionWorkspaceRepositories.executionWorkspaceId, input.workspaceId),
eq(executionWorkspaceRepositories.requestedByIssueId, input.issueId),
eq(executionWorkspaceRepositories.state, "pending"),
...(input.repositoryIds ? [inArray(executionWorkspaceRepositories.id, input.repositoryIds)] : [])))
.orderBy(asc(executionWorkspaceRepositories.createdAt), asc(executionWorkspaceRepositories.id)).limit(1);
return repository ?? null;
}
export async function pendingTaskRepositoryContinuation(db: Pick<Db, "select">, input: {
companyId: string; issueId: string; runId: string; workspaceId: string | null;
}) {
const repository = await pendingTaskRepository(db, input);
return repository ? { kind: "same_agent" as const, summary: "Continue with the prepared task repository.",
idempotencyKey: `task-repository:${input.issueId}:${repository.id}:${input.runId}` } : null;
}
function repositoryView(repo: Record<string, unknown>) {
return { id: repo.id, repoUrl: repo.repoUrl, relativePath: repo.relativePath, requestedRef: repo.requestedRef,
state: repo.state, pinnedCommit: repo.pinnedCommit, branchName: repo.branchName };
}
/** The workspace detail page exists only while isolated workspaces are enabled,
* so callers pass the company prefix only then; a missing href means no page. */
function workspaceHref(prefix: string | null | undefined, id: unknown) {
return prefix && typeof id === "string" ? { href: `/${encodeURIComponent(prefix)}/execution-workspaces/${encodeURIComponent(id)}` } : {};
}
function objectOrNull(value: unknown) {
return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : null;
}
/** The API reads that return a workspace, and the field that holds it ("" is the response itself). */
const WORKSPACE_READ_FIELDS: Readonly<Record<string, string>> = {
"GET /api/issues/{id}": "currentExecutionWorkspace",
"GET /api/issues/{id}/workspace": "workspace",
"GET /api/execution-workspaces/{id}": "",
};
/** True when an agent API result may hold a workspace, so the page prefix is read only then. */
export function apiResultMayHaveWorkspace(result: unknown) {
const operationId = objectOrNull(result)?.operationId;
return typeof operationId === "string" && Object.hasOwn(WORKSPACE_READ_FIELDS, operationId);
}
/**
* Adds the workspace page href to an agent's API read of a task or workspace,
* as get_workspace does. Without it the agent reads the missing href as "this
* workspace has no page" and names the workspace instead of linking it.
*/
export function withWorkspacePageHref<T>(result: T, prefix: string | null | undefined, companyId: string): T {
const response = objectOrNull(result);
const operationId = response?.operationId;
const data = objectOrNull(response?.data);
if (!prefix || !response || response.ok !== true || !data || typeof operationId !== "string"
|| !Object.hasOwn(WORKSPACE_READ_FIELDS, operationId)) return result;
const field = WORKSPACE_READ_FIELDS[operationId]!;
const workspace = field ? objectOrNull(data[field]) : data;
if (!workspace || workspace.companyId !== companyId || typeof workspace.id !== "string") return result;
const linked = { ...workspace, ...workspaceHref(prefix, workspace.id) };
return { ...response, data: field ? { ...data, [field]: linked } : linked } as T;
}
function workspacePage(rows: Array<Record<string, unknown>>, limit: number) {
const workspaces: Array<Record<string, unknown>> = [];
const result = () => ({ workspaces, limit, returnedCount: workspaces.length,
hasMore: rows.length > workspaces.length,
nextCursor: rows.length > workspaces.length ? workspaces.at(-1)!.id : null });
for (const row of rows.slice(0, limit)) {
workspaces.push(row);
if (Buffer.byteLength(JSON.stringify(result())) <= 128 * 1024) continue;
workspaces.pop();
if (workspaces.length === 0) {
const preview = { ...row };
const truncatedFields: string[] = [];
for (const [key, value] of Object.entries(row)) {
if (typeof value !== "string") continue;
const text = Array.from(value.slice(0, 2048)).slice(0, 1024).join("");
if (text === value) continue;
preview[key] = text;
truncatedFields.push(key);
}
workspaces.push({ ...preview, truncatedFields });
}
break;
}
return result();
}
export async function callTaskWorkspaceTool(input: { name: string; arguments: Record<string, unknown>; apiUrl: string; token: string; companyId: string; issueId: string; workspaceRoot?: string; workspacePagePrefix?: string | null }) {
let route = `/issues/${input.issueId}/workspace`;
let method = "GET";
let body: unknown;
const page = input.name === "list_workspaces" ? listTaskWorkspacesSchema.parse(input.arguments) : null;
switch (input.name) {
case "get_workspace": break;
case "list_workspaces": {
const query = new URLSearchParams({ summary: "true", selectableForTask: "true", limit: String(page!.limit + 1) });
if (page!.cursor) query.set("cursor", page!.cursor);
route = `/companies/${input.companyId}/execution-workspaces?${query}`;
break;
}
case "select_workspace": method = "PUT"; body = selectTaskWorkspaceSchema.parse(input.arguments); break;
case "prepare_repository": method = "POST"; route += "/repositories"; body = prepareWorkspaceRepositorySchema.parse(input.arguments); break;
default: throw badRequest("Unknown workspace tool");
}
const response = await fetch(`${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api${route}`, { method, headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json" }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(60_000) });
const result = await response.json();
if (!response.ok) throw new Error(typeof result.error === "string" ? result.error : `Workspace tool failed (${response.status})`);
if (page) {
return workspacePage(result.map((row: Record<string, unknown>) => ({ ...row, ...workspaceHref(input.workspacePagePrefix, row.id) })), page.limit);
}
if (input.name === "prepare_repository") {
const { operationId, ...rest } = result;
return { ...rest, ...(result.repository ? { repository: repositoryView(result.repository) } : {}), preparationId: operationId,
...(result.kind === "requires_next_admission" ? { instruction: "The repository is staged for the next admission. If unfinished work needs this checkout, finish independent work, then call paperclip_finish with reportedWorkDisposition=\"yielded\" and omit continuation (or use null). Paperclip will select the saved workspace continuation. Repository admission is routine setup; do not call paperclip_block or ask the user to restart. No timer is needed." } : {}),
};
}
if (input.name === "get_workspace") {
const workspace = result.workspace;
return { issueId: result.issueId, bindingRevision: result.bindingRevision, selection: result.selection,
pendingSelection: result.pendingSelection, cwd: input.workspaceRoot ?? null,
workspace: workspace ? { id: workspace.id, projectId: workspace.projectId, mode: workspace.mode, status: workspace.status,
...workspaceHref(input.workspacePagePrefix, workspace.id) } : null,
repositories: (result.repositories ?? []).map(repositoryView),
capabilities: result.capabilities, fileLocations: result.fileLocations };
}
return result;
}