diff --git a/server/src/__tests__/chat-project-tools.test.ts b/server/src/__tests__/chat-project-tools.test.ts index 80a4ada56de..c759d2ea881 100644 --- a/server/src/__tests__/chat-project-tools.test.ts +++ b/server/src/__tests__/chat-project-tools.test.ts @@ -38,6 +38,32 @@ import { recoveryPostgresSupport as support } from "./helpers/recovery-postgres. } }); + it("links another task's bound workspace page from get_task and call_api reads only while the page exists", async () => { + const f = await server.fixture({ conversation: true, disableWakeOnDemand: true }); + const [{ issuePrefix }] = await server.db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, f.companyId)); + const settings = instanceSettingsService(server.db); + const previous = await settings.getExperimental(); + const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, + mode: "shared_workspace", strategyType: "project_primary", name: "Website files" }).returning(); + const website = await issueService(server.db).create(f.companyId, { title: "Website task", status: "todo" }); + await server.db.update(issues).set({ executionWorkspaceId: workspace!.id }).where(eq(issues.id, website.id)); + const href = `/${issuePrefix}/execution-workspaces/${workspace!.id}`; + const read = async () => { + const task = await call(f, "get_task", { taskId: website.id }) as { data: { currentExecutionWorkspace: { id: string; href?: string } } }; + const view = await call(f, "call_api", { operationId: "GET /api/issues/{id}/workspace", pathParams: { id: website.id } }) as { data: { workspace: { href?: string } } }; + expect(task.data.currentExecutionWorkspace.id).toBe(workspace!.id); + return [task.data.currentExecutionWorkspace.href, view.data.workspace.href]; + }; + try { + await settings.updateExperimental({ enableIsolatedWorkspaces: true }); + expect(await read()).toEqual([href, href]); + await settings.updateExperimental({ enableIsolatedWorkspaces: false }); + expect(await read()).toEqual([undefined, undefined]); + } finally { + await settings.updateExperimental({ enableIsolatedWorkspaces: previous.enableIsolatedWorkspaces }); + } + }); + it("pages only visible projects and prefilters low-trust agent and run scopes", async () => { const f = await server.fixture({ disableWakeOnDemand: true }); const ids = Array.from({ length: 53 }, (_, i) => `abcdefab-0000-4000-8000-${String(i).padStart(12, "0")}`); diff --git a/server/src/__tests__/task-workspace-tools.test.ts b/server/src/__tests__/task-workspace-tools.test.ts index 2ca60b77574..1eba3f3b5c5 100644 --- a/server/src/__tests__/task-workspace-tools.test.ts +++ b/server/src/__tests__/task-workspace-tools.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { callTaskWorkspaceTool } from "../services/task-workspace-tools.js"; +import { apiResultMayHaveWorkspace, callTaskWorkspaceTool, withWorkspacePageHref } from "../services/task-workspace-tools.js"; afterEach(() => vi.unstubAllGlobals()); const base = { apiUrl: "https://paperclip.example/api", token: "run-token", companyId: "company", issueId: "task" }; @@ -61,3 +61,35 @@ describe("task workspace semantic transport", () => { expect(fetcher).toHaveBeenCalledTimes(1); }); }); + +describe("workspace page hrefs on agent API reads", () => { + // The chat agent read another task with get_task (GET /api/issues/{id}); its + // currentExecutionWorkspace had no href, so the agent told the person the + // workspace had no page even though the page was enabled. + const workspace = { id: "ws-1", companyId: "company", name: "COM-1", mode: "shared_workspace", cwd: "/srv/ws" }; + const taskRead = { operationId: "GET /api/issues/{id}", ok: true, status: 200, + data: { id: "task-1", identifier: "COM-1", companyId: "company", currentExecutionWorkspace: workspace } }; + it("links the task's bound workspace page when workspace pages are on", () => { + expect(apiResultMayHaveWorkspace(taskRead)).toBe(true); + expect(withWorkspacePageHref(taskRead, "COM", "company")).toEqual({ ...taskRead, + data: { ...taskRead.data, currentExecutionWorkspace: { ...workspace, href: "/COM/execution-workspaces/ws-1" } } }); + }); + it("links the workspace from the task workspace and workspace detail reads", () => { + expect(withWorkspacePageHref({ operationId: "GET /api/issues/{id}/workspace", ok: true, data: { issueId: "task-1", workspace } }, "COM", "company")) + .toMatchObject({ data: { workspace: { id: "ws-1", href: "/COM/execution-workspaces/ws-1" } } }); + expect(withWorkspacePageHref({ operationId: "GET /api/execution-workspaces/{id}", ok: true, data: workspace }, "COM", "company")) + .toMatchObject({ data: { id: "ws-1", href: "/COM/execution-workspaces/ws-1" } }); + }); + it("adds no href when the page is off, the read failed, or the workspace is not this company's", () => { + expect(withWorkspacePageHref(taskRead, null, "company")).toBe(taskRead); + expect(withWorkspacePageHref({ ...taskRead, ok: false }, "COM", "company")).toEqual({ ...taskRead, ok: false }); + expect(withWorkspacePageHref(taskRead, "COM", "other-company")).toBe(taskRead); + const unbound = { ...taskRead, data: { ...taskRead.data, currentExecutionWorkspace: null } }; + expect(withWorkspacePageHref(unbound, "COM", "company")).toBe(unbound); + }); + it("leaves unrelated reads untouched and skips the page setting for them", () => { + const other = { operationId: "GET /api/issues/{id}/runs", ok: true, data: [{ id: "ws-1", companyId: "company" }] }; + expect(apiResultMayHaveWorkspace(other)).toBe(false); + expect(withWorkspacePageHref(other, "COM", "company")).toBe(other); + }); +}); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index ead8a3c426c..1d51e1f483f 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -22,7 +22,7 @@ import { handoffCaseSchema } from "@paperclipai/shared"; import { skillAccessService } from "../skill-access.js"; import { SKILL_LIBRARY_SCHEMAS, SKILL_LIBRARY_TOOL_DEFINITIONS, SkillLibraryReadCache, executeSkillLibraryTool } from "./native-skill-library-tools.js"; import { withExternalExecutionAdmission, type ExternalAdmissionTransaction } from "../../modules/external-agents/index.js"; -import { callTaskWorkspaceTool, pendingTaskRepositoryContinuation } from "../task-workspace-tools.js"; +import { apiResultMayHaveWorkspace, callTaskWorkspaceTool, pendingTaskRepositoryContinuation, withWorkspacePageHref } from "../task-workspace-tools.js"; import { TaskAttachmentReadCache, TASK_ATTACHMENT_DEFINITIONS, TASK_ATTACHMENT_SCHEMAS, listTaskAttachments, readTaskAttachment } from "./runner-task-attachments.js"; import { RUNNER_BRIDGE_READ_OPERATIONS, RUNNER_BRIDGE_SCHEMAS, runnerBridgeDefinitions, readAssignedSkill, executeWorkspaceTool, readWorkspaceUploadFile, settleRunnerBridgeRead, assertRunnerWorkspacePathAllowed } from "./runner-bridge-tools.js"; import type { NativeRuntimeContextSnapshot } from "../../vendor/paperclip-runner/index.js"; @@ -727,7 +727,7 @@ export class PaperclipRunnerToolAuthority { // read-only options; the shared client still enforces GET-only export. return apiToolResult(await this.#callApi(call.callId, { ...input, saveResponse: true } as RunnerApiCall)); } - return apiToolResult(await this.#callApi(call.callId, taskBridgeApiRequest(call.tool, input))); + return apiToolResult(await this.#withWorkspacePageHref(await this.#callApi(call.callId, taskBridgeApiRequest(call.tool, input)))); } if (this.binding.firstPartyOnly && (call.tool === READ_TOOL_RESULT || this.binding.assignedMcpTools?.has(call.tool) || isConnectorTool(call.tool) || RUNTIME_CONNECTION_TOOL_DEFINITIONS.some(tool => tool.name === call.tool))) throw forbidden("This Grok Bot connection exposes first-party Paperclip operations. Use your own provider apps under their existing permissions."); @@ -925,7 +925,7 @@ export class PaperclipRunnerToolAuthority { // PRP reserves operationId/callId for semantic result identity. The // HTTP operation is metadata, including in previously saved receipts; // exposing it as operationId makes the runner reject a valid response. - return apiToolResult(await this.#callApi(call.callId, call.arguments)); + return apiToolResult(await this.#withWorkspacePageHref(await this.#callApi(call.callId, call.arguments))); } case "get_task_context": { if (this.#apiScope(context).kind === "skill_test") return { @@ -1155,6 +1155,12 @@ export class PaperclipRunnerToolAuthority { ? this.#companyPagePrefix() : null; } + /** Gives workspace reads the same page href get_workspace returns, reading the setting only for those reads. */ + async #withWorkspacePageHref(result: unknown) { + return apiResultMayHaveWorkspace(result) + ? withWorkspacePageHref(result, await this.#workspacePagePrefix(), this.binding.companyId) : result; + } + #apiToken(context: { actor: { adapterType: string }; issue: { workMode: string }; diff --git a/server/src/services/task-workspace-tools.ts b/server/src/services/task-workspace-tools.ts index b06a7eb07eb..e280bfbdda4 100644 --- a/server/src/services/task-workspace-tools.ts +++ b/server/src/services/task-workspace-tools.ts @@ -37,6 +37,41 @@ 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 : null; +} + +/** The API reads that return a workspace, and the field that holds it ("" is the response itself). */ +const WORKSPACE_READ_FIELDS: Readonly> = { + "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(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>, limit: number) { const workspaces: Array> = []; const result = () => ({ workspaces, limit, returnedCount: workspaces.length,