Skip to content

Commit fa30191

Browse files
authored
feat(coder/modules/agentapi): add log snapshot capture on shutdown (#676)
Captures the last 10 messages from AgentAPI when task workspaces stop, allowing users to view conversation history while the task is paused. The shutdown script fetches messages, builds a payload with last 10 messages, truncates to 64KB if needed (removes old messages first, then truncates content of the last message), and posts to the log snapshot endpoint. Gracefully handles non-task workspaces (skips), older Coder versions without the endpoint (logs and continues), and empty message sets. Enabled by default via task_log_snapshot variable. Task ID is automatically resolved from data.coder_task when available. Updates coder/internal#1257
1 parent e4606c5 commit fa30191

7 files changed

Lines changed: 564 additions & 2 deletions

File tree

‎registry/coder/modules/agentapi/README.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ The AgentAPI module is a building block for modules that need to run an AgentAPI
1616
```tf
1717
module "agentapi" {
1818
source = "registry.coder.com/coder/agentapi/coder"
19-
version = "2.0.0"
19+
version = "2.1.0"
2020
2121
agent_id = var.agent_id
2222
web_app_slug = local.app_slug
@@ -49,6 +49,19 @@ module "agentapi" {
4949
}
5050
```
5151

52+
## Task log snapshot
53+
54+
Captures the last 10 messages from AgentAPI when a task workspace stops. This allows viewing conversation history while the task is paused.
55+
56+
To enable for task workspaces:
57+
58+
```tf
59+
module "agentapi" {
60+
# ... other config
61+
task_log_snapshot = true # default: true
62+
}
63+
```
64+
5265
## For module developers
5366

5467
For a complete example of how to use this module, see the [Goose module](https://github.com/coder/registry/blob/main/registry/coder/modules/goose/main.tf).

‎registry/coder/modules/agentapi/main.test.ts‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,4 +257,157 @@ describe("agentapi", async () => {
257257
);
258258
expect(agentApiStartLog).toContain("AGENTAPI_ALLOWED_HOSTS: *");
259259
});
260+
261+
describe("shutdown script", async () => {
262+
const setupMocks = async (
263+
containerId: string,
264+
agentapiPreset: string,
265+
httpCode: number = 204,
266+
) => {
267+
const agentapiMock = await loadTestFile(
268+
import.meta.dir,
269+
"agentapi-mock-shutdown.js",
270+
);
271+
const coderMock = await loadTestFile(
272+
import.meta.dir,
273+
"coder-instance-mock.js",
274+
);
275+
276+
await writeExecutable({
277+
containerId,
278+
filePath: "/usr/local/bin/mock-agentapi",
279+
content: agentapiMock,
280+
});
281+
282+
await writeExecutable({
283+
containerId,
284+
filePath: "/usr/local/bin/mock-coder",
285+
content: coderMock,
286+
});
287+
288+
await execContainer(containerId, [
289+
"bash",
290+
"-c",
291+
`PRESET=${agentapiPreset} nohup node /usr/local/bin/mock-agentapi 3284 > /tmp/mock-agentapi.log 2>&1 &`,
292+
]);
293+
294+
await execContainer(containerId, [
295+
"bash",
296+
"-c",
297+
`HTTP_CODE=${httpCode} nohup node /usr/local/bin/mock-coder 18080 > /tmp/mock-coder.log 2>&1 &`,
298+
]);
299+
300+
await new Promise((resolve) => setTimeout(resolve, 1000));
301+
};
302+
303+
const runShutdownScript = async (
304+
containerId: string,
305+
taskId: string = "test-task",
306+
) => {
307+
const shutdownScript = await loadTestFile(
308+
import.meta.dir,
309+
"../scripts/agentapi-shutdown.sh",
310+
);
311+
312+
await writeExecutable({
313+
containerId,
314+
filePath: "/tmp/shutdown.sh",
315+
content: shutdownScript,
316+
});
317+
318+
return await execContainer(containerId, [
319+
"bash",
320+
"-c",
321+
`ARG_TASK_ID=${taskId} ARG_AGENTAPI_PORT=3284 CODER_AGENT_URL=http://localhost:18080 CODER_AGENT_TOKEN=test-token /tmp/shutdown.sh`,
322+
]);
323+
};
324+
325+
test("posts snapshot with normal messages", async () => {
326+
const { id } = await setup({
327+
moduleVariables: {},
328+
skipAgentAPIMock: true,
329+
});
330+
331+
await setupMocks(id, "normal");
332+
const result = await runShutdownScript(id);
333+
334+
expect(result.exitCode).toBe(0);
335+
expect(result.stdout).toContain("Retrieved 5 messages for log snapshot");
336+
expect(result.stdout).toContain("Log snapshot posted successfully");
337+
338+
const posted = await readFileContainer(id, "/tmp/snapshot-posted.json");
339+
const snapshot = JSON.parse(posted);
340+
expect(snapshot.task_id).toBe("test-task");
341+
expect(snapshot.payload.messages).toHaveLength(5);
342+
expect(snapshot.payload.messages[0].content).toBe("Hello");
343+
expect(snapshot.payload.messages[4].content).toBe("Great");
344+
});
345+
346+
test("truncates to last 10 messages", async () => {
347+
const { id } = await setup({
348+
moduleVariables: {},
349+
skipAgentAPIMock: true,
350+
});
351+
352+
await setupMocks(id, "many");
353+
const result = await runShutdownScript(id);
354+
355+
expect(result.exitCode).toBe(0);
356+
357+
const posted = await readFileContainer(id, "/tmp/snapshot-posted.json");
358+
const snapshot = JSON.parse(posted);
359+
expect(snapshot.task_id).toBe("test-task");
360+
expect(snapshot.payload.messages).toHaveLength(10);
361+
expect(snapshot.payload.messages[0].content).toBe("Message 6");
362+
expect(snapshot.payload.messages[9].content).toBe("Message 15");
363+
});
364+
365+
test("truncates huge message content", async () => {
366+
const { id } = await setup({
367+
moduleVariables: {},
368+
skipAgentAPIMock: true,
369+
});
370+
371+
await setupMocks(id, "huge");
372+
const result = await runShutdownScript(id);
373+
374+
expect(result.exitCode).toBe(0);
375+
expect(result.stdout).toContain("truncating final message content");
376+
377+
const posted = await readFileContainer(id, "/tmp/snapshot-posted.json");
378+
const snapshot = JSON.parse(posted);
379+
expect(snapshot.task_id).toBe("test-task");
380+
expect(snapshot.payload.messages).toHaveLength(1);
381+
expect(snapshot.payload.messages[0].content).toContain(
382+
"[...content truncated",
383+
);
384+
});
385+
386+
test("skips gracefully when TASK_ID is empty", async () => {
387+
const { id } = await setup({
388+
moduleVariables: {},
389+
skipAgentAPIMock: true,
390+
});
391+
392+
const result = await runShutdownScript(id, "");
393+
394+
expect(result.exitCode).toBe(0);
395+
expect(result.stdout).toContain("No task ID, skipping log snapshot");
396+
});
397+
398+
test("handles 404 gracefully for older Coder versions", async () => {
399+
const { id } = await setup({
400+
moduleVariables: {},
401+
skipAgentAPIMock: true,
402+
});
403+
404+
await setupMocks(id, "normal", 404);
405+
const result = await runShutdownScript(id);
406+
407+
expect(result.exitCode).toBe(0);
408+
expect(result.stdout).toContain(
409+
"Log snapshot endpoint not supported by this Coder version",
410+
);
411+
});
412+
});
260413
});

