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): remove the tasks-stream-via-proxy flag (#120618)

Shy Alter16c59772f24e
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index cb0ba28deb88..252d07d0accb 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -77,7 +77,7 @@ The thinking indicator stops at stream end, and a history error stays visible ev
`sandbox_stream_recovered` records successful recovery after history reconciliation, with the phase, run status, attempt counts, and elapsed time.
Neither event includes transcript contents or proxy tokens.
-After deployment, verify recovery with `tasks-stream-via-proxy` both enabled and disabled: interrupt a live stream, let the agent persist output, and confirm the restored transcript contains it once.
+After deployment, verify recovery on both stream legs (agent proxy and Django): interrupt a live stream, let the agent persist output, and confirm the restored transcript contains it once.
Also exhaust retries and verify that Retry works for both an active run and an ended run with an unreadable history snapshot.
```text
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index fb857cd2af44..c23b073e30f1 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -531,7 +531,6 @@ export const FEATURE_FLAGS = {
TASK_SUMMARIES: 'task-summaries', // owner: #team-ai-observability
TASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-ai
TASKS: 'tasks', // owner: #team-ai-observability
- TASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observability
TAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra multivariate=control,test, experiment: test asks the decision model which core events an events search with no results describes, then suggests them or says why there are none; control asks nothing
TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)
TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. control changes nothing, banner suggests the right tab, promote moves the predicted group to the top of the All tab
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 4f0b9e9881af..8e32e12da505 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -134,8 +134,8 @@ TASKS_AGENT_PROXY_CORS_ORIGINS: list[str] = [
TASKS_AGENT_PROXY_INGEST_URL: str | None = os.getenv("TASKS_AGENT_PROXY_INGEST_URL") or None
# Browser-facing base URL of the agent-proxy for the live-stream read leg, per environment (e.g.
-# https://agent-proxy.us.posthog.com). The stream_token endpoint returns it to clients only when this
-# is set AND the read-via-proxy flag is enabled for the user; unset means clients read from Django.
+# https://agent-proxy.us.posthog.com). The stream_token endpoint returns it to clients when this is
+# set; unset means clients read from Django.
TASKS_AGENT_PROXY_PUBLIC_URL: str | None = os.getenv("TASKS_AGENT_PROXY_PUBLIC_URL") or None
# In-cluster base URL of the agent-proxy for backend consumers (e.g. the Temporal worker relaying a
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index edf2286c7346..8b3de1eb8866 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -5,11 +5,10 @@ import { mockFeatureFlags } from '@playwright-utils/mockApi'
import { PlaywrightWorkspaceSetupResult, expect, test } from '@playwright-utils/workspace-test-base'
import { Page, Route } from '@playwright/test'
-// Flag keys mirror `FEATURE_FLAGS.TASKS` / `FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY` (frontend/src/lib/constants).
+// The flag key mirrors `FEATURE_FLAGS.TASKS` (frontend/src/lib/constants).
// Inlined as literals rather than imported: pulling `lib/constants` into a Node-run Playwright spec drags its
// heavy `types.ts` value-import graph into the test bundle. These keys are stable feature-flag wire strings.
const TASKS_FLAG = 'tasks'
-const TASKS_STREAM_VIA_PROXY_FLAG = 'tasks-stream-via-proxy'
// Fixed UUIDs so the `?runId=` deep link clears `taskDetailSceneLogic`'s `isUUIDLike` guard deterministically.
const TASK_ID = '0190a000-0000-4000-8000-0000000000a1'
@@ -125,7 +124,7 @@ async function routeTasksApi(page: Page, mock: TasksApiMock): Promise<void> {
)
await page.route((url) => runRe.test(url.pathname), fulfillJson(run))
// No `stream_base_url` ⇒ `resolveStreamTarget` returns null ⇒ streaming stays on the mockable Django
- // `stream/` route even when the proxy gate (flag or preflight `is_debug`) is on.
+ // `stream/` route.
await page.route((url) => tokenRe.test(url.pathname), fulfillJson({ token: 'e2e-token', stream_base_url: null }))
await page.route(
(url) => logsRe.test(url.pathname),
@@ -216,7 +215,7 @@ test.describe('Task run surface', () => {
test.beforeEach(async ({ page, playwrightSetup }) => {
await playwrightSetup.login(page, workspace!)
- await mockFeatureFlags(page, { [TASKS_FLAG]: true, [TASKS_STREAM_VIA_PROXY_FLAG]: false })
+ await mockFeatureFlags(page, { [TASKS_FLAG]: true })
})
test('terminal replay surfaces the agent error inline', async ({ page }) => {
@@ -371,7 +370,6 @@ test.describe('Task run surface', () => {
await prepareRunComposer(page)
await mockFeatureFlags(page, {
[TASKS_FLAG]: true,
- [TASKS_STREAM_VIA_PROXY_FLAG]: false,
'phai-sandbox-mode': true,
})
await routeTasksApi(page, {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index d7b8c63771d3..42c03236cac4 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -2,9 +2,7 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { projectLogic } from 'scenes/projectLogic'
import { initKeaTests } from '~/test/init'
@@ -235,8 +233,6 @@ describe('runStreamLogic', () => {
let logic: ReturnType<typeof runStreamLogic.build>
beforeEach(() => {
- // featureFlagLogic persists flags to localStorage; clear before init so a flag set by one
- // test (e.g. `enableProxy()`) can't leak into a later test's flag-off assertions.
window.localStorage.clear()
initKeaTests()
// The logic mirrors the live resume cursor to sessionStorage — clear it so a cursor written
@@ -2701,6 +2697,7 @@ describe('runStreamLogic', () => {
it('surfaces a named event:error frame verbatim', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitErrorFrame({
errorTitle: 'Sandbox crashed',
@@ -2943,6 +2940,7 @@ describe('runStreamLogic', () => {
state: { resume_from_run_id: 'run-1' },
}
logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })
+ await flushPromises()
const originalStream = MockStream.latest()
await originalStream.emitOpen()
await originalStream.emitMessage(notification('_posthog/run_started', { runId: 'run-1' }), '100-0')
@@ -2963,6 +2961,7 @@ describe('runStreamLogic', () => {
expect(logic.values.streamPhase).toBe('provisioning')
logic.actions.attachOptimisticResume('task-1', nextRun)
+ await flushPromises()
const resumedStream = MockStream.latest()
await resumedStream.emitOpen()
expect(resumedStream.options.lastEventId).toBeUndefined()
@@ -3153,6 +3152,7 @@ describe('runStreamLogic', () => {
describe('terminal-status handling', () => {
it('closes the SSE and stops reconnects on a terminal task_run_state', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -3166,6 +3166,7 @@ describe('runStreamLogic', () => {
it('keeps the stream open on a non-terminal task_run_state', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -3229,6 +3230,7 @@ describe('runStreamLogic', () => {
it('captures the pr url from a live task_run_state frame', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitOpen()
await expectLogic(logic, async () => {
@@ -4078,6 +4080,7 @@ describe('runStreamLogic', () => {
const getSpy = jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitOpen()
const beforeDrop = MockStream.connections.length
@@ -4094,6 +4097,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitOpen()
const beforeDrop = MockStream.connections.length
@@ -4116,6 +4120,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
// A live frame stamps its Redis stream id as the resume cursor.
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
@@ -4180,6 +4185,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
expect(logsSpy).not.toHaveBeenCalled()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
@@ -4201,6 +4207,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4222,6 +4229,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4234,13 +4242,14 @@ describe('runStreamLogic', () => {
it('releases the live turn when the resync recovers its completion from history', async () => {
const turnComplete = notification('_posthog/turn_complete', { stopReason: 'end_turn' })
- let resolveLogs: (entries: StoredLogEntry[]) => void = () => {}
+ let resolveLogs: (entries: StoredLogEntry[]) => void = async () => {}
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise<StoredLogEntry[]>((resolve) => (resolveLogs = resolve)) as any
)
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4266,13 +4275,14 @@ describe('runStreamLogic', () => {
it('keeps the turn open when the replayed completion belongs to an older turn', async () => {
const turnComplete = notification('_posthog/turn_complete', { stopReason: 'end_turn' })
- let resolveLogs: (entries: StoredLogEntry[]) => void = () => {}
+ let resolveLogs: (entries: StoredLogEntry[]) => void = async () => {}
jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(
new Promise<StoredLogEntry[]>((resolve) => (resolveLogs = resolve)) as any
)
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4301,6 +4311,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockRejectedValue({ status: 500 })
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4320,6 +4331,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitOpen()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')
await MockStream.latest().emitEndFrame({ type: 'resync', reason: 'trimmed' })
@@ -4390,10 +4402,12 @@ describe('runStreamLogic', () => {
it("opens a successor run on fresh connection state, not the finished run's", async () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
await MockStream.latest().emitStreamEnd()
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-2', startLatest: false })
+ await flushPromises()
expect(MockStream.latest().options.lastEventId).toBeUndefined()
await MockStream.latest().emitOpen()
@@ -4411,6 +4425,7 @@ describe('runStreamLogic', () => {
it('leaves a dead stream closed when a follow-up starts a turn', async () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await flushPromises()
await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
await MockStream.latest().emitStreamEnd()
expect(logic.values.sseStatus).toEqual('closed')
@@ -4426,8 +4441,9 @@ describe('runStreamLogic', () => {
// The keyed log store makes duplicate ingestion idempotent, so correctness no longer depends
// on closing the exact connection a hot reload orphaned (the old EventSource registry is
// gone). Teardown still aborts the active fetch so it stops streaming.
- it('aborts the active stream on closeSse', () => {
+ it('aborts the active stream on closeSse', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
logic.actions.closeSse()
@@ -4435,8 +4451,9 @@ describe('runStreamLogic', () => {
expect(source.closed).toEqual(true)
})
- it('aborts the active stream on reset', () => {
+ it('aborts the active stream on reset', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
logic.actions.reset()
@@ -4844,6 +4861,7 @@ describe('runStreamLogic', () => {
describe('wire frame parsing through the SSE reader', () => {
it('reads the snake_case error_message off task_run_state frames', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -4861,6 +4879,7 @@ describe('runStreamLogic', () => {
it('keeps the stream open for non-terminal task_run_state frames', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -4872,6 +4891,7 @@ describe('runStreamLogic', () => {
it('ignores unrecognized frame types', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -5959,6 +5979,7 @@ describe('runStreamLogic', () => {
expect(logic.values.streamPhase).toEqual('idle')
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitOpen()
// SSE open, agent not started yet — provisioning, surfacing _posthog/progress.
@@ -5977,6 +5998,7 @@ describe('runStreamLogic', () => {
it('tracks the optional task_run_state stage off the wire', async () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitOpen()
@@ -5991,6 +6013,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
jest.useFakeTimers()
@@ -6017,6 +6040,7 @@ describe('runStreamLogic', () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
await MockStream.latest().emitOpen()
// Drive the cumulative counter to the cap without growing the per-drop counter, as a
// clean-EOF reopen loop would (every reopen resets reconnectAttempt to 0).
@@ -6334,6 +6358,7 @@ describe('runStreamLogic', () => {
it('populates pendingPermissionRequest off a permission_request SSE frame', async () => {
jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'in_progress' } as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
await MockStream.latest().emitMessage({ ...permissionFrame })
@@ -6506,6 +6531,7 @@ describe('runStreamLogic', () => {
;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue({ status: 502 })
jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitMessage({
@@ -6618,6 +6644,7 @@ describe('runStreamLogic', () => {
it('ignores a replayed permission_request envelope once the request is resolved', async () => {
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitMessage({ ...permissionFrame })
@@ -6639,6 +6666,7 @@ describe('runStreamLogic', () => {
it('does not double-capture telemetry when the same envelope arrives twice while pending', async () => {
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
const source = MockStream.latest()
await source.emitMessage({ ...permissionFrame })
@@ -6730,11 +6758,6 @@ describe('runStreamLogic', () => {
})
describe('agent-proxy stream routing', () => {
- const enableProxy = (): void =>
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY], {
- [FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY]: true,
- })
-
beforeEach(() => {
;(tasksRunsStreamTokenRetrieve as jest.Mock).mockReset()
})
@@ -6745,7 +6768,6 @@ describe('runStreamLogic', () => {
{ name: 'Django fallback after history', historyFirst: true, proxy: false, remint: false },
{ name: 'token retry after history', historyFirst: true, proxy: true, remint: true },
])('replays a refreshed run without a stored cursor with $name', async ({ historyFirst, proxy, remint }) => {
- enableProxy()
window.sessionStorage.setItem('posthog-ai:stream-resume:run-1', '1700-0')
const target = { token: 'test-token', stream_base_url: proxy ? 'https://proxy.example' : null }
let resolveToken!: (value: typeof target) => void
@@ -6821,7 +6843,6 @@ describe('runStreamLogic', () => {
it.each(['failed request', 'empty stream', 'fresh stream'])(
'recovers responses across a cursorless startup reconnect after a %s',
async (drop) => {
- enableProxy()
const target = { token: 'test-token', stream_base_url: 'https://proxy.example' }
let resolveToken!: (value: typeof target) => void
const nextToken = new Promise((resolve) => (resolveToken = resolve))
@@ -6990,17 +7011,12 @@ describe('runStreamLogic', () => {
)
describe('resolveStreamTarget', () => {
- it('skips the token mint and streams from Django when the rollout is off', async () => {
- expect(await resolveStreamTarget('997', 'task-1', 'run-1', false)).toBeNull()
- expect(tasksRunsStreamTokenRetrieve).not.toHaveBeenCalled()
- })
-
it('routes to the proxy when the server resolves a base URL', async () => {
;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({
token: 'tok-1',
stream_base_url: 'https://proxy.example/',
})
- expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toEqual({
+ expect(await resolveStreamTarget('997', 'task-1', 'run-1')).toEqual({
baseUrl: 'https://proxy.example/',
token: 'tok-1',
})
@@ -7018,17 +7034,16 @@ describe('runStreamLogic', () => {
token: 'tok-1',
stream_base_url: null,
})
- expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()
+ expect(await resolveStreamTarget('997', 'task-1', 'run-1')).toBeNull()
})
it('falls back to Django when minting the token throws', async () => {
;(tasksRunsStreamTokenRetrieve as jest.Mock).mockRejectedValue(new Error('forbidden'))
- expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()
+ expect(await resolveStreamTarget('997', 'task-1', 'run-1')).toBeNull()
})
})
- it('passes the resolved proxy target to openStream when the rollout is on', async () => {
- enableProxy()
+ it('passes the resolved proxy target to openStream', async () => {
;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({
token: 'tok-1',
stream_base_url: 'https://proxy.example',
@@ -7050,19 +7065,7 @@ describe('runStreamLogic', () => {
})
})
- it('never mints a token or sets a proxy target when the rollout is off', async () => {
- // The flag is off by default here. Opening the stream must take the same-origin Django
- // path (no token mint, no proxy target) — guards against re-adding a debug/non-flag force
- // that would break flag-off streaming (the reported local bug).
- logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
- await flushPromises()
-
- expect(tasksRunsStreamTokenRetrieve).not.toHaveBeenCalled()
- expect(MockStream.latest().options.proxyTarget).toBeUndefined()
- })
-
it('re-mints the read token and retries once on a 401 from the proxy leg', async () => {
- enableProxy()
;(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({
token: 'tok-1',
stream_base_url: 'https://proxy.example',
@@ -7080,7 +7083,6 @@ describe('runStreamLogic', () => {
it('pauses after five proxy-token remints until manual Retry', async () => {
jest.useFakeTimers()
- enableProxy()
jest.mocked(tasksRunsStreamTokenRetrieve).mockResolvedValue({
token: 'fake-token',
stream_base_url: 'https://example.com',
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 0ed34020d1b1..11c594db5ffa 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -19,9 +19,7 @@ import { agentConversationEventToAcpNotification } from '@posthog/agent-contract
import type { AgentConversationEvent } from '@posthog/agent-contracts/agent-conversation'
import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'
@@ -38,7 +36,6 @@ import {
TaskRuntimeEnumApi,
} from 'products/tasks/frontend/generated/api.schemas'
-import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
import type { UserType } from '../../../../frontend/src/types'
import { turnSuggestionsStateRetrieve } from '../generated/api'
import { deliverPermissionResponse, isPermissionTargetEnded } from '../policy/permissionDelivery'
@@ -260,20 +257,15 @@ export interface StreamProxyTarget {
}
/**
- * Resolve the proxy target for a run, or null to stream from Django. Purely additive: with the
- * rollout flag off we skip the token mint entirely (pre-proxy behavior); with it on but the server
- * resolves no base URL — or the mint throws — we fall back to Django so streaming never breaks.
+ * Resolve the proxy target for a run, or null to stream from Django. When the server resolves no
+ * base URL — or the mint throws — we fall back to Django so streaming never breaks.
*/
export async function resolveStreamTarget(
projectId: string,
taskId: string,
runId: string,
- viaProxy: boolean,
signal?: AbortSignal
): Promise<StreamProxyTarget | null> {
- if (!viaProxy) {
- return null
- }
try {
const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(
projectId,
@@ -2397,7 +2389,6 @@ function rendersThreadItemContent(item: ThreadItem): boolean {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface runStreamLogicValues {
showDebugLogs: boolean // debugLogsLogic
- featureFlags: FeatureFlagsSet // featureFlagLogic
foregroundStreamKeys: Set<string> // foregroundStreamLogic
isDev: boolean | undefined // preflightLogic
currentProjectId: number | null // projectLogic
@@ -2448,7 +2439,6 @@ export interface runStreamLogicValues {
sseStatus: RunSseStatus
streamHasEnded: boolean
streamPhase: 'idle' | 'provisioning' | 'thinking'
- streamViaProxyEnabled: boolean
threadItems: ThreadItem[]
toolInvocations: Map<string, ToolInvocation>
traceId: string | null
@@ -2810,7 +2800,6 @@ export interface runStreamLogicMeta {
toolInvocations: Map<string, ToolInvocation>
) => boolean
hasGitArtifacts: (runArtifacts: RunArtifacts) => boolean
- streamViaProxyEnabled: (featureFlags: FeatureFlagsSet) => boolean
runConnectionState: (
sseStatus: RunSseStatus,
reconnectAttempt: number,
@@ -2856,8 +2845,6 @@ export const runStreamLogic = kea<runStreamLogicType>([
values: [
projectLogic,
['currentProjectId'],
- featureFlagLogic,
- ['featureFlags'],
preflightLogic,
['isDev'],
userLogic,
@@ -3753,19 +3740,6 @@ export const runStreamLogic = kea<runStreamLogicType>([
(s) => [s.runArtifacts],
(runArtifacts: RunArtifacts): boolean => !!runArtifacts.prUrl || !!runArtifacts.branch,
],
- /**
- * Gates routing the live stream through the standalone agent-proxy (the durable-streaming
- * rollout). Purely flag-driven: off ⇒ stream directly from Django and never mint a
- * `stream_token`; on ⇒ resolve a proxy target. The server still owns the final
- * proxy-vs-Django decision via `stream_token` (no base URL ⇒ Django), so a flag-on client
- * where the proxy isn't deployed falls back safely. Frontend flags evaluate in local dev, so
- * a dev exercises the proxy by enabling `tasks-stream-via-proxy` for their user.
- */
- streamViaProxyEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY],
- ],
/**
* The live connection banner view-model (footer `RunAlertActivity`), or null when the connection is
* healthy. `reconnecting` drives the attempt-counter card during the backoff loop; `connection_failed`
@@ -4406,21 +4380,11 @@ export const runStreamLogic = kea<runStreamLogicType>([
try {
let response: Response
for (;;) {
- const proxyTarget =
- values.streamViaProxyEnabled || values.piRuntime
- ? await session.request(
- STREAM_REQUEST_TIMEOUT_MS,
- (signal) =>
- resolveStreamTarget(
- String(session.projectId),
- taskId,
- runId,
- true,
- signal
- ),
- controller.signal
- )
- : null
+ const proxyTarget = await session.request(
+ STREAM_REQUEST_TIMEOUT_MS,
+ (signal) => resolveStreamTarget(String(session.projectId), taskId, runId, signal),
+ controller.signal
+ )
if (!ownsStream()) {
return
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts
index b0d441866bd8..364bf0dea461 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts
@@ -94,9 +94,6 @@ describe('taskDetailSceneLogic', () => {
// mounts the common logics, so clear before init or flags enabled in one test leak into
// the next.
window.localStorage.clear()
- // streamViaProxyEnabled is now purely flag-driven, so preflight no longer affects it. The
- // default test fixture has is_debug: true; pin it to false to keep the app context minimal
- // and unsurprising for these tests.
window.POSTHOG_APP_CONTEXT = { preflight: { is_debug: false } } as unknown as typeof window.POSTHOG_APP_CONTEXT
initKeaTests()
global.fetch = createFetchMock()
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index e105b673c813..9f9249a8307d 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -219,7 +219,6 @@ MAX_CUSTOM_IMAGES_PER_USER = 10
TASK_SESSION_MAX_SIZE_BYTES = 10 * 1024 * 1024
TASK_SESSION_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
-STREAM_VIA_PROXY_FEATURE_FLAG = "tasks-stream-via-proxy"
OVERLAP_CLONE_BOOT_FEATURE_FLAG = "tasks-overlap-clone-boot"
DESKTOP_WORKSPACE_WARM_FEATURE_FLAG = "task-cloud-desktop-workspace-warm"
# Kill switch: rtk command-output compression is on by default in cloud sandboxes;
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 0c809bec6787..9348a0a1c6dd 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5537,36 +5537,12 @@ def task_created_by_user(task_id: str | UUID, team_id: int, user_id: int) -> boo
return Task.objects.filter(id=task_id, team_id=team_id, created_by_id=user_id).exists()
-def resolve_stream_base_url(*, distinct_id: str, organization_id: str | UUID, force_proxy: bool = False) -> str | None:
+def resolve_stream_base_url() -> str | None:
"""Agent-proxy base URL for the read leg, or ``None`` to read from Django directly.
- Returns the configured agent-proxy URL only when it is set for this environment AND the
- read-via-proxy flag is enabled for the user, so rollout stays gradual and reversible. The
- server owns this decision; clients just connect to whatever URL comes back.
+ The server owns this decision; clients just connect to whatever URL comes back.
"""
- from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAG # noqa: PLC0415
-
- proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL
- if not proxy_url:
- return None
- # Local dev disables the analytics SDK, so the rollout flag never evaluates; the URL setting
- # is the opt-in there. Prod (DEBUG off) still gates on the flag below.
- if settings.DEBUG or force_proxy:
- return proxy_url
- try:
- enabled = bool(
- posthoganalytics.feature_enabled(
- STREAM_VIA_PROXY_FEATURE_FLAG,
- distinct_id=distinct_id,
- groups={"organization": str(organization_id)},
- group_properties={"organization": {"id": str(organization_id)}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- return None
- return proxy_url if enabled else None
+ return settings.TASKS_AGENT_PROXY_PUBLIC_URL or None
# --- Task run commands (user_message signal + sandbox proxy) ---
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 5092497b5a44..9467851f1765 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -3653,15 +3653,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
client_can_resync = bool(getattr(request, "validated_query_data", {}).get("resync"))
thin_tail_withheld = run_stream_thin_tail(stream_info.state) and not client_can_resync
- stream_base_url = (
- None
- if thin_tail_withheld
- else tasks_facade.resolve_stream_base_url(
- distinct_id=request.user.distinct_id,
- organization_id=self.team.organization_id,
- force_proxy=tasks_facade.task_uses_pi_runtime(task_id, self.team_id),
- )
- )
+ stream_base_url = None if thin_tail_withheld else tasks_facade.resolve_stream_base_url()
route: StreamTokenRoute = "thin_tail_withheld"
if not thin_tail_withheld:
route = "proxy" if stream_base_url else "django"
diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
index 1ccf19198ddf..f1f84546d9a8 100644
--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
@@ -10,14 +10,12 @@ from django.conf import settings
import httpx
import httpx_sse
import structlog
-import posthoganalytics
from temporalio import activity
from posthog.security.outbound_proxy import internal_httpx_async_client
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.utils import close_db_connections
-from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAG
from products.tasks.backend.logic.services.connection_token import create_stream_read_token
from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
@@ -172,31 +170,6 @@ def _resume_position() -> tuple[str | None, bool]:
return last_event_id, turn_active
-def _stream_via_proxy_enabled(task_run: TaskRunModel) -> bool:
- """Whether the read-via-proxy flag (``tasks-stream-via-proxy``) is on for this run.
-
- Mirrors the UI's ``resolve_stream_base_url`` and event_ingest's push gate so the relay reads
- the proxy leg only when the browser would too — a runtime kill-switch for both. Fails closed.
- """
- user = task_run.task.created_by
- if user is None:
- return False
- organization_id = str(task_run.team.organization_id)
- try:
- return bool(
- posthoganalytics.feature_enabled(
- STREAM_VIA_PROXY_FEATURE_FLAG,
- user.distinct_id or f"user_{user.id}",
- groups={"organization": organization_id},
- group_properties={"organization": {"id": organization_id}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- return False
-
-
@activity.defn
@close_db_connections
async def relay_agent_design_signals(input: RelayAgentDesignSignalsInput) -> None:
@@ -217,25 +190,18 @@ async def relay_agent_design_signals(input: RelayAgentDesignSignalsInput) -> Non
logger.warning("relay_agent_design_signals_handle_init_failed", run_id=input.run_id, error=str(e))
return
- # Read the live proxy leg only when a proxy is configured AND the read-via-proxy flag is on for
- # the run — the same decision the task UI makes. Otherwise tail the Django-side Redis stream.
+ # Read the live proxy leg when a proxy is configured. Otherwise tail the Django-side Redis stream.
base_url = _agent_proxy_base_url()
- task_run: TaskRunModel | None = None
- stream_via_proxy = False
- if base_url:
- task_run = await TaskRunModel.objects.select_related("task__created_by", "team").aget(id=input.run_id)
- # feature_enabled can block on a cold flag cache — off the event loop, this is an async activity.
- stream_via_proxy = await asyncio.to_thread(_stream_via_proxy_enabled, task_run)
logger.info(
"relay_agent_design_signals_started",
run_id=input.run_id,
- leg="proxy" if stream_via_proxy else "redis",
+ leg="proxy" if base_url else "redis",
base_url=base_url,
- stream_via_proxy=stream_via_proxy,
)
- if base_url and stream_via_proxy and task_run is not None:
+ if base_url:
+ task_run = await TaskRunModel.objects.select_related("task").aget(id=input.run_id)
await _relay_from_agent_proxy(base_url, task_run, input, workflow_handle)
return
# The Redis leg reads from 0 with a fresh emitter — no resume, so no turn to carry over.
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index afd2a7366dc5..1b2a81b7a548 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11398,21 +11398,23 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertNotIn("user_id", decoded)
self.assertIn("exp", decoded)
+ @parameterized.expand([("acp", Task.Runtime.ACP), ("pi", Task.Runtime.PI)])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_returns_proxy_url_when_configured_and_flag_enabled(self):
+ def test_stream_token_returns_proxy_url_when_configured(self, _name, runtime):
reset_sandbox_jwt_key_cache()
- task = self.create_task()
+ task = self.create_task(runtime=runtime)
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
with (
self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
- patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True),
+ patch("products.tasks.backend.presentation.views.api.observe_stream_token_routed") as observe_routed,
):
response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")
+ observe_routed.assert_called_once_with(task.origin_product, "proxy", False)
@parameterized.expand(
[
@@ -11433,7 +11435,6 @@ class TestTaskRunAPI(BaseTaskAPITest):
with (
self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
- patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True),
patch("products.tasks.backend.presentation.views.api.observe_stream_token_routed") as observe_routed,
):
response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/{query}")
@@ -11442,93 +11443,6 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.json()["stream_base_url"], expected_base_url)
observe_routed.assert_called_once_with(task.origin_product, expected_route, expected_resync_requested)
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_omits_proxy_url_when_flag_disabled(self):
- reset_sandbox_jwt_key_cache()
-
- task = self.create_task()
- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
-
- # Disable only the stream-via-proxy flag; leave other flags at their real values so the
- # request's own access checks still pass.
- def flag_enabled(key, *args, **kwargs):
- return key != "tasks-stream-via-proxy"
-
- with (
- self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
- patch(
- "products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
- side_effect=flag_enabled,
- ),
- patch("products.tasks.backend.presentation.views.api.observe_stream_token_routed") as observe_routed,
- ):
- response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIsNone(response.json()["stream_base_url"])
- observe_routed.assert_called_once_with(task.origin_product, "django", False)
-
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_returns_proxy_url_for_pi_when_flag_disabled(self):
- reset_sandbox_jwt_key_cache()
-
- task = self.create_task(runtime=Task.Runtime.PI)
- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
-
- def flag_enabled(key, *args, **kwargs):
- return key != "tasks-stream-via-proxy"
-
- with (
- self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
- patch(
- "products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
- side_effect=flag_enabled,
- ),
- ):
- response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")
-
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_returns_proxy_url_in_debug_without_flag(self):
- # Local dev (DEBUG) disables the analytics SDK, so the URL setting alone opts in.
- reset_sandbox_jwt_key_cache()
-
- task = self.create_task()
- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
-
- with self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="http://localhost:8003", DEBUG=True):
- response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["stream_base_url"], "http://localhost:8003")
-
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_omits_proxy_url_when_flag_evaluation_fails(self):
- # A flag-service outage must fall back to reading from Django, not break token issuance.
- reset_sandbox_jwt_key_cache()
-
- task = self.create_task()
- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
-
- def flag_enabled(key, *args, **kwargs):
- if key == "tasks-stream-via-proxy":
- raise RuntimeError("flag service unavailable")
- return True
-
- with (
- self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
- patch(
- "products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
- side_effect=flag_enabled,
- ),
- ):
- response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIsNone(response.json()["stream_base_url"])
-
def test_connection_token_cannot_access_other_team_run(self):
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Team")