Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(tasks): serve task chats a log without the duplicate tool response copy (#120766)

Shy Alter7c1af4d6f926
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ae5145ec85b4..3954296073f6 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -221,6 +221,7 @@ import type {
GitHubReposResponseApi,
} from 'products/integrations/frontend/generated/api.schemas'
import type { LogExplanation } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/ExploreWithAI/types'
+import type { TasksRunsLogsRetrieveParams } from 'products/logs/frontend/generated/api.schemas'
import type { NotebookCollabCursorApi } from 'products/notebooks/frontend/generated/api.schemas'
import type { Task, TaskListParams, TaskRun, TaskUpsertProps } from 'products/posthog_ai/frontend/types/taskTypes'
import type {
@@ -5079,6 +5080,7 @@ const api = {
tailBytes?: number
before?: number
start?: number
+ view?: TasksRunsLogsRetrieveParams['view']
}
): Promise<{
entries: Record<string, any>[]
@@ -5096,6 +5098,7 @@ const api = {
...(options.tailBytes !== undefined ? { tail_bytes: options.tailBytes } : {}),
...(options.before !== undefined ? { before: options.before } : {}),
...(options.start !== undefined ? { start: options.start } : {}),
+ ...(options.view ? { view: options.view } : {}),
})
.getResponse({ signal: options.signal })
const entries = parseLogEntries(await response.text())
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 865e82c32b55..28805dadb27f 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -3605,4 +3605,19 @@ export type TasksRunsLogsRetrieveParams = {
* @minimum 1
*/
tail_bytes?: number
+ /**
+ * 'full' returns every entry as stored. 'thread' drops the duplicate tool response copy in _meta.claudeCode.toolResponse and keeps only its decisionReason and message, for clients that render the conversation. It applies to the full log and to every slice.
+ *
+ * * `full` - full
+ * * `thread` - thread
+ * @minLength 1
+ */
+ view?: TasksRunsLogsRetrieveView
}
+
+export type TasksRunsLogsRetrieveView = (typeof TasksRunsLogsRetrieveView)[keyof typeof TasksRunsLogsRetrieveView]
+
+export const TasksRunsLogsRetrieveView = {
+ Full: 'full',
+ Thread: 'thread',
+} as const
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index ad6de8ad0f1b..ee706ca09584 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -1333,7 +1333,7 @@ export const getTasksRunsLogsRetrieveUrl = (
}
/**
- * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history. A resumed Pi run includes the earlier runs of its task session the same way, each preceded by a pi_run_started entry that names its run. For a live presence-gated run, the request marks the stream as watched before it reads the log, so events after the snapshot reach the live stream. Pass tail_bytes to read only the latest turns first, add before to page back through older turns, or add start to read every entry after the ones a client holds. X-Log-Origin names the first run of the chain: indexes from responses with different origins do not match. A Pi run returns its full log without the X-Log headers.
+ * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history. A resumed Pi run includes the earlier runs of its task session the same way, each preceded by a pi_run_started entry that names its run. For a live presence-gated run, the request marks the stream as watched before it reads the log, so events after the snapshot reach the live stream. Pass tail_bytes to read only the latest turns first, add before to page back through older turns, or add start to read every entry after the ones a client holds. X-Log-Origin names the first run of the chain: indexes from responses with different origins do not match. A Pi run returns its full log without the X-Log headers. Pass view=thread to drop the duplicate tool response copy that a rendered conversation does not use.
* @summary Get task run logs
*/
export const tasksRunsLogsRetrieve = async (
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index c1200a131e88..2358841a1233 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -2845,6 +2845,11 @@ describe('runStreamLogic', () => {
expect(logic.values.hasThreadItems).toBe(false)
expect(logic.values.bootstrapLoading).toBe(false)
+ expect(api.tasks.runs.getLogPage).toHaveBeenCalledWith(
+ 'task-1',
+ 'run-1',
+ expect.objectContaining({ view: 'thread' })
+ )
})
it('stores bootstrap errors for inline task-run error UI', async () => {
@@ -3667,6 +3672,33 @@ describe('runStreamLogic', () => {
expect(recovered.entries.map(({ entry }) => entry)).toEqual(entries.map(({ entry }) => entry))
})
+ it('recognizes a legacy tool update whose history copy has the tool response reduced', async () => {
+ const toolEvent = jest.fn()
+ toolStreamEventsLogic.actions.registerToolListener('reduced-history', { tools: '*', onEvent: toolEvent })
+ const call = sessionUpdate({
+ sessionUpdate: 'tool_call',
+ toolCallId: 'tool-1',
+ title: 'Run',
+ status: 'pending',
+ })
+ const update = (toolResponse?: Record<string, unknown>): StoredLogEntry =>
+ sessionUpdate({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'tool-1',
+ status: 'completed',
+ _meta: { claudeCode: { toolName: 'Bash', ...(toolResponse ? { toolResponse } : {}) } },
+ })
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([call, update()] as any)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+
+ await MockStream.latest().emitMessage(call, 'log-0')
+ await MockStream.latest().emitMessage(update({ stdout: 'output', stderr: '' }), 'log-1')
+ await flushPromises()
+
+ expect(toolEvent.mock.calls.map(([event]) => event.phase)).toEqual([])
+ })
+
it.each([false, true])(
'deduplicates late legacy backlog while preserving repeated live output: history first %s',
async (historyFirst) => {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index a533466b05b6..078e516841dd 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -1236,6 +1236,30 @@ function isAgentMessageEntry(entry: StoredLogEntry): boolean {
)
}
+const KEPT_TOOL_RESPONSE_FIELDS = ['decisionReason', 'message'] as const
+
+export function reduceToolResponseCopy(entry: StoredLogEntry): void {
+ const update = entry.notification.params?.update
+ const meta = isRecord(update) ? update._meta : undefined
+ const claudeCode = isRecord(meta) ? meta.claudeCode : undefined
+ if (!isRecord(claudeCode) || !('toolResponse' in claudeCode)) {
+ return
+ }
+ const toolResponse = claudeCode.toolResponse
+ const kept = Object.fromEntries(
+ isRecord(toolResponse)
+ ? KEPT_TOOL_RESPONSE_FIELDS.flatMap((key) =>
+ typeof toolResponse[key] === 'string' ? [[key, toolResponse[key]]] : []
+ )
+ : []
+ )
+ if (Object.keys(kept).length > 0) {
+ claudeCode.toolResponse = kept
+ } else {
+ delete claudeCode.toolResponse
+ }
+}
+
function persistedHumanText(entry: StoredLogEntry): string | null {
if (entry.notification.method === '_posthog/user_message') {
return unwrapUserMessageContent(extractUserMessageText(entry.notification.params?.content))
@@ -1539,7 +1563,7 @@ export function readFullThread(
if (!logic || !cursor || cursor.offset === 0 || !taskId || projectId == null) {
return null
}
- return api.tasks.runs.getLogPage(taskId, cursor.runId, { projectId }).then((page) => {
+ return api.tasks.runs.getLogPage(taskId, cursor.runId, { projectId, view: 'thread' }).then((page) => {
const history = normalizeHistory(page.entries, cursor.runId, logic.values.isBootstrapResumeRun)
const tail = logic.values.log.entries.filter(({ source }) => source !== 'replay')
const folded = foldLogToThread(reconcileRunLog(history, tail, []).entries, {
@@ -4152,6 +4176,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
api.tasks.runs.getLogPage(session.taskId, session.runId, {
signal,
projectId: session.projectId,
+ view: 'thread',
...(values.pagedHistory ? { tailBytes: HISTORY_TAIL_BYTES, start } : {}),
})
const stopHistoryPaging = (): void => {
@@ -4999,6 +5024,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
...parsed,
source_run_id: parsed.source_run_id ?? (id?.startsWith('log-') ? backlogRunId : runId),
}
+ reduceToolResponseCopy(entry)
const backlogIndex = id?.startsWith('log-') ? Number(id.slice('log-'.length)) : NaN
if (Number.isSafeInteger(backlogIndex)) {
backlogIndexes.set(entry, backlogIndex)
@@ -5777,6 +5803,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
projectId,
tailBytes: HISTORY_PAGE_BYTES,
before: cursor.offset,
+ view: 'thread',
})
const current = owned()
if (!current) {
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2a4009a14c55..3569bb3930c0 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -367,6 +367,7 @@ __all__ = [
"get_task_run_log_size",
"read_task_run_log_content",
"read_task_run_conversation_logs",
+ "thread_view_of_log_content",
"read_task_run_conversation_log_slice",
"mark_task_run_stream_watched",
"read_task_run_logs",
@@ -5248,6 +5249,44 @@ def mark_task_run_stream_watched(run_id: str | UUID, task_id: str | UUID, team_i
logger.warning("task_run_stream_mark_watched_failed run_id=%s", info.id, exc_info=True)
+_KEPT_TOOL_RESPONSE_FIELDS = ("decisionReason", "message")
+
+
+def _drop_tool_response_copy(entry: object) -> bool:
+ notification = entry.get("notification") if isinstance(entry, dict) else None
+ params = notification.get("params") if isinstance(notification, dict) else None
+ update = params.get("update") if isinstance(params, dict) else None
+ meta = update.get("_meta") if isinstance(update, dict) else None
+ claude_code = meta.get("claudeCode") if isinstance(meta, dict) else None
+ if not isinstance(claude_code, dict) or "toolResponse" not in claude_code:
+ return False
+ tool_response = claude_code["toolResponse"]
+ kept = (
+ {key: tool_response[key] for key in _KEPT_TOOL_RESPONSE_FIELDS if isinstance(tool_response.get(key), str)}
+ if isinstance(tool_response, dict)
+ else {}
+ )
+ if kept:
+ claude_code["toolResponse"] = kept
+ else:
+ del claude_code["toolResponse"]
+ return True
+
+
+def thread_view_of_log_content(log_content: str) -> str:
+ lines = log_content.split("\n")
+ for index, line in enumerate(lines):
+ if '"toolResponse"' not in line:
+ continue
+ try:
+ entry = json.loads(line)
+ except ValueError:
+ continue
+ if _drop_tool_response_copy(entry):
+ lines[index] = json.dumps(entry, separators=(",", ":"))
+ return "\n".join(lines)
+
+
def read_task_run_conversation_logs(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
run = _get_visible_run(run_id, task_id, team_id)
if run is None:
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index ef1597fc864a..8704a886d6c6 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3448,9 +3448,25 @@ class ConnectionTokenResponseSerializer(serializers.Serializer):
token = serializers.CharField(help_text="JWT token for authenticating with the sandbox")
+class TaskRunLogsView(models.TextChoices):
+ FULL = "full", "full"
+ THREAD = "thread", "thread"
+
+
class TaskRunLogsQuerySerializer(serializers.Serializer):
"""Query parameters for reading part of a task run log"""
+ view = serializers.ChoiceField(
+ choices=TaskRunLogsView.choices,
+ default=TaskRunLogsView.FULL,
+ required=False,
+ help_text=(
+ "'full' returns every entry as stored. 'thread' drops the duplicate tool response copy in "
+ "_meta.claudeCode.toolResponse and keeps only its decisionReason and message, for clients that "
+ "render the conversation. It applies to the full log and to every slice."
+ ),
+ )
+
tail_bytes = serializers.IntegerField(
required=False,
min_value=1,
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 51a8828b52ae..880d7d331e4f 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -203,6 +203,7 @@ from products.tasks.backend.presentation.serializers import (
TaskRunLivingArtifactResponseSerializer,
TaskRunLivingArtifactsResponseSerializer,
TaskRunLogsQuerySerializer,
+ TaskRunLogsView,
TaskRunPeerMessageRequestSerializer,
TaskRunPeerMessageResponseSerializer,
TaskRunPeersResponseSerializer,
@@ -3565,7 +3566,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"it reads the log, so events after the snapshot reach the live stream. Pass tail_bytes to read only "
"the latest turns first, add before to page back through older turns, or add start to read every "
"entry after the ones a client holds. X-Log-Origin names the first run of the chain: indexes from responses "
- "with different origins do not match. A Pi run returns its full log without the X-Log headers."
+ "with different origins do not match. A Pi run returns its full log without the X-Log headers. Pass "
+ "view=thread to drop the duplicate tool response copy that a rendered conversation does not use."
),
)
@action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])
@@ -3575,14 +3577,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
timer = ServerTimingsGathered()
with timer("mark_watched"):
tasks_facade.mark_task_run_stream_watched(pk, task_id, self.team_id)
- if "tail_bytes" not in query:
- with timer("s3_read"):
+ log_slice = None
+ with timer("s3_read"):
+ if "tail_bytes" not in query:
log_content = tasks_facade.read_task_run_conversation_logs(pk, task_id, self.team_id)
- if log_content is None:
- raise NotFound()
- response = HttpResponse(log_content, content_type="application/jsonl")
- else:
- with timer("s3_read"):
+ else:
log_slice = tasks_facade.read_task_run_conversation_log_slice(
pk,
task_id,
@@ -3591,20 +3590,24 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
before=query.get("before"),
start=query.get("start"),
)
- if log_slice is None:
- raise NotFound()
- response = HttpResponse(log_slice.content, content_type="application/jsonl")
- if log_slice.sliced:
- response["X-Log-Offset"] = str(log_slice.offset)
- response["X-Log-Count"] = str(log_slice.count)
- response["X-Log-Preamble"] = str(log_slice.preamble)
- response["X-Log-Turns-Before"] = str(log_slice.turns_before)
- response["X-Log-Origin"] = log_slice.origin
- # A cross-origin frontend (standalone OAuth mode) can read only exposed headers, and a page whose
- # headers it cannot read looks like the whole log.
- response["Access-Control-Expose-Headers"] = (
- "X-Log-Offset, X-Log-Count, X-Log-Preamble, X-Log-Turns-Before, X-Log-Origin"
- )
+ log_content = log_slice.content if log_slice else None
+ if log_content is None:
+ raise NotFound()
+ if query["view"] == TaskRunLogsView.THREAD:
+ with timer("thread_view"):
+ log_content = tasks_facade.thread_view_of_log_content(log_content)
+ response = HttpResponse(log_content, content_type="application/jsonl")
+ if log_slice is not None and log_slice.sliced:
+ response["X-Log-Offset"] = str(log_slice.offset)
+ response["X-Log-Count"] = str(log_slice.count)
+ response["X-Log-Preamble"] = str(log_slice.preamble)
+ response["X-Log-Turns-Before"] = str(log_slice.turns_before)
+ response["X-Log-Origin"] = log_slice.origin
+ # A cross-origin frontend (standalone OAuth mode) can read only exposed headers, and a page whose
+ # headers it cannot read looks like the whole log.
+ response["Access-Control-Expose-Headers"] = (
+ "X-Log-Offset, X-Log-Count, X-Log-Preamble, X-Log-Turns-Before, X-Log-Origin"
+ )
response["Cache-Control"] = "no-cache"
response["Server-Timing"] = timer.to_header_string()
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 779b77b49d65..a578cc65fa8c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11202,6 +11202,35 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content.decode("utf-8").splitlines(), expected_lines)
+ @parameterized.expand(
+ [
+ ("default_keeps_the_copy", "", status.HTTP_200_OK, True),
+ ("thread_drops_the_copy", "?view=thread", status.HTTP_200_OK, False),
+ ("thread_drops_the_copy_from_a_page", "?tail_bytes=1&view=thread", status.HTTP_200_OK, False),
+ ("unknown_view_rejected", "?view=compact", status.HTTP_400_BAD_REQUEST, None),
+ ]
+ )
+ @patch("posthog.storage.object_storage.read")
+ def test_logs_endpoint_view(self, _name: str, query: str, expected_status: int, has_copy: bool | None, mock_read):
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team)
+ entry = {
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"_meta": {"claudeCode": {"toolResponse": {"stdout": "x"}}}}},
+ }
+ }
+ mock_read.side_effect = lambda path, missing_ok=False: json.dumps(entry) + "\n" if path == run.log_url else None
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/logs/{query}")
+
+ self.assertEqual(response.status_code, expected_status)
+ if has_copy is not None:
+ claude_code = json.loads(response.content.decode("utf-8").splitlines()[0])["notification"]["params"][
+ "update"
+ ]["_meta"]["claudeCode"]
+ self.assertEqual("toolResponse" in claude_code, has_copy)
+
@parameterized.expand(
[
("latest_turn_across_the_chain", "?tail_bytes=1", status.HTTP_200_OK, ("2", "3", "1"), ["latest"]),
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 7fcd90f7a760..408fe09fd596 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -1,3 +1,4 @@
+import json
import importlib
import threading
from datetime import datetime, timedelta
@@ -1930,6 +1931,49 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertEqual(run.state.get("ai_stage"), "wizard_pr_agent")
+def _tool_update(tool_response: object) -> dict:
+ return {
+ "type": "notification",
+ "notification": {
+ "method": "session/update",
+ "params": {
+ "update": {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "t1",
+ "rawOutput": "out",
+ "_meta": {"claudeCode": {"toolName": "Bash", "toolResponse": tool_response}},
+ }
+ },
+ },
+ }
+
+
+class TestThreadViewOfLogContent(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("output_copy_dropped", {"stdout": "x" * 500, "stderr": ""}, None),
+ (
+ "denial_fields_kept",
+ {"decisionReason": "Denied", "message": "No", "stdout": "x"},
+ {"decisionReason": "Denied", "message": "No"},
+ ),
+ ("non_object_dropped", "plain text", None),
+ ]
+ )
+ def test_reduces_the_tool_response_copy(self, _name: str, tool_response: object, expected: object) -> None:
+ other = {"type": "notification", "notification": {"method": "_posthog/run_started", "params": {}}}
+ content = "\n".join([json.dumps(other), json.dumps(_tool_update(tool_response)), "not json", ""])
+
+ lines = facade.thread_view_of_log_content(content).split("\n")
+
+ self.assertEqual(lines[0], json.dumps(other))
+ self.assertEqual(lines[2:], ["not json", ""])
+ update = json.loads(lines[1])["notification"]["params"]["update"]
+ self.assertEqual(update["rawOutput"], "out")
+ self.assertEqual(update["_meta"]["claudeCode"].get("toolResponse"), expected)
+ self.assertEqual(update["_meta"]["claudeCode"]["toolName"], "Bash")
+
+
class TestAppendLogAgentActivity(SimpleTestCase):
# Guards the self-sustaining heartbeat loop: infra log lines (credential refresh ->
# _posthog/console) heartbeating with agent_active=True reset the workflow's inactivity
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f11e5f1fed67..24172c768b4f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -136314,8 +136314,24 @@ export namespace Schemas {
* @minimum 1
*/
tail_bytes?: number;
+ /**
+ * 'full' returns every entry as stored. 'thread' drops the duplicate tool response copy in _meta.claudeCode.toolResponse and keeps only its decisionReason and message, for clients that render the conversation. It applies to the full log and to every slice.
+ *
+ * * `full` - full
+ * * `thread` - thread
+ * @minLength 1
+ */
+ view?: TasksRunsLogsRetrieveView;
};
+ export type TasksRunsLogsRetrieveView = typeof TasksRunsLogsRetrieveView[keyof typeof TasksRunsLogsRetrieveView];
+
+
+ export const TasksRunsLogsRetrieveView = {
+ Full: 'full',
+ Thread: 'thread',
+ } as const;
+
export type TasksRunsSessionLogsRetrieveParams = {
/**
* Only return events after this ISO8601 timestamp