‎registry/coder/modules/agentapi/main.tf‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ terraform {
44
required_providers {
55
coder = {
66
source = "coder/coder"
7-
version = ">= 2.12"
7+
version = ">= 2.13"
88
}
99
}
1010
}
@@ -18,6 +18,8 @@ data "coder_workspace" "me" {}
1818

1919
data "coder_workspace_owner" "me" {}
2020

21+
data "coder_task" "me" {}
22+
2123
variable "web_app_order" {
2224
type = number
2325
description = "The order determines the position of app in the UI presentation. The lowest order is shown first and apps with equal order are sorted by name (ascending order)."
@@ -126,6 +128,12 @@ variable "agentapi_port" {
126128
default = 3284
127129
}
128130

131+
variable "task_log_snapshot" {
132+
type = bool
133+
description = "Capture last 10 messages when workspace stops for offline viewing while task is paused."
134+
default = true
135+
}
136+
129137
locals {
130138
# agentapi_subdomain_false_min_version_expr matches a semantic version >= v0.3.3.
131139
# Initial support was added in v0.3.1 but configuration via environment variable
@@ -173,6 +181,7 @@ locals {
173181
// for backward compatibility.
174182
agentapi_chat_base_path = var.agentapi_subdomain ? "" : "/@${data.coder_workspace_owner.me.name}/${data.coder_workspace.me.name}.${var.agent_id}/apps/${var.web_app_slug}/chat"
175183
main_script = file("${path.module}/scripts/main.sh")
184+
shutdown_script = file("${path.module}/scripts/agentapi-shutdown.sh")
176185
}
177186

178187
resource "coder_script" "agentapi" {
@@ -198,11 +207,32 @@ resource "coder_script" "agentapi" {
198207
ARG_POST_INSTALL_SCRIPT="$(echo -n '${local.encoded_post_install_script}' | base64 -d)" \
199208
ARG_AGENTAPI_PORT='${var.agentapi_port}' \
200209
ARG_AGENTAPI_CHAT_BASE_PATH='${local.agentapi_chat_base_path}' \
210+
ARG_TASK_ID='${try(data.coder_task.me.id, "")}' \
211+
ARG_TASK_LOG_SNAPSHOT='${var.task_log_snapshot}' \
201212
/tmp/main.sh
202213
EOT
203214
run_on_start = true
204215
}
205216

217+
resource "coder_script" "agentapi_shutdown" {
218+
agent_id = var.agent_id
219+
display_name = "AgentAPI Shutdown"
220+
icon = var.web_app_icon
221+
run_on_stop = true
222+
script = <<-EOT
223+
#!/bin/bash
224+
set -o pipefail
225+
226+
echo -n '${base64encode(local.shutdown_script)}' | base64 -d > /tmp/agentapi-shutdown.sh
227+
chmod +x /tmp/agentapi-shutdown.sh
228+
229+
ARG_TASK_ID='${try(data.coder_task.me.id, "")}' \
230+
ARG_TASK_LOG_SNAPSHOT='${var.task_log_snapshot}' \
231+
ARG_AGENTAPI_PORT='${var.agentapi_port}' \
232+
/tmp/agentapi-shutdown.sh
233+
EOT
234+
}
235+
206236
resource "coder_app" "agentapi_web" {
207237
slug = var.web_app_slug
208238
display_name = var.web_app_display_name

0 commit comments

Comments
 (0)