mirror of
https://github.com/simstudioai/sim.git
synced 2026-11-24 22:49:06 +08:00
feat(cli): add resumable async Sim Chat
This commit is contained in:
1 parent
35a7078a7d
commit
d4c74648b0
38 files changed
+3482
-203
No files matched your search
+275
-2
@@ -1434,7 +1434,7 @@
|
||||
"post": {
|
||||
"operationId": "chat",
|
||||
"summary": "Ask Sim Chat",
|
||||
"description": "Chat with the Mothership agent for a workspace. Personal API keys use their owner's current workspace permission, integrations, credentials, environment context, and memory, and their conversations are synchronized with the Sim Home chat history. Shared workspace keys retain normal workspace capabilities but do not inherit a human owner's personal integrations, secrets, environment, memory, or private chat history. Set `readOnly` to select the subtractive, secretless workspace-query policy. Omit `continuationToken` for a one-shot or first interactive turn, then send the latest opaque token returned by the stream to continue the same conversation. Tokens are bound to the workspace, authorization principal, credential type, and read-only mode, and expire on a rolling 24-hour window; this chat POST never accepts a raw chat ID. The response is a Server-Sent Events stream. `text` events contain incremental assistant output and `complete` contains the authoritative final result. Comment frames are heartbeats and `data: [DONE]` closes a successful stream. The caller's Sim API key selects and authorizes the local workspace but is never forwarded to Mothership. Workspace keys use the workspace billing account as their system actor while local tool authorization remains bound to the key owner; personal keys use their owner. Inline attachments are base64-only: paths and URLs are not accepted or resolved.",
|
||||
"description": "Chat with the Mothership agent for a workspace. Personal API keys use their owner's current workspace permission, integrations, credentials, environment context, and memory, and their conversations are synchronized with the Sim Home chat history. Shared workspace keys retain normal workspace capabilities but do not inherit a human owner's personal integrations, secrets, environment, memory, or private chat history. Set `readOnly` to select the subtractive, secretless workspace-query policy. Omit `continuationToken` for a one-shot or first interactive turn, then send the latest opaque token returned by the stream to continue the same conversation. Tokens are bound to the workspace, authorization principal, credential type, and read-only mode, and expire on a rolling 24-hour window; this chat POST never accepts a raw chat ID. Set `async: true` with a personal API key to keep an accepted persisted turn running after disconnect; its first accepted `session` event includes a durable `runId` that can be polled through the chat-run endpoints. `runId` is omitted for ordinary synchronous turns. Set `persistChat: false` to suppress persistence of a newly created chat; that mode cannot be asynchronous. The response is a Server-Sent Events stream. `text` events contain incremental assistant output and `complete` contains the authoritative final result. Comment frames are heartbeats and `data: [DONE]` closes a successful stream. The caller's Sim API key selects and authorizes the local workspace but is never forwarded to Mothership. Workspace keys use the workspace billing account as their system actor while local tool authorization remains bound to the key owner; personal keys use their owner. Inline attachments are base64-only: paths and URLs are not accepted or resolved.",
|
||||
"tags": ["Chat"],
|
||||
"security": [
|
||||
{
|
||||
@@ -1472,6 +1472,16 @@
|
||||
"default": false,
|
||||
"description": "Use the secretless, read-only workspace-query policy. The default keeps normal workspace capabilities; shared workspace credentials still exclude personal integrations, secrets, environment, and persistent memory."
|
||||
},
|
||||
"async": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Keep an accepted persisted turn running after the caller disconnects and return its durable run ID in the session event. Requires a personal API key and `persistChat: true`; poll the chat-run endpoints for progress."
|
||||
},
|
||||
"persistChat": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Allow a new conversation to be persisted in the workspace chat list. Setting this to false suppresses new-chat persistence and cannot be combined with `async: true`; an existing persisted chat remains persisted when continued."
|
||||
},
|
||||
"attachments": {
|
||||
"type": "array",
|
||||
"maxItems": 5,
|
||||
@@ -1637,6 +1647,7 @@
|
||||
"example": {
|
||||
"workspaceId": "ws_abc123",
|
||||
"prompt": "Summarize the attached notes and compare them with this workspace.",
|
||||
"async": true,
|
||||
"attachments": [
|
||||
{
|
||||
"name": "notes.md",
|
||||
@@ -1668,7 +1679,7 @@
|
||||
"content": {
|
||||
"text/event-stream": {
|
||||
"schema": { "type": "string" },
|
||||
"example": "data: {\"type\":\"session\",\"continuationToken\":\"sim-v2-chat-v1.opaque.refreshed\",\"requestId\":\"req_123\",\"chatId\":\"80a47295-040e-46f9-9ea8-ad78eff3bcab\"}\n\ndata: {\"type\":\"text\",\"delta\":\"Two workflows...\"}\n\ndata: {\"type\":\"complete\",\"data\":{\"content\":\"Two workflows...\",\"continuationToken\":\"sim-v2-chat-v1.opaque.refreshed\",\"usage\":{\"prompt\":120,\"completion\":18,\"total\":138}}}\n\ndata: [DONE]\n\n"
|
||||
"example": "data: {\"type\":\"session\",\"continuationToken\":\"sim-v2-chat-v1.opaque.refreshed\",\"requestId\":\"req_123\",\"chatId\":\"80a47295-040e-46f9-9ea8-ad78eff3bcab\",\"runId\":\"4bfa6f89-b746-43be-8246-bf1c69b58593\"}\n\ndata: {\"type\":\"text\",\"delta\":\"Two workflows...\"}\n\ndata: {\"type\":\"complete\",\"data\":{\"content\":\"Two workflows...\",\"continuationToken\":\"sim-v2-chat-v1.opaque.refreshed\",\"usage\":{\"prompt\":120,\"completion\":18,\"total\":138}}}\n\ndata: [DONE]\n\n"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1705,6 +1716,186 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/chat/runs": {
|
||||
"get": {
|
||||
"operationId": "listChatRuns",
|
||||
"summary": "List Sim Chat Runs",
|
||||
"description": "List a bounded page of the authenticated user's root Mothership runs for one workspace, newest first. This private history surface requires a personal API key. It returns durable run state and safe chat metadata only; stream IDs, continuation tokens, model reasoning, tool payloads, and errors are never exposed. Pass `nextCursor` back as `cursor` to load another page.",
|
||||
"tags": ["Chat"],
|
||||
"security": [
|
||||
{
|
||||
"apiKey": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "workspaceId",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": { "type": "string" },
|
||||
"description": "Workspace whose owned Sim Chat runs should be listed."
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"active",
|
||||
"paused_waiting_for_tool",
|
||||
"resuming",
|
||||
"complete",
|
||||
"error",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"description": "Return only runs with this durable status."
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 30 },
|
||||
"description": "Maximum runs to return."
|
||||
},
|
||||
{
|
||||
"name": "cursor",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "string", "minLength": 1 },
|
||||
"description": "Opaque cursor returned by the previous page."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A bounded page of safe chat run summaries.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["data", "nextCursor"],
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/V2ChatRunSummary" }
|
||||
},
|
||||
"nextCursor": { "type": ["string", "null"] }
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"data": [
|
||||
{
|
||||
"runId": "4bfa6f89-b746-43be-8246-bf1c69b58593",
|
||||
"chatId": "80a47295-040e-46f9-9ea8-ad78eff3bcab",
|
||||
"chatTitle": "Review release workflow",
|
||||
"status": "complete",
|
||||
"startedAt": "2026-08-08T18:29:00.000Z",
|
||||
"completedAt": "2026-08-08T18:30:00.000Z"
|
||||
}
|
||||
],
|
||||
"nextCursor": null
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/V2BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/V2Unauthorized"
|
||||
},
|
||||
"403": {
|
||||
"$ref": "#/components/responses/V2Forbidden"
|
||||
},
|
||||
"429": {
|
||||
"$ref": "#/components/responses/V2RateLimited"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/chat/runs/{runId}": {
|
||||
"get": {
|
||||
"operationId": "getChatRun",
|
||||
"summary": "Get Sim Chat Run",
|
||||
"description": "Poll one owned root Mothership run. In addition to durable status and chat metadata, the response contains accumulated root-assistant text and chronological display-safe activity updates when complete replay is available. A terminal run falls back to its persisted assistant response after replay expires. Raw argument/result objects, model reasoning, upstream errors, stream IDs, and continuation tokens are never returned; activity labels may summarize the same user-visible target or operation shown in Sim Home. Runs outside the user, workspace, live Mothership chat, or root-run scope all return the same 404.",
|
||||
"tags": ["Chat"],
|
||||
"security": [
|
||||
{
|
||||
"apiKey": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "runId",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "format": "uuid" },
|
||||
"description": "Run ID returned by Ask Sim Chat or List Sim Chat Runs."
|
||||
},
|
||||
{
|
||||
"name": "workspaceId",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": { "type": "string" },
|
||||
"description": "Workspace the run and its chat must belong to."
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A safe snapshot of the chat run.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["data"],
|
||||
"properties": {
|
||||
"data": { "$ref": "#/components/schemas/V2ChatRunDetail" }
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"data": {
|
||||
"runId": "4bfa6f89-b746-43be-8246-bf1c69b58593",
|
||||
"chatId": "80a47295-040e-46f9-9ea8-ad78eff3bcab",
|
||||
"chatTitle": "Review release workflow",
|
||||
"status": "active",
|
||||
"startedAt": "2026-08-08T18:29:00.000Z",
|
||||
"completedAt": null,
|
||||
"response": "I reviewed the release workflow.",
|
||||
"activities": [
|
||||
{
|
||||
"kind": "tool",
|
||||
"id": "tool-1",
|
||||
"label": "Read workflow",
|
||||
"state": "complete"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/V2BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/V2Unauthorized"
|
||||
},
|
||||
"403": {
|
||||
"$ref": "#/components/responses/V2Forbidden"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/V2NotFound"
|
||||
},
|
||||
"429": {
|
||||
"$ref": "#/components/responses/V2RateLimited"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/V2ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v2/billing/status": {
|
||||
"get": {
|
||||
"operationId": "getBillingStatus",
|
||||
@@ -2738,6 +2929,88 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"V2ChatRunSummary": {
|
||||
"type": "object",
|
||||
"required": ["runId", "chatId", "chatTitle", "status", "startedAt", "completedAt"],
|
||||
"properties": {
|
||||
"runId": { "type": "string", "format": "uuid" },
|
||||
"chatId": { "type": "string", "format": "uuid" },
|
||||
"chatTitle": { "type": ["string", "null"] },
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"active",
|
||||
"paused_waiting_for_tool",
|
||||
"resuming",
|
||||
"complete",
|
||||
"error",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"startedAt": { "type": "string", "format": "date-time" },
|
||||
"completedAt": { "type": ["string", "null"], "format": "date-time" }
|
||||
}
|
||||
},
|
||||
"V2ChatRunActivity": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind", "id", "label", "state"],
|
||||
"properties": {
|
||||
"kind": { "type": "string", "enum": ["subagent", "tool"] },
|
||||
"id": { "type": "string" },
|
||||
"parentId": { "type": "string" },
|
||||
"label": { "type": "string" },
|
||||
"state": { "type": "string", "enum": ["running", "complete", "error"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind", "parentId", "delta"],
|
||||
"properties": {
|
||||
"kind": { "type": "string", "const": "narration" },
|
||||
"parentId": { "type": "string" },
|
||||
"delta": { "type": "string" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"V2ChatRunDetail": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"runId",
|
||||
"chatId",
|
||||
"chatTitle",
|
||||
"status",
|
||||
"startedAt",
|
||||
"completedAt",
|
||||
"response",
|
||||
"activities"
|
||||
],
|
||||
"properties": {
|
||||
"runId": { "type": "string", "format": "uuid" },
|
||||
"chatId": { "type": "string", "format": "uuid" },
|
||||
"chatTitle": { "type": ["string", "null"] },
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"active",
|
||||
"paused_waiting_for_tool",
|
||||
"resuming",
|
||||
"complete",
|
||||
"error",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"startedAt": { "type": "string", "format": "date-time" },
|
||||
"completedAt": { "type": ["string", "null"], "format": "date-time" },
|
||||
"response": { "type": "string" },
|
||||
"activities": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/V2ChatRunActivity" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"V2Error": {
|
||||
"type": "object",
|
||||
"required": ["error"],
|
||||
|
||||
@@ -184,6 +184,14 @@ vi.mock('@/lib/core/config/env', () => ({ env: mockEnv }))
|
||||
vi.mock('@/lib/core/config/env-flags', () => mockEnvFlags)
|
||||
vi.mock('@/lib/core/utils/request', () => ({ generateRequestId: () => 'request-1' }))
|
||||
|
||||
vi.mock('@/executor/utils/resolved-secret-trace-registry', () => ({
|
||||
ResolvedSecretTraceRegistry: class MockResolvedSecretTraceRegistry {
|
||||
getModelEgressSnapshot() {
|
||||
return { complete: true }
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@sim/utils/id', () => ({ generateId: mockGenerateId }))
|
||||
|
||||
import { MAX_V2_CHAT_BODY_BYTES } from '@/lib/api/contracts/v2/chat'
|
||||
@@ -299,6 +307,55 @@ describe('POST /api/v2/chat', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The one-off CLI turn (`sim chat ask`) is a command, not a conversation the
|
||||
* workspace accumulates, so it must leave nothing for the chat list or
|
||||
* `sim chats list` to surface — matching the Mothership block, which mints
|
||||
* its own conversation id and never writes a chat row. The turn still gets a
|
||||
* chat id and a continuation token, so the conversation remains continuable.
|
||||
*/
|
||||
it('creates no chat row when the caller opts out of persistence', async () => {
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'What is here?',
|
||||
persistChat: false,
|
||||
})
|
||||
const stream = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockResolveOrCreateChat).not.toHaveBeenCalled()
|
||||
expect(mockPersistCopilotUserMessage).not.toHaveBeenCalled()
|
||||
expect(stream).toContain('"type":"complete"')
|
||||
// No Sim-side row, so the token must not claim Sim persistence.
|
||||
expect(mockIssueV2ChatContinuationToken).toHaveBeenCalledWith(
|
||||
expect.not.objectContaining({ persistence: 'sim' })
|
||||
)
|
||||
})
|
||||
|
||||
it('still persists the chat when the caller does not opt out', async () => {
|
||||
await callChat({ workspaceId: 'workspace-1', prompt: 'What is here?' })
|
||||
expect(mockResolveOrCreateChat).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires persisted chat storage for asynchronous execution', async () => {
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'What is here?',
|
||||
async: true,
|
||||
persistChat: false,
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(await response.json()).toEqual({
|
||||
error: {
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Asynchronous chat requires persistChat to be true',
|
||||
},
|
||||
})
|
||||
expect(mockResolveOrCreateChat).not.toHaveBeenCalled()
|
||||
expect(mockRunWorkspaceChat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('streams a personal-key chat and bills its authenticated actor', async () => {
|
||||
const response = await callChat({ workspaceId: 'workspace-1', prompt: 'What is here?' })
|
||||
const stream = await response.text()
|
||||
@@ -309,6 +366,7 @@ describe('POST /api/v2/chat', () => {
|
||||
expect(stream).toContain('"type":"session"')
|
||||
expect(stream).toContain('"continuationToken":"continuation-new"')
|
||||
expect(stream).toContain('"chatId":"chat-1"')
|
||||
expect(stream).not.toContain('"runId":"run-1"')
|
||||
expect(stream).toContain('"delta":"Hello from Sim"')
|
||||
expect(stream).toContain('"type":"complete"')
|
||||
expect(stream).toContain('data: [DONE]')
|
||||
@@ -403,6 +461,17 @@ describe('POST /api/v2/chat', () => {
|
||||
workspaceId: 'workspace-1',
|
||||
})
|
||||
)
|
||||
/**
|
||||
* Title generation projects its input against the secret-trace registry and
|
||||
* fails closed when none is supplied, so omitting this silently skips every
|
||||
* title on this route — the failure is a missing log line, not an error.
|
||||
* The registry must also report complete, or the projection is still unsafe.
|
||||
*/
|
||||
const titleParams = mockFireTitleGeneration.mock.calls[0]![0] as {
|
||||
resolvedSecretTraceRegistry?: { getModelEgressSnapshot(): { complete: boolean } }
|
||||
}
|
||||
expect(titleParams.resolvedSecretTraceRegistry).toBeDefined()
|
||||
expect(titleParams.resolvedSecretTraceRegistry!.getModelEgressSnapshot().complete).toBe(true)
|
||||
expect(mockPublisherClose).toHaveBeenCalledTimes(1)
|
||||
expect(mockScheduleBufferCleanup).toHaveBeenCalledWith('message-1')
|
||||
expect(mockScheduleFilePreviewSessionCleanup).toHaveBeenCalledWith('message-1')
|
||||
@@ -559,7 +628,7 @@ describe('POST /api/v2/chat', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('does not hold the Go leg on run-segment creation but waits before finalizing it', async () => {
|
||||
it('does not hold a synchronous Go leg on run creation but waits before finalizing it', async () => {
|
||||
let resolveRunSegment!: () => void
|
||||
let resolveChat!: () => void
|
||||
mockCreateRunSegment.mockReturnValueOnce(
|
||||
@@ -593,7 +662,41 @@ describe('POST /api/v2/chat', () => {
|
||||
expect(mockFinalizeStream).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps a synced turn working when run-segment creation fails', async () => {
|
||||
it('creates an asynchronous run durably before starting Go or exposing its session', async () => {
|
||||
let resolveRunSegment!: () => void
|
||||
mockCreateRunSegment.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
resolveRunSegment = () => resolve({ id: 'run-1' })
|
||||
})
|
||||
)
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'Continue',
|
||||
async: true,
|
||||
})
|
||||
const reader = response.body!.getReader()
|
||||
let firstReadSettled = false
|
||||
const firstRead = reader.read().then((result) => {
|
||||
firstReadSettled = true
|
||||
return result
|
||||
})
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
expect(mockRunWorkspaceChat).not.toHaveBeenCalled()
|
||||
expect(firstReadSettled).toBe(false)
|
||||
|
||||
resolveRunSegment()
|
||||
const first = await firstRead
|
||||
expect(new TextDecoder().decode(first.value)).toContain('"runId":"run-1"')
|
||||
while (!(await reader.read()).done) {
|
||||
// Drain the completion so route cleanup can release its lease.
|
||||
}
|
||||
expect(mockRunWorkspaceChat).toHaveBeenCalledTimes(1)
|
||||
expect(mockFinalizeStream).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps a synchronous synced turn working when run creation fails', async () => {
|
||||
mockCreateRunSegment.mockRejectedValueOnce(new Error('run table unavailable'))
|
||||
|
||||
const response = await callChat({ workspaceId: 'workspace-1', prompt: 'Continue' })
|
||||
@@ -601,9 +704,28 @@ describe('POST /api/v2/chat', () => {
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(stream).toContain('"type":"complete"')
|
||||
expect(stream).not.toContain('"runId":"run-1"')
|
||||
expect(mockRunWorkspaceChat).toHaveBeenCalledTimes(1)
|
||||
expect(mockFinalizeStream).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('fails before acceptance when durable run creation fails', async () => {
|
||||
mockCreateRunSegment.mockRejectedValueOnce(new Error('run table unavailable'))
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'Continue',
|
||||
async: true,
|
||||
})
|
||||
const stream = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(stream).not.toContain('"type":"session"')
|
||||
expect(stream).toContain('"code":"INTERNAL_ERROR"')
|
||||
expect(mockRunWorkspaceChat).not.toHaveBeenCalled()
|
||||
expect(mockFinalizeStream).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a pre-acceptance failure without exposing a continuation token', async () => {
|
||||
mockRunWorkspaceChat.mockResolvedValueOnce({
|
||||
success: false,
|
||||
@@ -681,6 +803,31 @@ describe('POST /api/v2/chat', () => {
|
||||
expect(mockPublishStatusChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects asynchronous continuation of a legacy Go-only chat', async () => {
|
||||
mockVerifyV2ChatContinuationToken.mockReturnValueOnce({
|
||||
valid: true,
|
||||
chatId: 'private-chat-id',
|
||||
})
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'Tell me more',
|
||||
continuationToken: 'continuation-old',
|
||||
async: true,
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(await response.json()).toEqual({
|
||||
error: {
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Asynchronous chat requires a persisted chat',
|
||||
},
|
||||
})
|
||||
expect(mockResolveBillingAttribution).not.toHaveBeenCalled()
|
||||
expect(mockCreateRunSegment).not.toHaveBeenCalled()
|
||||
expect(mockRunWorkspaceChat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('continues an existing persisted personal chat with UI replay enabled', async () => {
|
||||
mockVerifyV2ChatContinuationToken.mockReturnValueOnce({
|
||||
valid: true,
|
||||
@@ -1213,6 +1360,31 @@ describe('POST /api/v2/chat', () => {
|
||||
expect(mockPublishStatusChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires a personal API key for asynchronous execution', async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({
|
||||
...RATE_LIMIT,
|
||||
keyType: 'workspace',
|
||||
workspaceId: 'workspace-1',
|
||||
})
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'Summarize it',
|
||||
async: true,
|
||||
})
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(await response.json()).toEqual({
|
||||
error: {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Asynchronous chat requires a personal API key',
|
||||
},
|
||||
})
|
||||
expect(mockResolveSystemBillingAttribution).not.toHaveBeenCalled()
|
||||
expect(mockResolveOrCreateChat).not.toHaveBeenCalled()
|
||||
expect(mockRunWorkspaceChat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('routes a workspace-key abort by its owner while preserving the billing actor body', async () => {
|
||||
mockGenerateId
|
||||
.mockReset()
|
||||
@@ -1485,6 +1657,150 @@ describe('POST /api/v2/chat', () => {
|
||||
expect(mockCleanupAbortMarker).toHaveBeenCalledWith('message-1')
|
||||
})
|
||||
|
||||
it('keeps an accepted asynchronous turn running after its reader disconnects', async () => {
|
||||
let settle!: () => void
|
||||
let lifecycleSignal: AbortSignal | undefined
|
||||
let userStopSignal: AbortSignal | undefined
|
||||
mockRunWorkspaceChat.mockImplementationOnce(
|
||||
(input) =>
|
||||
new Promise((resolve) => {
|
||||
lifecycleSignal = input.abortSignal
|
||||
userStopSignal = input.userStopSignal
|
||||
input.onInitialStreamAccepted?.()
|
||||
settle = () =>
|
||||
resolve({
|
||||
success: true,
|
||||
content: 'Finished in the background',
|
||||
contentBlocks: [],
|
||||
toolCalls: [],
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'keep going',
|
||||
async: true,
|
||||
})
|
||||
const reader = response.body!.getReader()
|
||||
const acceptedSession = new TextDecoder().decode((await reader.read()).value)
|
||||
expect(acceptedSession).toContain('"runId":"run-1"')
|
||||
|
||||
await reader.cancel('async_receipt_received')
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
expect(mockRequestExplicitStreamAbort).not.toHaveBeenCalled()
|
||||
expect(lifecycleSignal?.aborted).toBe(false)
|
||||
expect(userStopSignal?.aborted).toBe(false)
|
||||
expect(mockReleasePendingChatStream).not.toHaveBeenCalled()
|
||||
|
||||
settle()
|
||||
await vi.waitFor(() => expect(mockReleasePendingChatStream).toHaveBeenCalledTimes(1))
|
||||
expect(mockFinalizeStream).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ success: true, content: 'Finished in the background' }),
|
||||
expect.any(Object),
|
||||
'run-1',
|
||||
'success',
|
||||
'request-1'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not classify an accepted asynchronous turn as cancelled when its request aborts', async () => {
|
||||
const requestAbortController = new AbortController()
|
||||
let settle!: () => void
|
||||
let userStopSignal: AbortSignal | undefined
|
||||
mockRunWorkspaceChat.mockImplementationOnce(
|
||||
(input) =>
|
||||
new Promise((resolve) => {
|
||||
userStopSignal = input.userStopSignal
|
||||
input.onInitialStreamAccepted?.()
|
||||
settle = () =>
|
||||
resolve({
|
||||
success: true,
|
||||
content: 'Finished after request disconnect',
|
||||
contentBlocks: [],
|
||||
toolCalls: [],
|
||||
})
|
||||
})
|
||||
)
|
||||
const request = new NextRequest('http://localhost:3000/api/v2/chat', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': 'caller-platform-key',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'keep going',
|
||||
async: true,
|
||||
}),
|
||||
signal: requestAbortController.signal,
|
||||
})
|
||||
|
||||
const response = await POST(request)
|
||||
const reader = response.body!.getReader()
|
||||
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"runId":"run-1"')
|
||||
|
||||
requestAbortController.abort()
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
expect(mockRequestExplicitStreamAbort).not.toHaveBeenCalled()
|
||||
expect(userStopSignal?.aborted).toBe(false)
|
||||
|
||||
settle()
|
||||
while (!(await reader.read()).done) {
|
||||
// Drain the completion so route cleanup can release its lease.
|
||||
}
|
||||
await vi.waitFor(() => expect(mockReleasePendingChatStream).toHaveBeenCalledTimes(1))
|
||||
expect(mockFinalizeStream).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ success: true, content: 'Finished after request disconnect' }),
|
||||
expect.any(Object),
|
||||
'run-1',
|
||||
'success',
|
||||
'request-1'
|
||||
)
|
||||
})
|
||||
|
||||
it('still stops an asynchronous turn when the reader disconnects before acceptance', async () => {
|
||||
let settle!: () => void
|
||||
let userStopSignal: AbortSignal | undefined
|
||||
mockRunWorkspaceChat.mockImplementationOnce(
|
||||
(input) =>
|
||||
new Promise((resolve) => {
|
||||
userStopSignal = input.userStopSignal
|
||||
settle = () =>
|
||||
resolve({
|
||||
success: false,
|
||||
cancelled: true,
|
||||
content: '',
|
||||
contentBlocks: [],
|
||||
toolCalls: [],
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
const response = await callChat({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'keep going',
|
||||
async: true,
|
||||
})
|
||||
await vi.waitFor(() => expect(mockRunWorkspaceChat).toHaveBeenCalledTimes(1))
|
||||
await response.body!.cancel('pre_accept_disconnect')
|
||||
|
||||
await vi.waitFor(() => expect(mockRequestExplicitStreamAbort).toHaveBeenCalledTimes(1))
|
||||
expect(userStopSignal?.aborted).toBe(true)
|
||||
expect(userStopSignal?.reason).toBe('user_stop:abortActiveStream')
|
||||
|
||||
settle()
|
||||
await vi.waitFor(() => expect(mockReleasePendingChatStream).toHaveBeenCalledTimes(1))
|
||||
expect(mockFinalizeStream).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cancelled: true }),
|
||||
expect.any(Object),
|
||||
'run-1',
|
||||
'cancelled',
|
||||
'request-1'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not start a lifecycle when Stop wins before workspace chat begins', async () => {
|
||||
mockRegisterActiveStream.mockImplementationOnce(
|
||||
(
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
getAccessibleCopilotChatContinuationMetadata,
|
||||
resolveOrCreateChat,
|
||||
} from '@/lib/copilot/chat/lifecycle'
|
||||
import { ChatActivityProjector, type V2ChatActivity } from '@/lib/copilot/chat/public-activity'
|
||||
import {
|
||||
buildCopilotTurnOnComplete,
|
||||
buildCopilotTurnOnError,
|
||||
@@ -62,7 +63,6 @@ import { isAuthDisabled } from '@/lib/core/config/env-flags'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { checkRateLimit, resolveWorkspaceAccess } from '@/app/api/v1/middleware'
|
||||
import { ChatActivityProjector, type V2ChatActivity } from '@/app/api/v2/chat/activity'
|
||||
import { v2ApiGateError } from '@/app/api/v2/lib/gate'
|
||||
import {
|
||||
rateLimitHeaders,
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
v2ValidationError,
|
||||
v2WorkspaceAccessError,
|
||||
} from '@/app/api/v2/lib/response'
|
||||
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
|
||||
|
||||
export const maxDuration = 3600
|
||||
export const runtime = 'nodejs'
|
||||
@@ -82,6 +83,22 @@ const HEARTBEAT_INTERVAL_MS = 15_000
|
||||
const ATTACHMENT_ONLY_PROMPT = 'Please inspect the attached file(s).'
|
||||
const V2_CHAT_TITLE_MODEL = 'claude-opus-4-8'
|
||||
|
||||
/**
|
||||
* An empty, complete secret-trace registry for title generation.
|
||||
*
|
||||
* `projectResolvedSecretModelContent` fails closed on a missing registry, so
|
||||
* without one every title on this route is skipped. The empty registry is the
|
||||
* accurate claim rather than a bypass: the title is generated from
|
||||
* `effectivePrompt`, which is the request body's own `prompt` verbatim — this
|
||||
* route runs no workflow and resolves no secrets into it, so there is nothing
|
||||
* for the matcher to redact. Shared because it is immutable and the matcher
|
||||
* cache is keyed on the instance.
|
||||
*
|
||||
* If this route ever resolves secrets into the prompt, thread that execution's
|
||||
* real registry through here instead.
|
||||
*/
|
||||
const V2_CHAT_TITLE_SECRET_REGISTRY = new ResolvedSecretTraceRegistry([])
|
||||
|
||||
interface SyncedChat {
|
||||
chat: { title?: string | null } | null
|
||||
isNewChat: boolean
|
||||
@@ -130,8 +147,16 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
: parsed.response
|
||||
}
|
||||
|
||||
const { workspaceId, prompt, continuationToken, readOnly, attachments, contexts } =
|
||||
parsed.data.body
|
||||
const {
|
||||
workspaceId,
|
||||
prompt,
|
||||
continuationToken,
|
||||
readOnly,
|
||||
async: asyncRequested,
|
||||
attachments,
|
||||
contexts,
|
||||
persistChat,
|
||||
} = parsed.data.body
|
||||
const credentialType = rateLimit.keyType === 'workspace' ? 'workspace' : 'personal'
|
||||
const effectivePrompt = prompt.trim() ? prompt : ATTACHMENT_ONLY_PROMPT
|
||||
// DISABLE_AUTH produces an anonymous pseudo-personal principal. It is not
|
||||
@@ -155,6 +180,17 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
})
|
||||
}
|
||||
|
||||
if (asyncRequested && rateLimit.keyType !== 'personal') {
|
||||
return v2Error('FORBIDDEN', 'Asynchronous chat requires a personal API key', {
|
||||
headers: rateLimitHeaders(rateLimit),
|
||||
})
|
||||
}
|
||||
if (asyncRequested && !persistChat) {
|
||||
return v2Error('BAD_REQUEST', 'Asynchronous chat requires persistChat to be true', {
|
||||
headers: rateLimitHeaders(rateLimit),
|
||||
})
|
||||
}
|
||||
|
||||
const continuation = continuationToken
|
||||
? await verifyV2ChatContinuationToken(continuationToken, {
|
||||
workspaceId,
|
||||
@@ -203,6 +239,11 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (asyncRequested && continuation?.valid && !continuedSyncedChat) {
|
||||
return v2Error('BAD_REQUEST', 'Asynchronous chat requires a persisted chat', {
|
||||
headers: rateLimitHeaders(rateLimit),
|
||||
})
|
||||
}
|
||||
|
||||
const preparedAttachments = prepareV2ChatAttachments(attachments)
|
||||
if (!preparedAttachments.success) {
|
||||
@@ -236,7 +277,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
|
||||
if (continuation?.valid) {
|
||||
chatId = continuation.chatId
|
||||
} else if (shouldSyncChat) {
|
||||
} else if (shouldSyncChat && persistChat) {
|
||||
/* `persistChat: false` gates chat *creation* only. It deliberately does
|
||||
not reach the continuation branch above: detaching a chat that is
|
||||
already persisted would silently drop the rest of its transcript. */
|
||||
const created = await resolveOrCreateChat({
|
||||
userId: authenticatedUserId,
|
||||
workspaceId,
|
||||
@@ -321,7 +365,11 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
let lifecycleStarted = false
|
||||
let abortRequested = false
|
||||
let allowExplicitAbort = true
|
||||
let sessionAccepted = false
|
||||
let explicitAbortRequest: Promise<void> | undefined
|
||||
const acceptedAsyncTurnIsDetached = () => asyncRequested && sessionAccepted
|
||||
const requestAbortStopsLifecycle = () =>
|
||||
request.signal.aborted && !acceptedAsyncTurnIsDetached()
|
||||
|
||||
const requestExplicitAbortOnce = () => {
|
||||
if (!lifecycleStarted || !allowExplicitAbort) return undefined
|
||||
@@ -346,12 +394,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* A disconnected public reader is an explicit stop request. Match the web
|
||||
* UI's Stop path: stop Sim-side work, mark the detached Go execution, and
|
||||
* keep draining the active Go leg so persistence settles before cleanup.
|
||||
* The route owns the chat lease until that lifecycle has unwound.
|
||||
* A normal disconnect is an explicit stop request. Once an asynchronous
|
||||
* caller has received its durable session receipt, however, disconnect is
|
||||
* passive and the route keeps draining the Go leg into persisted state.
|
||||
* In either case the route owns the chat lease until lifecycle settlement.
|
||||
*/
|
||||
const abortLifecycle = () => {
|
||||
if (acceptedAsyncTurnIsDetached()) return
|
||||
abortRequested = true
|
||||
requestExplicitAbortOnce()
|
||||
if (allowExplicitAbort && !userStopController.signal.aborted) {
|
||||
@@ -383,7 +432,6 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
for (const activity of activities) send({ type: 'activity', data: activity })
|
||||
}
|
||||
|
||||
let sessionSent = false
|
||||
let pendingTitle = syncedChat?.chat?.title?.trim() || undefined
|
||||
let publishedTitle: string | undefined
|
||||
let replayFinalized = false
|
||||
@@ -392,20 +440,31 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const next = title.trim()
|
||||
if (!next) return
|
||||
pendingTitle = next
|
||||
if (!sessionSent || next === publishedTitle) return
|
||||
if (send({ type: 'session', chatId, title: next })) publishedTitle = next
|
||||
if (!sessionAccepted || next === publishedTitle) return
|
||||
if (
|
||||
send({
|
||||
type: 'session',
|
||||
chatId,
|
||||
...(asyncRequested && runId ? { runId } : {}),
|
||||
title: next,
|
||||
})
|
||||
) {
|
||||
publishedTitle = next
|
||||
}
|
||||
}
|
||||
const sendSession = () => {
|
||||
if (sessionSent) return
|
||||
sessionSent = true
|
||||
if (sessionAccepted) return
|
||||
const sent = send({
|
||||
type: 'session',
|
||||
continuationToken: refreshedContinuationToken,
|
||||
requestId,
|
||||
...(syncedChat ? { chatId } : {}),
|
||||
...(asyncRequested && runId ? { runId } : {}),
|
||||
...(pendingTitle ? { title: pendingTitle } : {}),
|
||||
})
|
||||
if (sent && pendingTitle) publishedTitle = pendingTitle
|
||||
if (!sent) return
|
||||
sessionAccepted = true
|
||||
if (pendingTitle) publishedTitle = pendingTitle
|
||||
}
|
||||
heartbeatId = setInterval(() => {
|
||||
if (!cancelled && publicStreamOpen) {
|
||||
@@ -421,7 +480,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
|
||||
if (replayPublisher && syncedChat && executionId && runId) {
|
||||
await Promise.all([resetBuffer(messageId), clearFilePreviewSessions(messageId)])
|
||||
runSegmentPromise = createRunSegment({
|
||||
const createRunSegmentPromise = createRunSegment({
|
||||
id: runId,
|
||||
executionId,
|
||||
chatId,
|
||||
@@ -430,11 +489,15 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
streamId: messageId,
|
||||
model: null,
|
||||
requestContext: { requestId, source: 'v2_chat' },
|
||||
}).catch((error) => {
|
||||
logger.warn(`[${requestId}] Failed to create v2 chat run segment`, {
|
||||
error: getErrorMessage(error),
|
||||
})
|
||||
})
|
||||
runSegmentPromise = asyncRequested
|
||||
? createRunSegmentPromise
|
||||
: createRunSegmentPromise.catch((error) => {
|
||||
logger.warn(`[${requestId}] Failed to create v2 chat run segment`, {
|
||||
error: getErrorMessage(error),
|
||||
})
|
||||
})
|
||||
if (asyncRequested) await runSegmentPromise
|
||||
replayPublisher.publish({
|
||||
type: MothershipStreamV1EventType.session,
|
||||
payload: { kind: MothershipStreamV1SessionKind.chat, chatId },
|
||||
@@ -458,6 +521,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
workspaceId,
|
||||
billingAttribution,
|
||||
requestId,
|
||||
resolvedSecretTraceRegistry: V2_CHAT_TITLE_SECRET_REGISTRY,
|
||||
publisher: {
|
||||
publish(event) {
|
||||
replayPublisher.publish(event)
|
||||
@@ -519,7 +583,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
: result.cancelled ||
|
||||
lifecycleAbortController.signal.aborted ||
|
||||
userStopController.signal.aborted ||
|
||||
request.signal.aborted
|
||||
requestAbortStopsLifecycle()
|
||||
? RequestTraceV1Outcome.cancelled
|
||||
: RequestTraceV1Outcome.error
|
||||
await finalizeStream(result, replayPublisher, runId, replayOutcome, requestId)
|
||||
@@ -540,13 +604,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
return
|
||||
}
|
||||
|
||||
if (!sessionSent) {
|
||||
if (!sessionAccepted) {
|
||||
throw new Error('Mothership did not acknowledge the initial chat stream')
|
||||
}
|
||||
if (
|
||||
lifecycleAbortController.signal.aborted ||
|
||||
userStopController.signal.aborted ||
|
||||
request.signal.aborted ||
|
||||
requestAbortStopsLifecycle() ||
|
||||
result.cancelled
|
||||
) {
|
||||
requestExplicitAbortOnce()
|
||||
@@ -589,7 +653,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const aborted =
|
||||
lifecycleAbortController.signal.aborted ||
|
||||
userStopController.signal.aborted ||
|
||||
request.signal.aborted ||
|
||||
requestAbortStopsLifecycle() ||
|
||||
isAbortError(error)
|
||||
const terminalResult: OrchestratorResult = {
|
||||
success: false,
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
authenticate: vi.fn(),
|
||||
checkPreauth: vi.fn(),
|
||||
checkOperationRate: vi.fn(),
|
||||
gate: vi.fn(),
|
||||
readRun: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => ({
|
||||
authenticateV2ApiKey: mocks.authenticate,
|
||||
V2ApiKeyUnauthenticatedError: class V2ApiKeyUnauthenticatedError extends Error {},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/rate-limiter', () => ({
|
||||
getRateLimit: () => ({ maxTokens: 100, refillRate: 50, refillIntervalMs: 60_000 }),
|
||||
RateLimiter: class RateLimiter {
|
||||
checkRateLimitDirect = mocks.checkPreauth
|
||||
checkRateLimitDirectOrThrow = mocks.checkOperationRate
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v2/lib/gate', () => ({ v2ApiGateError: mocks.gate }))
|
||||
|
||||
vi.mock('@/lib/copilot/chat/application/runs', () => ({
|
||||
readChatRun: {
|
||||
operation: { id: 'chat.runs.read' },
|
||||
execute: mocks.readRun,
|
||||
},
|
||||
}))
|
||||
|
||||
import { ChatRunProgressUnavailableError } from '@/lib/copilot/chat/application/errors'
|
||||
import { InsufficientWorkspacePermissionsError } from '@/lib/core/application'
|
||||
import { OrchestrationError } from '@/lib/core/orchestration/types'
|
||||
import { GET } from '@/app/api/v2/chat/runs/[runId]/route'
|
||||
|
||||
const RUN_ID = '4bfa6f89-b746-43be-8246-bf1c69b58593'
|
||||
const CHAT_ID = '80a47295-040e-46f9-9ea8-ad78eff3bcab'
|
||||
const auth = {
|
||||
principal: {
|
||||
kind: 'personal_api_key' as const,
|
||||
userId: 'user-1',
|
||||
keyId: 'key-1',
|
||||
},
|
||||
rolloutUserId: 'user-1',
|
||||
rateLimitSubjectIds: ['api-key:key-1', 'user:user-1'] as const,
|
||||
rateLimitSubscription: null,
|
||||
keyType: 'personal' as const,
|
||||
}
|
||||
const run = {
|
||||
runId: RUN_ID,
|
||||
chatId: CHAT_ID,
|
||||
chatTitle: 'Release plan',
|
||||
streamId: 'stream-1',
|
||||
status: 'active' as const,
|
||||
startedAt: new Date('2026-08-08T12:00:00.000Z'),
|
||||
completedAt: null,
|
||||
}
|
||||
const context = () => ({ params: Promise.resolve({ runId: RUN_ID }) })
|
||||
|
||||
function callDetail() {
|
||||
return GET(
|
||||
new NextRequest(`http://localhost:3000/api/v2/chat/runs/${RUN_ID}?workspaceId=workspace-1`),
|
||||
context()
|
||||
)
|
||||
}
|
||||
|
||||
describe('GET /api/v2/chat/runs/[runId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.authenticate.mockResolvedValue(auth)
|
||||
mocks.gate.mockResolvedValue(null)
|
||||
mocks.checkPreauth.mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 599,
|
||||
resetAt: new Date('2026-08-08T13:00:00.000Z'),
|
||||
})
|
||||
mocks.checkOperationRate.mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 99,
|
||||
resetAt: new Date('2026-08-08T13:00:00.000Z'),
|
||||
})
|
||||
mocks.readRun.mockResolvedValue({
|
||||
run,
|
||||
status: 'active',
|
||||
completedAt: null,
|
||||
response: 'Working',
|
||||
activities: [{ kind: 'tool', id: 'tool-1', label: 'Reading file', state: 'running' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('projects the authorized application result through the public contract', async () => {
|
||||
const request = new NextRequest(
|
||||
`http://localhost:3000/api/v2/chat/runs/${RUN_ID}?workspaceId=workspace-1`
|
||||
)
|
||||
const response = await GET(request, context())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({
|
||||
data: {
|
||||
runId: RUN_ID,
|
||||
chatId: CHAT_ID,
|
||||
chatTitle: 'Release plan',
|
||||
status: 'active',
|
||||
startedAt: '2026-08-08T12:00:00.000Z',
|
||||
completedAt: null,
|
||||
response: 'Working',
|
||||
activities: [{ kind: 'tool', id: 'tool-1', label: 'Reading file', state: 'running' }],
|
||||
},
|
||||
})
|
||||
expect(mocks.readRun).toHaveBeenCalledWith({
|
||||
principal: auth.principal,
|
||||
input: { runId: RUN_ID, workspaceId: 'workspace-1' },
|
||||
request,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
new InsufficientWorkspacePermissionsError(),
|
||||
new OrchestrationError('not_found', 'Workspace not found'),
|
||||
new OrchestrationError('not_found', 'Chat run not found'),
|
||||
])('uniformly conceals inaccessible scoped runs', async (error) => {
|
||||
mocks.readRun.mockRejectedValue(error)
|
||||
|
||||
const response = await callDetail()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(await response.json()).toEqual({
|
||||
error: { code: 'NOT_FOUND', message: 'Chat run not found' },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns a retryable 503 for temporarily unavailable progress', async () => {
|
||||
mocks.readRun.mockRejectedValue(new ChatRunProgressUnavailableError())
|
||||
|
||||
const response = await callDetail()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect((await response.json()).error.code).toBe('SERVICE_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('does not disguise unexpected infrastructure failures as absence', async () => {
|
||||
mocks.readRun.mockRejectedValue(new Error('database unavailable'))
|
||||
|
||||
const response = await callDetail()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(await response.json()).toEqual({
|
||||
error: { code: 'INTERNAL_ERROR', message: 'Internal server error' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { v2GetChatRunContract } from '@/lib/api/contracts/v2/chat-runs'
|
||||
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
|
||||
import { toPublicChatRunSummary } from '@/lib/copilot/chat/api/run-presenters'
|
||||
import { v2ChatRunErrorPolicies } from '@/lib/copilot/chat/api/run-route-policy'
|
||||
import { chatOperations } from '@/lib/copilot/chat/application/operations'
|
||||
import { readChatRun } from '@/lib/copilot/chat/application/runs'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const revalidate = 0
|
||||
|
||||
/** GET /api/v2/chat/runs/[runId] — safe pollable run status and progress. */
|
||||
export const GET = defineV2JsonRoute({
|
||||
contract: v2GetChatRunContract,
|
||||
auth: v2ApiKeyAuth,
|
||||
operation: chatOperations.readRun,
|
||||
rateLimit: v2RateLimits.publicApi,
|
||||
errorPolicy: v2ChatRunErrorPolicies.detail,
|
||||
mapInput: ({ params, query }) => ({
|
||||
runId: params.runId,
|
||||
workspaceId: query.workspaceId,
|
||||
}),
|
||||
useCase: readChatRun,
|
||||
present: ({ run, status, completedAt, response, activities }) => ({
|
||||
data: {
|
||||
...toPublicChatRunSummary(run),
|
||||
status,
|
||||
completedAt: completedAt?.toISOString() ?? null,
|
||||
response,
|
||||
activities,
|
||||
},
|
||||
}),
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
authenticate: vi.fn(),
|
||||
checkPreauth: vi.fn(),
|
||||
checkOperationRate: vi.fn(),
|
||||
gate: vi.fn(),
|
||||
listRuns: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => ({
|
||||
authenticateV2ApiKey: mocks.authenticate,
|
||||
V2ApiKeyUnauthenticatedError: class V2ApiKeyUnauthenticatedError extends Error {},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/rate-limiter', () => ({
|
||||
getRateLimit: () => ({ maxTokens: 100, refillRate: 50, refillIntervalMs: 60_000 }),
|
||||
RateLimiter: class RateLimiter {
|
||||
checkRateLimitDirect = mocks.checkPreauth
|
||||
checkRateLimitDirectOrThrow = mocks.checkOperationRate
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v2/lib/gate', () => ({ v2ApiGateError: mocks.gate }))
|
||||
|
||||
vi.mock('@/lib/copilot/chat/application/runs', () => ({
|
||||
listChatRuns: {
|
||||
operation: { id: 'chat.runs.list' },
|
||||
execute: mocks.listRuns,
|
||||
},
|
||||
}))
|
||||
|
||||
import { PrincipalKindAuthorizationError } from '@/lib/core/application'
|
||||
import { GET } from '@/app/api/v2/chat/runs/route'
|
||||
|
||||
const RUN_ID = '4bfa6f89-b746-43be-8246-bf1c69b58593'
|
||||
const CHAT_ID = '80a47295-040e-46f9-9ea8-ad78eff3bcab'
|
||||
const auth = {
|
||||
principal: {
|
||||
kind: 'personal_api_key' as const,
|
||||
userId: 'user-1',
|
||||
keyId: 'key-1',
|
||||
},
|
||||
rolloutUserId: 'user-1',
|
||||
rateLimitSubjectIds: ['api-key:key-1', 'user:user-1'] as const,
|
||||
rateLimitSubscription: null,
|
||||
keyType: 'personal' as const,
|
||||
}
|
||||
const run = {
|
||||
runId: RUN_ID,
|
||||
chatId: CHAT_ID,
|
||||
chatTitle: 'Release plan',
|
||||
streamId: 'stream-1',
|
||||
status: 'complete' as const,
|
||||
startedAt: new Date('2026-08-08T12:00:00.000Z'),
|
||||
completedAt: new Date('2026-08-08T12:01:00.000Z'),
|
||||
}
|
||||
|
||||
function callList(query = 'workspaceId=workspace-1') {
|
||||
return GET(new NextRequest(`http://localhost:3000/api/v2/chat/runs?${query}`))
|
||||
}
|
||||
|
||||
describe('GET /api/v2/chat/runs', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.authenticate.mockResolvedValue(auth)
|
||||
mocks.gate.mockResolvedValue(null)
|
||||
mocks.checkPreauth.mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 599,
|
||||
resetAt: new Date('2026-08-08T13:00:00.000Z'),
|
||||
})
|
||||
mocks.checkOperationRate.mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 99,
|
||||
resetAt: new Date('2026-08-08T13:00:00.000Z'),
|
||||
})
|
||||
mocks.listRuns.mockResolvedValue({ rows: [], hasMore: false })
|
||||
})
|
||||
|
||||
it('routes validated list input through the semantic application operation', async () => {
|
||||
mocks.listRuns.mockResolvedValue({ rows: [run], hasMore: true })
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/v2/chat/runs?workspaceId=workspace-1&status=complete&limit=1'
|
||||
)
|
||||
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.data).toEqual([
|
||||
{
|
||||
runId: RUN_ID,
|
||||
chatId: CHAT_ID,
|
||||
chatTitle: 'Release plan',
|
||||
status: 'complete',
|
||||
startedAt: '2026-08-08T12:00:00.000Z',
|
||||
completedAt: '2026-08-08T12:01:00.000Z',
|
||||
},
|
||||
])
|
||||
expect(body.nextCursor).toEqual(expect.any(String))
|
||||
expect(mocks.listRuns).toHaveBeenCalledWith({
|
||||
principal: auth.principal,
|
||||
input: {
|
||||
workspaceId: 'workspace-1',
|
||||
status: 'complete',
|
||||
limit: 1,
|
||||
cursorKeys: undefined,
|
||||
},
|
||||
request,
|
||||
})
|
||||
expect(mocks.checkOperationRate).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rejects malformed cursors before application execution', async () => {
|
||||
const response = await callList('workspaceId=workspace-1&cursor=not-a-cursor')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect((await response.json()).error.message).toMatch(/cursor does not match/i)
|
||||
expect(mocks.listRuns).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders the personal-key-only operation failure consistently', async () => {
|
||||
mocks.listRuns.mockRejectedValue(
|
||||
new PrincipalKindAuthorizationError('workspace_api_key', 'chat.runs.list')
|
||||
)
|
||||
|
||||
const response = await callList()
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(await response.json()).toEqual({
|
||||
error: { code: 'FORBIDDEN', message: 'Chat runs require a personal API key' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { v2ListChatRunsContract } from '@/lib/api/contracts/v2/chat-runs'
|
||||
import { INVALID_CURSOR_MESSAGE } from '@/lib/api/list-query'
|
||||
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
|
||||
import { toPublicChatRunSummary } from '@/lib/copilot/chat/api/run-presenters'
|
||||
import { v2ChatRunErrorPolicies } from '@/lib/copilot/chat/api/run-route-policy'
|
||||
import { chatOperations } from '@/lib/copilot/chat/application/operations'
|
||||
import { listChatRuns } from '@/lib/copilot/chat/application/runs'
|
||||
import { encodePublicChatRunCursor, PUBLIC_CHAT_RUN_SORT } from '@/lib/copilot/chat/public-runs'
|
||||
import { OrchestrationError } from '@/lib/core/orchestration/types'
|
||||
import { decodeSortedCursor, encodeSortedCursor } from '@/app/api/v2/lib/response'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const revalidate = 0
|
||||
|
||||
function decodeCursor(cursor: string | undefined) {
|
||||
const decoded = decodeSortedCursor(cursor, PUBLIC_CHAT_RUN_SORT)
|
||||
if (decoded.status === 'invalid') {
|
||||
throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE)
|
||||
}
|
||||
return decoded.status === 'ok' ? decoded.keys : undefined
|
||||
}
|
||||
|
||||
/** GET /api/v2/chat/runs — list owned root Mothership chat runs. */
|
||||
export const GET = defineV2JsonRoute({
|
||||
contract: v2ListChatRunsContract,
|
||||
auth: v2ApiKeyAuth,
|
||||
operation: chatOperations.listRuns,
|
||||
rateLimit: v2RateLimits.publicApi,
|
||||
errorPolicy: v2ChatRunErrorPolicies.default,
|
||||
mapInput: ({ query }) => ({
|
||||
workspaceId: query.workspaceId,
|
||||
status: query.status,
|
||||
limit: query.limit,
|
||||
cursorKeys: decodeCursor(query.cursor),
|
||||
}),
|
||||
useCase: listChatRuns,
|
||||
present: ({ rows, hasMore }) => {
|
||||
const last = rows.at(-1)
|
||||
return {
|
||||
data: rows.map(toPublicChatRunSummary),
|
||||
nextCursor:
|
||||
hasMore && last
|
||||
? encodeSortedCursor(PUBLIC_CHAT_RUN_SORT, encodePublicChatRunCursor(last))
|
||||
: null,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
listOrderBy,
|
||||
numberKey,
|
||||
searchFilter,
|
||||
textKey,
|
||||
timestampKey,
|
||||
uuidKey,
|
||||
} from '@/lib/api/list-query'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { reconcileChatStreamMarkers } from '@/lib/copilot/chat/stream-liveness'
|
||||
@@ -50,7 +50,7 @@ const pinnedRank = sql<number>`case when ${copilotChats.pinned} then 1 else 0 en
|
||||
const CHAT_KEYS = [
|
||||
numberKey<ChatRow>(pinnedRank, (row) => (row.pinned ? 1 : 0)),
|
||||
timestampKey<ChatRow>(copilotChats.updatedAt, (row) => row.updatedAt),
|
||||
textKey<ChatRow>(copilotChats.id, (row) => row.id),
|
||||
uuidKey<ChatRow>(copilotChats.id, (row) => row.id),
|
||||
]
|
||||
|
||||
/** GET /api/v2/chats — bounded personal chat history for the terminal picker. */
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
v2ChatRunDetailSchema,
|
||||
v2ChatRunParamsSchema,
|
||||
v2GetChatRunQuerySchema,
|
||||
v2ListChatRunsQuerySchema,
|
||||
} from '@/lib/api/contracts/v2/chat-runs'
|
||||
|
||||
describe('v2ListChatRunsQuerySchema', () => {
|
||||
it('defaults and clamps its bounded page size', () => {
|
||||
expect(v2ListChatRunsQuerySchema.parse({ workspaceId: 'workspace-1' }).limit).toBe(30)
|
||||
expect(v2ListChatRunsQuerySchema.parse({ workspaceId: 'workspace-1', limit: '0' }).limit).toBe(
|
||||
1
|
||||
)
|
||||
expect(
|
||||
v2ListChatRunsQuerySchema.parse({ workspaceId: 'workspace-1', limit: '999' }).limit
|
||||
).toBe(100)
|
||||
})
|
||||
|
||||
it('accepts only durable run statuses and a non-empty cursor', () => {
|
||||
expect(
|
||||
v2ListChatRunsQuerySchema.parse({ workspaceId: 'workspace-1', status: 'resuming' }).status
|
||||
).toBe('resuming')
|
||||
expect(
|
||||
v2ListChatRunsQuerySchema.safeParse({ workspaceId: 'workspace-1', status: 'running' }).success
|
||||
).toBe(false)
|
||||
expect(
|
||||
v2ListChatRunsQuerySchema.safeParse({ workspaceId: 'workspace-1', cursor: '' }).success
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('v2GetChatRunQuerySchema', () => {
|
||||
it('rejects unknown query fields', () => {
|
||||
expect(
|
||||
v2GetChatRunQuerySchema.safeParse({ workspaceId: 'workspace-1', continuationToken: 'secret' })
|
||||
.success
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a malformed run UUID before it reaches Postgres', () => {
|
||||
expect(v2ChatRunParamsSchema.safeParse({ runId: 'not-a-uuid' }).success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('v2ChatRunDetailSchema', () => {
|
||||
it('strips private replay fields from the public projection', () => {
|
||||
const parsed = v2ChatRunDetailSchema.parse({
|
||||
runId: '4bfa6f89-b746-43be-8246-bf1c69b58593',
|
||||
chatId: '80a47295-040e-46f9-9ea8-ad78eff3bcab',
|
||||
chatTitle: 'Release plan',
|
||||
status: 'complete',
|
||||
startedAt: '2026-08-08T12:00:00.000Z',
|
||||
completedAt: '2026-08-08T12:01:00.000Z',
|
||||
response: 'Done',
|
||||
activities: [
|
||||
{
|
||||
kind: 'tool',
|
||||
id: 'tool-1',
|
||||
label: 'Read file',
|
||||
state: 'complete',
|
||||
arguments: { secret: 'private' },
|
||||
result: 'private',
|
||||
},
|
||||
],
|
||||
continuationToken: 'private',
|
||||
error: 'private',
|
||||
})
|
||||
|
||||
expect(parsed).toEqual({
|
||||
runId: '4bfa6f89-b746-43be-8246-bf1c69b58593',
|
||||
chatId: '80a47295-040e-46f9-9ea8-ad78eff3bcab',
|
||||
chatTitle: 'Release plan',
|
||||
status: 'complete',
|
||||
startedAt: '2026-08-08T12:00:00.000Z',
|
||||
completedAt: '2026-08-08T12:01:00.000Z',
|
||||
response: 'Done',
|
||||
activities: [{ kind: 'tool', id: 'tool-1', label: 'Read file', state: 'complete' }],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { z } from 'zod'
|
||||
import { workspaceIdSchema } from '@/lib/api/contracts/primitives'
|
||||
import { defineRouteContract } from '@/lib/api/contracts/types'
|
||||
import { v2CursorListResponse, v2DataResponse } from '@/lib/api/contracts/v2/shared'
|
||||
|
||||
export const v2ChatRunStatusSchema = z.enum([
|
||||
'active',
|
||||
'paused_waiting_for_tool',
|
||||
'resuming',
|
||||
'complete',
|
||||
'error',
|
||||
'cancelled',
|
||||
])
|
||||
|
||||
export type V2ChatRunStatus = z.output<typeof v2ChatRunStatusSchema>
|
||||
|
||||
/** Safe, durable metadata for one root Mothership chat run. */
|
||||
export const v2ChatRunSummarySchema = z.object({
|
||||
runId: z.string().uuid(),
|
||||
chatId: z.string().uuid(),
|
||||
chatTitle: z.string().nullable(),
|
||||
status: v2ChatRunStatusSchema,
|
||||
startedAt: z.string().datetime(),
|
||||
completedAt: z.string().datetime().nullable(),
|
||||
})
|
||||
|
||||
export type V2ChatRunSummary = z.output<typeof v2ChatRunSummarySchema>
|
||||
|
||||
const v2ChatRunActivityStateSchema = z.enum(['running', 'complete', 'error'])
|
||||
|
||||
export const v2ChatRunActivitySchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
kind: z.enum(['subagent', 'tool']),
|
||||
id: z.string().min(1),
|
||||
parentId: z.string().min(1).optional(),
|
||||
label: z.string(),
|
||||
state: v2ChatRunActivityStateSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('narration'),
|
||||
parentId: z.string().min(1),
|
||||
delta: z.string(),
|
||||
}),
|
||||
])
|
||||
|
||||
export type V2ChatRunActivity = z.output<typeof v2ChatRunActivitySchema>
|
||||
|
||||
export const v2ChatRunDetailSchema = v2ChatRunSummarySchema.extend({
|
||||
/** Accumulated root-assistant response; empty until public text is available. */
|
||||
response: z.string(),
|
||||
/** Chronological, display-safe activity updates projected from replay. */
|
||||
activities: z.array(v2ChatRunActivitySchema),
|
||||
})
|
||||
|
||||
export type V2ChatRunDetail = z.output<typeof v2ChatRunDetailSchema>
|
||||
|
||||
export const v2ListChatRunsQuerySchema = z
|
||||
.object({
|
||||
workspaceId: workspaceIdSchema,
|
||||
status: v2ChatRunStatusSchema.optional(),
|
||||
limit: z.coerce
|
||||
.number()
|
||||
.optional()
|
||||
.default(30)
|
||||
.transform((value) => Math.min(Math.max(1, Math.trunc(value)), 100)),
|
||||
cursor: z.string().min(1).optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type V2ListChatRunsQuery = z.output<typeof v2ListChatRunsQuerySchema>
|
||||
|
||||
export const v2ChatRunParamsSchema = z.object({ runId: z.string().uuid() }).strict()
|
||||
|
||||
export const v2GetChatRunQuerySchema = z.object({ workspaceId: workspaceIdSchema }).strict()
|
||||
|
||||
export const v2ListChatRunsContract = defineRouteContract({
|
||||
method: 'GET',
|
||||
path: '/api/v2/chat/runs',
|
||||
query: v2ListChatRunsQuerySchema,
|
||||
response: { mode: 'json', schema: v2CursorListResponse(v2ChatRunSummarySchema) },
|
||||
})
|
||||
|
||||
export const v2GetChatRunContract = defineRouteContract({
|
||||
method: 'GET',
|
||||
path: '/api/v2/chat/runs/[runId]',
|
||||
params: v2ChatRunParamsSchema,
|
||||
query: v2GetChatRunQuerySchema,
|
||||
response: { mode: 'json', schema: v2DataResponse(v2ChatRunDetailSchema) },
|
||||
})
|
||||
@@ -34,10 +34,22 @@ describe('v2ChatBodySchema', () => {
|
||||
prompt: 'Read this',
|
||||
continuationToken: 'opaque-token',
|
||||
readOnly: false,
|
||||
async: false,
|
||||
persistChat: true,
|
||||
attachments: [{ name: 'Notes.MD', mediaType: 'text/markdown', data: 'aGk=' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts explicit asynchronous execution', () => {
|
||||
expect(
|
||||
v2ChatBodySchema.parse({
|
||||
workspaceId: 'workspace-1',
|
||||
prompt: 'Run this in the background',
|
||||
async: true,
|
||||
}).async
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts only the identity-bearing contexts supported by public resource lists', () => {
|
||||
const contexts = [
|
||||
{ kind: 'workflow', workflowId: 'workflow-1', label: 'Release' },
|
||||
|
||||
@@ -170,6 +170,20 @@ export const v2ChatBodySchema = z
|
||||
continuationToken: z.string().min(1).max(MAX_V2_CHAT_CONTINUATION_TOKEN_LENGTH).optional(),
|
||||
/** Normal Mothership is the default; this explicitly selects its read-only projection. */
|
||||
readOnly: z.boolean().optional().default(false),
|
||||
/**
|
||||
* Keep an accepted persisted turn running after the caller disconnects.
|
||||
* The route requires a personal API key and `persistChat: true` so it can
|
||||
* return a durable run id that another client can follow.
|
||||
*/
|
||||
async: z.boolean().optional().default(false),
|
||||
/**
|
||||
* Whether this turn may create a chat that shows up in the workspace's chat
|
||||
* list. `false` matches the Mothership block: the turn still gets a chat id
|
||||
* and stays continuable through its token, but leaves no row behind for the
|
||||
* UI or `sim chats list` to surface. Only suppresses *creating* a chat — a
|
||||
* continuation token for an already-persisted chat keeps persisting.
|
||||
*/
|
||||
persistChat: z.boolean().optional().default(true),
|
||||
attachments: z.array(v2ChatAttachmentSchema).max(MAX_V2_CHAT_ATTACHMENTS).optional(),
|
||||
contexts: z.array(v2ChatContextSchema).max(MAX_V2_CHAT_CONTEXTS).optional(),
|
||||
})
|
||||
@@ -189,8 +203,10 @@ export type V2ChatBody = z.input<typeof v2ChatBodySchema>
|
||||
* A normal workspace Mothership turn. Omit `continuationToken` for a one-shot
|
||||
* or the first interactive turn; pass the latest server-issued token to
|
||||
* continue the same private conversation. `readOnly` explicitly selects the
|
||||
* secretless query projection. Successful responses are SSE so proxies stay
|
||||
* alive during long agent turns and callers can cancel the run.
|
||||
* secretless query projection. `async: true` keeps an accepted persisted turn
|
||||
* running after disconnect. `persistChat: false` runs the turn without leaving
|
||||
* a chat behind in the workspace's chat list. Successful responses are SSE so
|
||||
* proxies stay alive during long agent turns and callers can cancel the run.
|
||||
*/
|
||||
export const v2ChatContract = defineRouteContract({
|
||||
method: 'POST',
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
searchFilter,
|
||||
textKey,
|
||||
timestampKey,
|
||||
uuidKey,
|
||||
} from '@/lib/api/list-query'
|
||||
|
||||
const thing = pgTable('thing', {
|
||||
@@ -139,6 +140,13 @@ describe('cursor key value validation', () => {
|
||||
expect(sizeKey.bind(Number.POSITIVE_INFINITY)).toBeNull()
|
||||
expect(sizeKey.bind(12)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a malformed UUID before it reaches a UUID column comparison', () => {
|
||||
const id = uuidKey<Row>(thing.id, (row) => row.id)
|
||||
|
||||
expect(id.bind('not-a-uuid')).toBeNull()
|
||||
expect(id.bind('4bfa6f89-b746-43be-8246-bf1c69b58593')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('encodeKeyset / keysetColumns', () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isValidUuid } from '@sim/utils/id'
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
@@ -83,6 +84,15 @@ export function textKey<Row>(column: Column, read: (row: Row) => string): Keyset
|
||||
}
|
||||
}
|
||||
|
||||
/** A UUID key whose caller-controlled cursor value is validated before SQL binding. */
|
||||
export function uuidKey<Row>(column: Column, read: (row: Row) => string): KeysetKey<Row> {
|
||||
return {
|
||||
expr: column,
|
||||
encode: read,
|
||||
bind: (value) => (typeof value === 'string' && isValidUuid(value) ? sql`${value}` : null),
|
||||
}
|
||||
}
|
||||
|
||||
/** A numeric key — sizes, counts, manual positions. */
|
||||
export function numberKey<Row>(column: SQLWrapper, read: (row: Row) => number): KeysetKey<Row> {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { V2ChatRunSummary } from '@/lib/api/contracts/v2/chat-runs'
|
||||
import type { PublicChatRunRow } from '@/lib/copilot/chat/public-runs'
|
||||
|
||||
export function toPublicChatRunSummary(row: PublicChatRunRow): V2ChatRunSummary {
|
||||
return {
|
||||
runId: row.runId,
|
||||
chatId: row.chatId,
|
||||
chatTitle: row.chatTitle,
|
||||
status: row.status,
|
||||
startedAt: row.startedAt.toISOString(),
|
||||
completedAt: row.completedAt?.toISOString() ?? null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { v2ChatRunErrorPolicies } from '@/lib/copilot/chat/api/run-route-policy'
|
||||
import { ChatRunProgressUnavailableError } from '@/lib/copilot/chat/application/errors'
|
||||
import {
|
||||
InsufficientWorkspacePermissionsError,
|
||||
PersonalApiKeysDisabledError,
|
||||
PrincipalKindAuthorizationError,
|
||||
} from '@/lib/core/application'
|
||||
import { OrchestrationError } from '@/lib/core/orchestration/types'
|
||||
|
||||
describe('v2 chat run error policies', () => {
|
||||
it('keeps the personal-key-only failure explicit', async () => {
|
||||
const response = v2ChatRunErrorPolicies.default.render(
|
||||
new PrincipalKindAuthorizationError('workspace_api_key', 'chat.runs.list')
|
||||
)
|
||||
|
||||
expect(response?.status).toBe(403)
|
||||
expect(await response?.json()).toEqual({
|
||||
error: { code: 'FORBIDDEN', message: 'Chat runs require a personal API key' },
|
||||
})
|
||||
})
|
||||
|
||||
it('conceals detail authorization and scoped misses as the same absence', async () => {
|
||||
for (const error of [
|
||||
new InsufficientWorkspacePermissionsError(),
|
||||
new OrchestrationError('not_found', 'Workspace not found'),
|
||||
new OrchestrationError('not_found', 'Chat run not found'),
|
||||
]) {
|
||||
const response = v2ChatRunErrorPolicies.detail.render(error)
|
||||
expect(response?.status).toBe(404)
|
||||
expect(await response?.json()).toEqual({
|
||||
error: { code: 'NOT_FOUND', message: 'Chat run not found' },
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves workspace personal-key policy failures', async () => {
|
||||
const response = v2ChatRunErrorPolicies.detail.render(new PersonalApiKeysDisabledError())
|
||||
expect(response?.status).toBe(403)
|
||||
})
|
||||
|
||||
it('maps transient replay unavailability without masking infrastructure failures', async () => {
|
||||
expect(
|
||||
v2ChatRunErrorPolicies.detail.render(new ChatRunProgressUnavailableError())?.status
|
||||
).toBe(503)
|
||||
expect(v2ChatRunErrorPolicies.detail.render(new Error('redis unavailable'))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { V2ErrorPolicy } from '@/lib/api/server/routes'
|
||||
import { ChatRunProgressUnavailableError } from '@/lib/copilot/chat/application/errors'
|
||||
import {
|
||||
InsufficientWorkspacePermissionsError,
|
||||
PersonalApiKeysDisabledError,
|
||||
PrincipalKindAuthorizationError,
|
||||
} from '@/lib/core/application'
|
||||
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'
|
||||
|
||||
const defaultPolicy = {
|
||||
render(error) {
|
||||
if (error instanceof PrincipalKindAuthorizationError) {
|
||||
return v2Error('FORBIDDEN', 'Chat runs require a personal API key')
|
||||
}
|
||||
if (error instanceof ChatRunProgressUnavailableError) {
|
||||
return v2Error('SERVICE_UNAVAILABLE', error.message)
|
||||
}
|
||||
return v2CaughtOrchestrationError(error)
|
||||
},
|
||||
} satisfies V2ErrorPolicy
|
||||
|
||||
export const v2ChatRunErrorPolicies = {
|
||||
default: defaultPolicy,
|
||||
detail: {
|
||||
render(error) {
|
||||
if (
|
||||
error instanceof PrincipalKindAuthorizationError ||
|
||||
error instanceof PersonalApiKeysDisabledError ||
|
||||
error instanceof ChatRunProgressUnavailableError
|
||||
) {
|
||||
return defaultPolicy.render(error)
|
||||
}
|
||||
if (error instanceof InsufficientWorkspacePermissionsError) {
|
||||
return v2Error('NOT_FOUND', 'Chat run not found')
|
||||
}
|
||||
const response = v2CaughtOrchestrationError(error)
|
||||
return response?.status === 404 ? v2Error('NOT_FOUND', 'Chat run not found') : response
|
||||
},
|
||||
} satisfies V2ErrorPolicy,
|
||||
} as const
|
||||
@@ -0,0 +1,6 @@
|
||||
export class ChatRunProgressUnavailableError extends Error {
|
||||
constructor() {
|
||||
super('Chat run progress is temporarily unavailable')
|
||||
this.name = 'ChatRunProgressUnavailableError'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineWorkspaceOperation } from '@/lib/core/application'
|
||||
|
||||
const PERSONAL_API_KEY_PRINCIPALS = ['personal_api_key'] as const
|
||||
|
||||
export const chatOperations = {
|
||||
listRuns: defineWorkspaceOperation({
|
||||
id: 'chat.runs.list',
|
||||
minimumRole: 'read',
|
||||
workspaceApiKey: 'deny',
|
||||
principalKinds: PERSONAL_API_KEY_PRINCIPALS,
|
||||
}),
|
||||
readRun: defineWorkspaceOperation({
|
||||
id: 'chat.runs.read',
|
||||
minimumRole: 'read',
|
||||
workspaceApiKey: 'deny',
|
||||
principalKinds: PERSONAL_API_KEY_PRINCIPALS,
|
||||
}),
|
||||
} as const
|
||||
@@ -0,0 +1,420 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadWorkspace: vi.fn(),
|
||||
resolvePermission: vi.fn(),
|
||||
listRuns: vi.fn(),
|
||||
getRun: vi.fn(),
|
||||
getPersistedResponse: vi.fn(),
|
||||
readEvents: vi.fn(),
|
||||
updateRunStatus: vi.fn(),
|
||||
recordAudit: vi.fn(),
|
||||
envFlags: { isAuthDisabled: false },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/config/env-flags', () => mocks.envFlags)
|
||||
|
||||
vi.mock('@/lib/workspaces/application/workspace-context', () => ({
|
||||
loadActiveWorkspaceApplicationContext: mocks.loadWorkspace,
|
||||
}))
|
||||
|
||||
vi.mock('@sim/platform-authz/workspace', () => ({
|
||||
permissionSatisfies: (permission: string | null, required: string) =>
|
||||
permission === 'admin' || permission === 'write' || permission === required,
|
||||
resolveEffectiveWorkspacePermission: mocks.resolvePermission,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/chat/public-runs', () => ({
|
||||
listPublicChatRuns: mocks.listRuns,
|
||||
getPublicChatRun: mocks.getRun,
|
||||
getPersistedPublicChatRunResponse: mocks.getPersistedResponse,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/request/session', () => ({
|
||||
readEvents: mocks.readEvents,
|
||||
eventToStreamEvent: (event: { type: string; payload: unknown; scope?: unknown }) => ({
|
||||
type: event.type,
|
||||
payload: event.payload,
|
||||
...(event.scope ? { scope: event.scope } : {}),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/async-runs/repository', () => ({
|
||||
updateRunStatus: mocks.updateRunStatus,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/headless/workspace-chat', () => ({
|
||||
publicChatUsageLimitMessage: (content: string) =>
|
||||
/^\s*<usage_upgrade>[\s\S]+<\/usage_upgrade>\s*$/.test(content) ? 'Usage limit exceeded' : null,
|
||||
}))
|
||||
|
||||
vi.mock('@sim/audit', () => ({ recordAudit: mocks.recordAudit }))
|
||||
|
||||
import { ChatRunProgressUnavailableError } from '@/lib/copilot/chat/application/errors'
|
||||
import { chatOperations } from '@/lib/copilot/chat/application/operations'
|
||||
import { listChatRuns, readChatRun } from '@/lib/copilot/chat/application/runs'
|
||||
|
||||
const workspaceContext = {
|
||||
workspaceId: 'workspace-1',
|
||||
workspaceOrganizationId: null,
|
||||
allowPersonalApiKeys: true,
|
||||
billedAccountUserId: 'billing-owner-1',
|
||||
}
|
||||
const personalPrincipal = {
|
||||
kind: 'personal_api_key' as const,
|
||||
userId: 'user-1',
|
||||
keyId: 'key-1',
|
||||
}
|
||||
const run = {
|
||||
runId: '4bfa6f89-b746-43be-8246-bf1c69b58593',
|
||||
chatId: '80a47295-040e-46f9-9ea8-ad78eff3bcab',
|
||||
chatTitle: 'Release plan',
|
||||
streamId: 'stream-1',
|
||||
status: 'complete' as const,
|
||||
startedAt: new Date('2026-08-08T12:00:00.000Z'),
|
||||
completedAt: new Date('2026-08-08T12:01:00.000Z'),
|
||||
}
|
||||
|
||||
function envelope(seq: number, type: string, payload: Record<string, unknown>) {
|
||||
return {
|
||||
v: 1,
|
||||
seq,
|
||||
ts: `2026-08-08T12:00:0${seq}.000Z`,
|
||||
stream: { streamId: 'stream-1' },
|
||||
type,
|
||||
payload,
|
||||
}
|
||||
}
|
||||
|
||||
describe('chat run application operations', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.envFlags.isAuthDisabled = false
|
||||
mocks.loadWorkspace.mockResolvedValue(workspaceContext)
|
||||
mocks.resolvePermission.mockResolvedValue('read')
|
||||
mocks.listRuns.mockResolvedValue({ status: 'ok', rows: [] })
|
||||
mocks.getRun.mockResolvedValue(run)
|
||||
mocks.getPersistedResponse.mockResolvedValue(null)
|
||||
mocks.readEvents.mockResolvedValue([
|
||||
envelope(1, 'session', { kind: 'chat', chatId: run.chatId }),
|
||||
envelope(2, 'text', { channel: 'assistant', text: 'Done' }),
|
||||
envelope(3, 'complete', { status: 'complete' }),
|
||||
])
|
||||
mocks.updateRunStatus.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
it('defines read-only personal-key operations', () => {
|
||||
for (const operation of [chatOperations.listRuns, chatOperations.readRun]) {
|
||||
expect(operation).toMatchObject({
|
||||
minimumRole: 'read',
|
||||
workspaceApiKey: 'deny',
|
||||
principalKinds: ['personal_api_key'],
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects workspace keys before canonical workspace or run loading', async () => {
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: {
|
||||
kind: 'workspace_api_key',
|
||||
workspaceId: 'workspace-1',
|
||||
keyId: 'key-1',
|
||||
},
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'forbidden' })
|
||||
|
||||
expect(mocks.loadWorkspace).not.toHaveBeenCalled()
|
||||
expect(mocks.getRun).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('enforces personal-key workspace policy before protected run reads', async () => {
|
||||
mocks.loadWorkspace.mockResolvedValue({ ...workspaceContext, allowPersonalApiKeys: false })
|
||||
|
||||
await expect(
|
||||
listChatRuns.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { workspaceId: 'workspace-1', limit: 30 },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'forbidden' })
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'forbidden' })
|
||||
|
||||
expect(mocks.listRuns).not.toHaveBeenCalled()
|
||||
expect(mocks.getRun).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not treat the auth-disabled self-host principal as a real personal key', async () => {
|
||||
mocks.envFlags.isAuthDisabled = true
|
||||
mocks.loadWorkspace.mockResolvedValue({ ...workspaceContext, allowPersonalApiKeys: false })
|
||||
|
||||
await listChatRuns.execute({
|
||||
principal: { ...personalPrincipal, keyId: 'auth-disabled' },
|
||||
input: { workspaceId: 'workspace-1', limit: 30 },
|
||||
})
|
||||
|
||||
expect(mocks.resolvePermission).toHaveBeenCalled()
|
||||
expect(mocks.listRuns).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires current personal-key permission before protected run reads', async () => {
|
||||
mocks.resolvePermission.mockResolvedValue(null)
|
||||
|
||||
await expect(
|
||||
listChatRuns.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { workspaceId: 'workspace-1', limit: 30 },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'forbidden' })
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'forbidden' })
|
||||
|
||||
expect(mocks.listRuns).not.toHaveBeenCalled()
|
||||
expect(mocks.getRun).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('authorizes the personal key before listing its owned runs', async () => {
|
||||
mocks.listRuns.mockResolvedValue({ status: 'ok', rows: [run, { ...run }] })
|
||||
|
||||
const result = await listChatRuns.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { workspaceId: 'workspace-1', status: 'complete', limit: 1 },
|
||||
})
|
||||
|
||||
expect(mocks.resolvePermission).toHaveBeenCalled()
|
||||
expect(mocks.listRuns).toHaveBeenCalledWith({
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
status: 'complete',
|
||||
limit: 1,
|
||||
cursorKeys: undefined,
|
||||
})
|
||||
expect(result).toEqual({ rows: [run], hasMore: true })
|
||||
})
|
||||
|
||||
it('keeps malformed keyset cursors out of successful application results', async () => {
|
||||
mocks.listRuns.mockResolvedValue({ status: 'invalid_cursor' })
|
||||
|
||||
await expect(
|
||||
listChatRuns.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { workspaceId: 'workspace-1', limit: 30, cursorKeys: ['bad'] },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'validation' })
|
||||
})
|
||||
|
||||
it('masks every scoped run miss as chat-run absence', async () => {
|
||||
mocks.getRun.mockResolvedValue(null)
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'not_found', message: 'Chat run not found' })
|
||||
})
|
||||
|
||||
it('returns safe accumulated text and repairs stale terminal status from replay', async () => {
|
||||
mocks.getRun.mockResolvedValue({ ...run, status: 'active', completedAt: null })
|
||||
|
||||
const result = await readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'complete',
|
||||
completedAt: new Date('2026-08-08T12:00:03.000Z'),
|
||||
response: 'Done',
|
||||
activities: [],
|
||||
})
|
||||
expect(mocks.updateRunStatus).toHaveBeenCalledWith(run.runId, 'complete', {
|
||||
completedAt: new Date('2026-08-08T12:00:03.000Z'),
|
||||
})
|
||||
})
|
||||
|
||||
it('projects replay into safe root text and opaque activities', async () => {
|
||||
mocks.readEvents.mockResolvedValue([
|
||||
envelope(1, 'session', { kind: 'chat', chatId: run.chatId }),
|
||||
envelope(2, 'text', { channel: 'assistant', text: 'Done' }),
|
||||
envelope(3, 'text', { channel: 'thinking', text: 'private chain of thought' }),
|
||||
envelope(4, 'tool', {
|
||||
toolCallId: 'private-tool-id',
|
||||
toolName: 'read',
|
||||
phase: 'call',
|
||||
arguments: { path: 'files/private.txt', secret: 'private-argument' },
|
||||
executor: 'go',
|
||||
mode: 'sync',
|
||||
}),
|
||||
envelope(5, 'tool', {
|
||||
toolCallId: 'private-tool-id',
|
||||
toolName: 'read',
|
||||
phase: 'result',
|
||||
status: 'success',
|
||||
success: true,
|
||||
output: { secret: 'private-result' },
|
||||
}),
|
||||
envelope(6, 'error', { code: 'PRIVATE', message: 'private-error' }),
|
||||
envelope(7, 'complete', { status: 'complete', reason: 'private-reason' }),
|
||||
])
|
||||
|
||||
const result = await readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
const progress = { response: result.response, activities: result.activities }
|
||||
const serialized = JSON.stringify(progress)
|
||||
|
||||
expect(progress).toEqual({
|
||||
response: 'Done',
|
||||
activities: [
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Reading private.txt', state: 'running' },
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Read private.txt', state: 'complete' },
|
||||
],
|
||||
})
|
||||
for (const privateValue of [
|
||||
'private-tool-id',
|
||||
'files/private.txt',
|
||||
'private-argument',
|
||||
'private-result',
|
||||
'private-error',
|
||||
'private-reason',
|
||||
'private chain of thought',
|
||||
]) {
|
||||
expect(serialized).not.toContain(privateValue)
|
||||
}
|
||||
})
|
||||
|
||||
it('uses persisted assistant prose after a terminal replay expires', async () => {
|
||||
mocks.readEvents.mockResolvedValue([])
|
||||
mocks.getPersistedResponse.mockResolvedValue('Stored answer')
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).resolves.toMatchObject({ response: 'Stored answer', activities: [] })
|
||||
})
|
||||
|
||||
it('uses persisted assistant prose when terminal replay has no root text', async () => {
|
||||
mocks.getPersistedResponse.mockResolvedValue('Stored answer')
|
||||
mocks.readEvents.mockResolvedValue([
|
||||
envelope(1, 'session', { kind: 'chat', chatId: run.chatId }),
|
||||
envelope(2, 'complete', { status: 'complete' }),
|
||||
])
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).resolves.toMatchObject({ response: 'Stored answer' })
|
||||
})
|
||||
|
||||
it('falls back to persisted text when terminal replay has a sequence gap', async () => {
|
||||
mocks.getPersistedResponse.mockResolvedValue('Complete stored answer')
|
||||
mocks.readEvents.mockResolvedValue([
|
||||
envelope(1, 'text', { channel: 'assistant', text: 'Truncated ' }),
|
||||
envelope(3, 'complete', { status: 'complete' }),
|
||||
])
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: 'complete',
|
||||
response: 'Complete stored answer',
|
||||
activities: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('uses replay completion metadata when stale durable terminal state disagrees', async () => {
|
||||
mocks.getRun.mockResolvedValue({
|
||||
...run,
|
||||
status: 'error',
|
||||
completedAt: new Date('2026-08-08T11:59:00.000Z'),
|
||||
})
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: 'complete',
|
||||
completedAt: new Date('2026-08-08T12:00:03.000Z'),
|
||||
response: 'Done',
|
||||
})
|
||||
expect(mocks.updateRunStatus).toHaveBeenCalledWith(run.runId, 'complete', {
|
||||
completedAt: new Date('2026-08-08T12:00:03.000Z'),
|
||||
})
|
||||
})
|
||||
|
||||
it('reports missing or gapped active replay as transient', async () => {
|
||||
mocks.getRun.mockResolvedValue({ ...run, status: 'active', completedAt: null })
|
||||
mocks.readEvents.mockResolvedValue([])
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toBeInstanceOf(ChatRunProgressUnavailableError)
|
||||
})
|
||||
|
||||
it('does not regress an active run when its replay is gapped', async () => {
|
||||
mocks.getRun.mockResolvedValue({ ...run, status: 'active', completedAt: null })
|
||||
mocks.readEvents.mockResolvedValue([
|
||||
envelope(1, 'text', { channel: 'assistant', text: 'Partial' }),
|
||||
envelope(3, 'text', { channel: 'assistant', text: ' answer' }),
|
||||
])
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toBeInstanceOf(ChatRunProgressUnavailableError)
|
||||
expect(mocks.getPersistedResponse).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports replay-store failures as transient only while a run is active', async () => {
|
||||
mocks.getRun.mockResolvedValue({ ...run, status: 'active', completedAt: null })
|
||||
mocks.readEvents.mockRejectedValue(new Error('redis unavailable'))
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toBeInstanceOf(ChatRunProgressUnavailableError)
|
||||
expect(mocks.getPersistedResponse).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('propagates unexpected run-store failures unchanged', async () => {
|
||||
const failure = new Error('database unavailable')
|
||||
mocks.getRun.mockRejectedValueOnce(failure)
|
||||
|
||||
await expect(
|
||||
readChatRun.execute({
|
||||
principal: personalPrincipal,
|
||||
input: { runId: run.runId, workspaceId: 'workspace-1' },
|
||||
})
|
||||
).rejects.toBe(failure)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type CursorKey, INVALID_CURSOR_MESSAGE } from '@/lib/api/list-query'
|
||||
import { updateRunStatus } from '@/lib/copilot/async-runs/repository'
|
||||
import { ChatRunProgressUnavailableError } from '@/lib/copilot/chat/application/errors'
|
||||
import { chatOperations } from '@/lib/copilot/chat/application/operations'
|
||||
import { ChatActivityProjector, type V2ChatActivity } from '@/lib/copilot/chat/public-activity'
|
||||
import {
|
||||
getPersistedPublicChatRunResponse,
|
||||
getPublicChatRun,
|
||||
listPublicChatRuns,
|
||||
type PublicChatRunRow,
|
||||
} from '@/lib/copilot/chat/public-runs'
|
||||
import {
|
||||
MothershipStreamV1CompletionStatus,
|
||||
MothershipStreamV1EventType,
|
||||
MothershipStreamV1TextChannel,
|
||||
} from '@/lib/copilot/generated/mothership-stream-v1'
|
||||
import { publicChatUsageLimitMessage } from '@/lib/copilot/headless/workspace-chat'
|
||||
import { eventToStreamEvent, readEvents } from '@/lib/copilot/request/session'
|
||||
import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application'
|
||||
import { isAuthDisabled } from '@/lib/core/config/env-flags'
|
||||
import { OrchestrationError } from '@/lib/core/orchestration/types'
|
||||
import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/workspace-context'
|
||||
|
||||
const logger = createLogger('CopilotChatRunsApplication')
|
||||
const TERMINAL_RUN_STATUSES = new Set<PublicChatRunRow['status']>([
|
||||
'complete',
|
||||
'error',
|
||||
'cancelled',
|
||||
])
|
||||
|
||||
async function loadWorkspaceContext(workspaceId: string) {
|
||||
const context = await loadActiveWorkspaceApplicationContext(workspaceId)
|
||||
if (!context) throw new OrchestrationError('not_found', 'Workspace not found')
|
||||
/**
|
||||
* DISABLE_AUTH's synthetic principal is not a personal API key. Preserve the
|
||||
* self-host policy while still requiring its current workspace permission.
|
||||
*/
|
||||
return isAuthDisabled ? { ...context, allowPersonalApiKeys: true } : context
|
||||
}
|
||||
|
||||
export interface ListChatRunsInput {
|
||||
workspaceId: string
|
||||
status?: PublicChatRunRow['status']
|
||||
limit: number
|
||||
cursorKeys?: CursorKey[]
|
||||
}
|
||||
|
||||
export interface ListChatRunsResult {
|
||||
rows: PublicChatRunRow[]
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export const listChatRuns = defineAuthorizedWorkspaceUseCase({
|
||||
operation: chatOperations.listRuns,
|
||||
resolveContext: ({ input }: { input: ListChatRunsInput }) =>
|
||||
loadWorkspaceContext(input.workspaceId),
|
||||
authorizationOptions: {},
|
||||
execute: async ({ principal, input, context }): Promise<ListChatRunsResult> => {
|
||||
const result = await listPublicChatRuns({
|
||||
userId: principal.userId,
|
||||
workspaceId: context.workspaceId,
|
||||
status: input.status,
|
||||
limit: input.limit,
|
||||
cursorKeys: input.cursorKeys,
|
||||
})
|
||||
if (result.status === 'invalid_cursor') {
|
||||
throw new OrchestrationError('validation', INVALID_CURSOR_MESSAGE)
|
||||
}
|
||||
return {
|
||||
rows: result.rows.slice(0, input.limit),
|
||||
hasMore: result.rows.length > input.limit,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
interface PublicRunSnapshot {
|
||||
response: string
|
||||
activities: V2ChatActivity[]
|
||||
replayStatus?: PublicChatRunRow['status']
|
||||
replayCompletedAt?: Date
|
||||
}
|
||||
|
||||
async function persistedFallback(run: PublicChatRunRow): Promise<string> {
|
||||
const response = (await getPersistedPublicChatRunResponse(run.chatId, run.streamId)) ?? ''
|
||||
return publicChatUsageLimitMessage(response) ? '' : response
|
||||
}
|
||||
|
||||
async function buildPublicRunSnapshot(run: PublicChatRunRow): Promise<PublicRunSnapshot | null> {
|
||||
let envelopes
|
||||
try {
|
||||
envelopes = await readEvents(run.streamId, '0')
|
||||
} catch (error) {
|
||||
logger.warn('Failed to read chat run replay; using safe fallback', {
|
||||
runId: run.runId,
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
})
|
||||
return TERMINAL_RUN_STATUSES.has(run.status)
|
||||
? { response: await persistedFallback(run), activities: [] }
|
||||
: null
|
||||
}
|
||||
|
||||
if (envelopes.length === 0 || envelopes.some((envelope, index) => envelope.seq !== index + 1)) {
|
||||
return TERMINAL_RUN_STATUSES.has(run.status)
|
||||
? { response: await persistedFallback(run), activities: [] }
|
||||
: null
|
||||
}
|
||||
|
||||
const projector = new ChatActivityProjector()
|
||||
const activities: V2ChatActivity[] = []
|
||||
const rootText: string[] = []
|
||||
let completionStatus: 'complete' | 'error' | undefined
|
||||
let replayStatus: PublicChatRunRow['status'] | undefined
|
||||
let replayCompletedAt: Date | undefined
|
||||
|
||||
for (const envelope of envelopes) {
|
||||
const event = eventToStreamEvent(envelope)
|
||||
activities.push(...projector.project(event))
|
||||
|
||||
if (
|
||||
event.type === MothershipStreamV1EventType.text &&
|
||||
event.payload.channel === MothershipStreamV1TextChannel.assistant &&
|
||||
!event.scope &&
|
||||
event.payload.text &&
|
||||
!publicChatUsageLimitMessage(event.payload.text)
|
||||
) {
|
||||
rootText.push(event.payload.text)
|
||||
}
|
||||
|
||||
if (event.type === MothershipStreamV1EventType.complete && !event.scope) {
|
||||
replayStatus =
|
||||
event.payload.status === MothershipStreamV1CompletionStatus.complete
|
||||
? 'complete'
|
||||
: event.payload.status === MothershipStreamV1CompletionStatus.cancelled
|
||||
? 'cancelled'
|
||||
: 'error'
|
||||
replayCompletedAt = new Date(envelope.ts)
|
||||
completionStatus = replayStatus === 'complete' ? 'complete' : 'error'
|
||||
}
|
||||
}
|
||||
|
||||
if (!completionStatus && TERMINAL_RUN_STATUSES.has(run.status)) {
|
||||
completionStatus = run.status === 'complete' ? 'complete' : 'error'
|
||||
}
|
||||
if (completionStatus) activities.push(...projector.finish(completionStatus))
|
||||
|
||||
const accumulated = rootText.join('')
|
||||
const response =
|
||||
accumulated.length === 0 && (replayStatus || TERMINAL_RUN_STATUSES.has(run.status))
|
||||
? await persistedFallback(run)
|
||||
: accumulated
|
||||
return {
|
||||
response: publicChatUsageLimitMessage(response) ? '' : response,
|
||||
activities,
|
||||
...(replayStatus ? { replayStatus, replayCompletedAt } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReadChatRunInput {
|
||||
runId: string
|
||||
workspaceId: string
|
||||
}
|
||||
|
||||
export interface ReadChatRunResult {
|
||||
run: PublicChatRunRow
|
||||
status: PublicChatRunRow['status']
|
||||
completedAt: Date | null
|
||||
response: string
|
||||
activities: V2ChatActivity[]
|
||||
}
|
||||
|
||||
export const readChatRun = defineAuthorizedWorkspaceUseCase({
|
||||
operation: chatOperations.readRun,
|
||||
resolveContext: ({ input }: { input: ReadChatRunInput }) =>
|
||||
loadWorkspaceContext(input.workspaceId),
|
||||
authorizationOptions: {},
|
||||
execute: async ({ principal, input, context }): Promise<ReadChatRunResult> => {
|
||||
const run = await getPublicChatRun({
|
||||
runId: input.runId,
|
||||
userId: principal.userId,
|
||||
workspaceId: context.workspaceId,
|
||||
})
|
||||
if (!run) throw new OrchestrationError('not_found', 'Chat run not found')
|
||||
|
||||
const snapshot = await buildPublicRunSnapshot(run)
|
||||
if (!snapshot) throw new ChatRunProgressUnavailableError()
|
||||
|
||||
const status = snapshot.replayStatus ?? run.status
|
||||
const completedAt = snapshot.replayCompletedAt ?? run.completedAt
|
||||
if (snapshot.replayStatus && (run.status !== snapshot.replayStatus || !run.completedAt)) {
|
||||
try {
|
||||
await updateRunStatus(run.runId, snapshot.replayStatus, {
|
||||
completedAt: snapshot.replayCompletedAt ?? new Date(),
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn('Failed to reconcile chat run status from terminal replay', {
|
||||
runId: run.runId,
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
run,
|
||||
status,
|
||||
completedAt,
|
||||
response: snapshot.response,
|
||||
activities: snapshot.activities,
|
||||
}
|
||||
},
|
||||
})
|
||||
+1
-1
@@ -2,9 +2,9 @@
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { ChatActivityProjector } from '@/lib/copilot/chat/public-activity'
|
||||
import type { MothershipStreamV1StreamScope } from '@/lib/copilot/generated/mothership-stream-v1'
|
||||
import type { StreamEvent } from '@/lib/copilot/request/types'
|
||||
import { ChatActivityProjector } from '@/app/api/v2/chat/activity'
|
||||
|
||||
vi.mock('@/lib/copilot/tools/client/read-block', () => ({
|
||||
getReadTargetBlock: vi.fn((path: string | undefined) =>
|
||||
@@ -88,8 +88,9 @@ const FILE_SUBAGENT = 'file'
|
||||
|
||||
/**
|
||||
* Request-local projection of the private Mothership stream onto the public
|
||||
* activity tree. Raw span/tool ids, arguments, results, errors, and thinking
|
||||
* never cross this boundary.
|
||||
* activity tree. Raw span/tool ids, argument/result objects, errors, and
|
||||
* thinking never cross this boundary. Labels may summarize the same
|
||||
* user-visible target or operation shown in Sim Home.
|
||||
*/
|
||||
export class ChatActivityProjector {
|
||||
private readonly calls = new Map<string, ToolProjection>()
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
dbChainMockFns,
|
||||
flattenMockConditions,
|
||||
queueTableRows,
|
||||
resetDbChainMock,
|
||||
schemaMock,
|
||||
} from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
getPersistedPublicChatRunResponse,
|
||||
getPublicChatRun,
|
||||
listPublicChatRuns,
|
||||
} from '@/lib/copilot/chat/public-runs'
|
||||
|
||||
function assertOwnedRootMothershipScope(where: unknown, extraRight?: string) {
|
||||
const conditions = flattenMockConditions(where)
|
||||
const equalities = conditions.filter((condition) => condition.type === 'eq')
|
||||
const nullChecks = conditions.filter((condition) => condition.type === 'isNull')
|
||||
|
||||
// Both the run and joined chat are independently pinned to the caller.
|
||||
expect(equalities.filter((condition) => condition.right === 'user-1')).toHaveLength(2)
|
||||
expect(equalities.filter((condition) => condition.right === 'workspace-1')).toHaveLength(2)
|
||||
expect(equalities).toContainEqual(expect.objectContaining({ left: 'type', right: 'mothership' }))
|
||||
expect(nullChecks).toContainEqual(expect.objectContaining({ column: 'parentRunId' }))
|
||||
expect(nullChecks).toContainEqual(expect.objectContaining({ column: 'deletedAt' }))
|
||||
if (extraRight) {
|
||||
expect(equalities).toContainEqual(expect.objectContaining({ right: extraRight }))
|
||||
}
|
||||
|
||||
expect(dbChainMockFns.innerJoin).toHaveBeenCalledWith(schemaMock.copilotChats, expect.anything())
|
||||
}
|
||||
|
||||
describe('public chat run repository', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetDbChainMock()
|
||||
})
|
||||
|
||||
it('scopes list queries to owned root runs in live Mothership chats', async () => {
|
||||
queueTableRows(schemaMock.copilotRuns, [])
|
||||
|
||||
await listPublicChatRuns({
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
status: 'active',
|
||||
limit: 30,
|
||||
})
|
||||
|
||||
assertOwnedRootMothershipScope(dbChainMockFns.where.mock.calls.at(-1)?.[0], 'active')
|
||||
expect(dbChainMockFns.limit).toHaveBeenCalledWith(31)
|
||||
})
|
||||
|
||||
it('uses the same masked scope for run detail lookups', async () => {
|
||||
queueTableRows(schemaMock.copilotRuns, [])
|
||||
|
||||
expect(
|
||||
await getPublicChatRun({
|
||||
runId: 'run-private',
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
})
|
||||
).toBeNull()
|
||||
|
||||
assertOwnedRootMothershipScope(dbChainMockFns.where.mock.calls.at(-1)?.[0], 'run-private')
|
||||
expect(dbChainMockFns.limit).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('rejects a cursor with a malformed UUID before querying Postgres', async () => {
|
||||
await expect(
|
||||
listPublicChatRuns({
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
limit: 30,
|
||||
cursorKeys: ['2026-08-08T12:00:00.000Z', 'not-a-uuid'],
|
||||
})
|
||||
).resolves.toEqual({ status: 'invalid_cursor' })
|
||||
|
||||
expect(dbChainMockFns.select).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns only assistant prose from persisted stream messages', async () => {
|
||||
queueTableRows(schemaMock.copilotMessages, [
|
||||
{
|
||||
content: {
|
||||
id: 'assistant-1',
|
||||
role: 'assistant',
|
||||
content: 'Stored answer',
|
||||
timestamp: '2026-08-08T12:00:00.000Z',
|
||||
contentBlocks: [
|
||||
{
|
||||
type: 'tool',
|
||||
toolCall: { params: { secret: 'private' }, result: { output: 'private' } },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
await expect(getPersistedPublicChatRunResponse('chat-1', 'stream-1')).resolves.toBe(
|
||||
'Stored answer'
|
||||
)
|
||||
const conditions = flattenMockConditions(dbChainMockFns.where.mock.calls.at(-1)?.[0])
|
||||
expect(conditions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: 'eq', left: 'chatId', right: 'chat-1' }),
|
||||
expect.objectContaining({ type: 'eq', left: 'streamId', right: 'stream-1' }),
|
||||
expect.objectContaining({ type: 'eq', left: 'role', right: 'assistant' }),
|
||||
expect.objectContaining({ type: 'isNull', column: 'deletedAt' }),
|
||||
])
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a malformed persisted content value instead of forwarding it', async () => {
|
||||
queueTableRows(schemaMock.copilotMessages, [
|
||||
{ content: { content: { secret: 'private' }, toolResult: 'private' } },
|
||||
])
|
||||
|
||||
await expect(getPersistedPublicChatRunResponse('chat-1', 'stream-1')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import { db } from '@sim/db'
|
||||
import { type CopilotRunStatus, copilotChats, copilotMessages, copilotRuns } from '@sim/db/schema'
|
||||
import { and, desc, eq, isNull, type SQL } from 'drizzle-orm'
|
||||
import {
|
||||
type CursorKey,
|
||||
encodeKeyset,
|
||||
keysetAfter,
|
||||
keysetColumns,
|
||||
listOrderBy,
|
||||
timestampKey,
|
||||
uuidKey,
|
||||
} from '@/lib/api/list-query'
|
||||
|
||||
export const PUBLIC_CHAT_RUN_SORT = 'startedAt:desc'
|
||||
|
||||
export interface PublicChatRunRow {
|
||||
runId: string
|
||||
chatId: string
|
||||
chatTitle: string | null
|
||||
streamId: string
|
||||
status: CopilotRunStatus
|
||||
startedAt: Date
|
||||
completedAt: Date | null
|
||||
}
|
||||
|
||||
const PUBLIC_CHAT_RUN_KEYS = [
|
||||
timestampKey<PublicChatRunRow>(copilotRuns.startedAt, (row) => row.startedAt),
|
||||
uuidKey<PublicChatRunRow>(copilotRuns.id, (row) => row.runId),
|
||||
]
|
||||
|
||||
const publicChatRunSelection = {
|
||||
runId: copilotRuns.id,
|
||||
chatId: copilotRuns.chatId,
|
||||
chatTitle: copilotChats.title,
|
||||
streamId: copilotRuns.streamId,
|
||||
status: copilotRuns.status,
|
||||
startedAt: copilotRuns.startedAt,
|
||||
completedAt: copilotRuns.completedAt,
|
||||
} as const
|
||||
|
||||
function ownedRootMothershipRunWhere(input: {
|
||||
userId: string
|
||||
workspaceId: string
|
||||
runId?: string
|
||||
status?: CopilotRunStatus
|
||||
resumeAfter?: SQL
|
||||
}) {
|
||||
return and(
|
||||
eq(copilotRuns.userId, input.userId),
|
||||
eq(copilotRuns.workspaceId, input.workspaceId),
|
||||
isNull(copilotRuns.parentRunId),
|
||||
eq(copilotChats.userId, input.userId),
|
||||
eq(copilotChats.workspaceId, input.workspaceId),
|
||||
eq(copilotChats.type, 'mothership'),
|
||||
isNull(copilotChats.deletedAt),
|
||||
input.runId ? eq(copilotRuns.id, input.runId) : undefined,
|
||||
input.status ? eq(copilotRuns.status, input.status) : undefined,
|
||||
input.resumeAfter
|
||||
)
|
||||
}
|
||||
|
||||
export type ListPublicChatRunsResult =
|
||||
| { status: 'ok'; rows: PublicChatRunRow[] }
|
||||
| { status: 'invalid_cursor' }
|
||||
|
||||
/** Lists only user-owned root runs from live Mothership chats. */
|
||||
export async function listPublicChatRuns(input: {
|
||||
userId: string
|
||||
workspaceId: string
|
||||
status?: CopilotRunStatus
|
||||
limit: number
|
||||
cursorKeys?: CursorKey[]
|
||||
}): Promise<ListPublicChatRunsResult> {
|
||||
const resumeAfter = input.cursorKeys
|
||||
? keysetAfter(PUBLIC_CHAT_RUN_KEYS, input.cursorKeys, 'desc')
|
||||
: undefined
|
||||
if (resumeAfter === null) return { status: 'invalid_cursor' }
|
||||
|
||||
const rows = await db
|
||||
.select(publicChatRunSelection)
|
||||
.from(copilotRuns)
|
||||
.innerJoin(copilotChats, eq(copilotChats.id, copilotRuns.chatId))
|
||||
.where(ownedRootMothershipRunWhere({ ...input, resumeAfter }))
|
||||
.orderBy(...listOrderBy(keysetColumns(PUBLIC_CHAT_RUN_KEYS), 'desc'))
|
||||
.limit(input.limit + 1)
|
||||
|
||||
return { status: 'ok', rows }
|
||||
}
|
||||
|
||||
export function encodePublicChatRunCursor(row: PublicChatRunRow): CursorKey[] {
|
||||
return encodeKeyset(PUBLIC_CHAT_RUN_KEYS, row)
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads one public run while masking every ownership, scope, type, deletion,
|
||||
* and parent-run mismatch behind the same absence result.
|
||||
*/
|
||||
export async function getPublicChatRun(input: {
|
||||
runId: string
|
||||
userId: string
|
||||
workspaceId: string
|
||||
}): Promise<PublicChatRunRow | null> {
|
||||
const [run] = await db
|
||||
.select(publicChatRunSelection)
|
||||
.from(copilotRuns)
|
||||
.innerJoin(copilotChats, eq(copilotChats.id, copilotRuns.chatId))
|
||||
.where(ownedRootMothershipRunWhere(input))
|
||||
.limit(1)
|
||||
|
||||
return run ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads only the root assistant prose persisted for this stream. Tool blocks
|
||||
* stay inside the JSON message and never cross the public boundary.
|
||||
*/
|
||||
export async function getPersistedPublicChatRunResponse(
|
||||
chatId: string,
|
||||
streamId: string
|
||||
): Promise<string | null> {
|
||||
const [row] = await db
|
||||
.select({ content: copilotMessages.content })
|
||||
.from(copilotMessages)
|
||||
.where(
|
||||
and(
|
||||
eq(copilotMessages.chatId, chatId),
|
||||
eq(copilotMessages.streamId, streamId),
|
||||
eq(copilotMessages.role, 'assistant'),
|
||||
isNull(copilotMessages.deletedAt)
|
||||
)
|
||||
)
|
||||
.orderBy(desc(copilotMessages.seq), desc(copilotMessages.createdAt), desc(copilotMessages.id))
|
||||
.limit(1)
|
||||
|
||||
if (!row?.content || typeof row.content !== 'object' || Array.isArray(row.content)) return null
|
||||
const response = (row.content as Record<string, unknown>).content
|
||||
return typeof response === 'string' ? response : null
|
||||
}
|
||||
@@ -1841,6 +1841,7 @@ describe('runCopilotLifecycle', () => {
|
||||
)
|
||||
|
||||
expect(fetchUrls[1]).toBe('http://mothership.test/api/tools/resume')
|
||||
expect(mockUpdateRunStatus).toHaveBeenCalledWith('run-1', 'resuming')
|
||||
expect(requestBodies[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
checkpointId: 'ckpt-1',
|
||||
|
||||
@@ -1490,6 +1490,17 @@ async function runCheckpointLoop(
|
||||
break
|
||||
}
|
||||
|
||||
if (isResume && options.runId) {
|
||||
try {
|
||||
await updateRunStatus(options.runId, 'resuming')
|
||||
} catch (error) {
|
||||
logger.warn('Failed to mark run as resuming', {
|
||||
runId: options.runId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const loopOptions = {
|
||||
...options,
|
||||
onEvent: async (event: StreamEvent) => {
|
||||
|
||||
+60
-29
@@ -18,7 +18,7 @@ npm install --global @simai/cli@dev # dev
|
||||
## Profiles
|
||||
|
||||
Profiles work like the AWS CLI: one identity and one set of defaults per named
|
||||
profile, selected with `-P`, `--profile`, or `SIM_PROFILE`. This is what lets you keep
|
||||
profile, selected with `-p`, `--profile`, or `SIM_PROFILE`. This is what lets you keep
|
||||
production and a local dev stack side by side without re-authenticating.
|
||||
|
||||
Non-secret settings live in `~/.sim/config`:
|
||||
@@ -118,7 +118,10 @@ conversation, while `sim chats` manages saved chat resources.
|
||||
|
||||
```bash
|
||||
sim chat [prompt...] [-f <path>...] [--read-only]
|
||||
sim chat -p [prompt...] [-f <path>...] [--read-only]
|
||||
sim chat ask [prompt...] [-f <path>...] [--read-only] [--chat <chatId>] [--async]
|
||||
sim chat follow <runId>
|
||||
sim chat runs list [--status <status>] [--limit <n>]
|
||||
sim chat runs get <runId>
|
||||
sim chats list [--search <text>] [--limit <n>]
|
||||
sim chats get <chatId> [--read-only]
|
||||
sim chats rename <chatId> --title <title>
|
||||
@@ -234,19 +237,18 @@ sim chat --file screenshot.png "What is failing here?"
|
||||
sim chat --read-only "Summarize this workspace without changing it"
|
||||
```
|
||||
|
||||
Inside the chat, `/attach <paths>` attaches up to five local images, PDFs, or
|
||||
UTF-8 text files to the next turn. A pasted or dragged file path preloads an
|
||||
`/attach` command; review it and press Enter before the CLI reads the file. On
|
||||
macOS, press Ctrl+V or use `/paste-image` to attach a clipboard image;
|
||||
any draft text remains in the prompt. `/chats` loads the chat history and opens
|
||||
a searchable picker. Selecting one restores its transcript and continues it
|
||||
with a fresh opaque token. The header shows the active chat title and keeps the
|
||||
`/chats` switch hint visible; a new chat's generated title appears there as soon
|
||||
as the server publishes it. `/rename <title>` retitles the active synced chat in
|
||||
both the terminal and Sim Home. `/new` clears the visible transcript and
|
||||
starts a new conversation, `/help` lists commands, and `/exit` or Ctrl+D exits.
|
||||
Ctrl+C clears idle input or cancels the active generation and returns to the
|
||||
prompt.
|
||||
Inside the chat, type or drop local paths to attach up to five images, PDFs, or
|
||||
UTF-8 text files. Paths are removed from the submitted prompt and the files are
|
||||
sent inline; a path-only turn sends just the attachments. Press Ctrl+V (or
|
||||
Cmd+V on macOS) to add a clipboard image or file without replacing draft text.
|
||||
`/chats` loads the chat history and opens a searchable picker. Selecting one
|
||||
restores its transcript and continues it with a fresh opaque token. The header
|
||||
shows the active chat title and keeps the `/chats` switch hint visible; a new
|
||||
chat's generated title appears there as soon as the server publishes it.
|
||||
`/rename <title>` retitles the active synced chat in both the terminal and Sim
|
||||
Home. `/new` clears the visible transcript and starts a new conversation,
|
||||
`/help` lists commands, and `/exit` or Ctrl+D exits. Ctrl+C clears idle input or
|
||||
cancels the active generation and returns to the prompt.
|
||||
|
||||
Chats sent with the personal API key issued by `sim login` use the same history
|
||||
as Sim Home, so a CLI conversation appears in the web UI and a web conversation
|
||||
@@ -257,29 +259,58 @@ profile to replace it with a personal key and enable synchronized history and
|
||||
`/chats`.
|
||||
|
||||
Chat uses the full Mothership toolset by default. Add `--read-only` in either
|
||||
interactive or print mode when the conversation must be restricted to
|
||||
interactive or one-shot mode when the conversation must be restricted to
|
||||
workspace-reading tools.
|
||||
|
||||
`sim chat -p` is the non-interactive form. It never opens a prompt: the
|
||||
completed, terminal-safe answer is the only thing written to stdout, so it
|
||||
composes cleanly with shell tools. Bare `sim chat` requires a real terminal;
|
||||
pipelines and redirected output must use `-p`.
|
||||
`sim chat ask` is the non-interactive form. It never opens a prompt. With a
|
||||
personal API key, each ask creates or continues a saved chat, so the returned
|
||||
chat ID can be passed back with `--chat` and the conversation also appears in
|
||||
Sim Home. Without `--async`, table and text output keep the completed,
|
||||
terminal-safe answer as the only stdout payload, so it composes cleanly with
|
||||
shell tools; an interactive terminal shows the chat ID on stderr. JSON and YAML
|
||||
return both `content` and `chatId`. Bare `sim chat` requires a real terminal;
|
||||
pipelines and redirected output must use `chat ask`.
|
||||
|
||||
```bash
|
||||
sim chat -p "Which workflows handle support tickets?"
|
||||
sim chat -p --chat <chatId> "Continue this conversation"
|
||||
cat incident.txt | sim chat -p "Which workflow is most likely involved?"
|
||||
sim chat -p < question.txt
|
||||
sim chat -p --file report.pdf "Summarize this in workspace context"
|
||||
sim chat ask "Which workflows handle support tickets?"
|
||||
sim chat ask --chat <chatId> "Continue this conversation"
|
||||
cat incident.txt | sim chat ask "Which workflow is most likely involved?"
|
||||
sim chat ask < question.txt
|
||||
sim chat ask --file report.pdf "Summarize this in workspace context"
|
||||
```
|
||||
|
||||
Pass `--chat <chatId>` to append one print-mode turn to an existing inactive
|
||||
Pass `--chat <chatId>` to append one turn to an existing inactive
|
||||
chat, print its answer, and exit. The chat must belong to the active workspace,
|
||||
and synchronized history requires a personal API key.
|
||||
|
||||
```bash
|
||||
chat_id=$(sim --output json chat ask "Inspect this workspace" | jq -r .chatId)
|
||||
sim chat ask --chat "$chat_id" "Now inspect the deployed workflows"
|
||||
```
|
||||
|
||||
Add `--async` when the shell should regain control as soon as the run is
|
||||
accepted. The receipt contains the `runId`, `chatId`, and initial `active`
|
||||
status in the profile's normal output format. Async asks are saved chats, so
|
||||
they stay synchronized with Sim Home. `chat runs list` shows recent requests,
|
||||
and `chat runs get --output json` or `--output yaml` includes one run's
|
||||
accumulated response and activity.
|
||||
|
||||
Use `chat follow` to observe a run until it reaches a terminal state. In human
|
||||
output it streams only response text that has appeared since the last poll;
|
||||
when stderr is a terminal, concise status and tool activity appear there.
|
||||
JSON and YAML wait and emit one final snapshot instead. Ctrl+C detaches the
|
||||
observer without cancelling the server-side run. A run ending in `error` or
|
||||
`cancelled` still emits its safe partial/final result and exits nonzero.
|
||||
|
||||
```bash
|
||||
run_id=$(sim --output json chat ask --async "Audit this workspace" | jq -r .runId)
|
||||
sim chat follow "$run_id"
|
||||
sim chat runs get "$run_id"
|
||||
```
|
||||
|
||||
When both a positional prompt and stdin are present, the positional prompt comes
|
||||
first and the piped content follows on the next line. This matches Claude Code's
|
||||
print-mode input behavior. Combined input is limited to 10 MiB of UTF-8 text.
|
||||
first and the piped content follows on the next line. Combined input is limited
|
||||
to 10 MiB of UTF-8 text.
|
||||
Files are sent inline by basename only: local paths never cross the API
|
||||
boundary. Images and PDFs are limited to 5 MiB each, text files to 200 KiB, and
|
||||
all attachments in a turn to 10 MiB total.
|
||||
@@ -289,7 +320,7 @@ workspace without logging in locally:
|
||||
|
||||
```bash
|
||||
sim configure --set-endpoint http://localhost:3000 --set-workspace ws_local
|
||||
sim chat -p "What is in this workspace?"
|
||||
sim chat ask "What is in this workspace?"
|
||||
```
|
||||
|
||||
That deployment must enable `V2_API=true` and set `COPILOT_API_KEY` server-side.
|
||||
|
||||
@@ -23,21 +23,32 @@ import type {
|
||||
ChatTerminalSelectResult,
|
||||
ChatTerminalWelcome,
|
||||
} from './chat-terminal.js'
|
||||
import { attachProtocolCommands } from './index.js'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
output: 'table' as 'table' | 'text' | 'json' | 'yaml',
|
||||
request: vi.fn(),
|
||||
requestRaw: vi.fn(),
|
||||
requireWorkspace: vi.fn(() => 'ws_local'),
|
||||
selectedProfile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../context.js', () => ({
|
||||
clientFrom: () => ({ client: mocks, profile: { endpoint: 'https://sim.example' } }),
|
||||
clientFrom: (command: Command) => {
|
||||
mocks.selectedProfile(command.optsWithGlobals().profile)
|
||||
return {
|
||||
client: mocks,
|
||||
profile: { endpoint: 'https://sim.example', name: 'default', output: mocks.output },
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.request.mockReset().mockResolvedValue({ data: [], nextCursor: null })
|
||||
mocks.requestRaw.mockReset()
|
||||
mocks.requireWorkspace.mockClear()
|
||||
mocks.selectedProfile.mockReset()
|
||||
mocks.output = 'table'
|
||||
})
|
||||
|
||||
function sse(chunks: string[]): Response {
|
||||
@@ -50,12 +61,18 @@ function sse(chunks: string[]): Response {
|
||||
return new Response(body, { headers: { 'content-type': 'text/event-stream' } })
|
||||
}
|
||||
|
||||
function completed(content: string, token = 'continuation-1', deltas: string[] = []): Response {
|
||||
function completed(
|
||||
content: string,
|
||||
token = 'continuation-1',
|
||||
deltas: string[] = [],
|
||||
chatId: string | null = null
|
||||
): Response {
|
||||
return sse([
|
||||
`event: session\ndata: ${JSON.stringify({
|
||||
type: 'session',
|
||||
continuationToken: token,
|
||||
requestId: 'req_1',
|
||||
...(chatId ? { chatId } : {}),
|
||||
})}\n\n`,
|
||||
...deltas.map((delta) => `event: text\ndata: ${JSON.stringify({ type: 'text', delta })}\n\n`),
|
||||
`event: complete\ndata: ${JSON.stringify({
|
||||
@@ -85,8 +102,8 @@ function program(
|
||||
writeOutput = vi.fn(),
|
||||
overrides: Partial<ChatDependencies> = {}
|
||||
): Command {
|
||||
const root = new Command('sim').exitOverride()
|
||||
root.option('-P, --profile <name>')
|
||||
const root = new Command('sim')
|
||||
root.option('-p, --profile <name>')
|
||||
root.addCommand(
|
||||
chatCommand({
|
||||
readInput,
|
||||
@@ -95,6 +112,11 @@ function program(
|
||||
...overrides,
|
||||
})
|
||||
)
|
||||
const overrideExit = (command: Command) => {
|
||||
command.exitOverride()
|
||||
command.commands.forEach(overrideExit)
|
||||
}
|
||||
overrideExit(root)
|
||||
return root
|
||||
}
|
||||
|
||||
@@ -236,7 +258,7 @@ class FakeTerminal implements ChatTerminal {
|
||||
}
|
||||
}
|
||||
|
||||
describe('chat print mode', () => {
|
||||
describe('chat ask', () => {
|
||||
it('posts to the selected workspace and prints only the completed answer', async () => {
|
||||
const wire = [
|
||||
': keepalive\n\n',
|
||||
@@ -262,7 +284,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'What',
|
||||
'is',
|
||||
'here?',
|
||||
@@ -280,6 +302,62 @@ describe('chat print mode', () => {
|
||||
expect(writeOutput).toHaveBeenCalledWith('Hello world')
|
||||
})
|
||||
|
||||
it('shows the reusable saved chat ID on stderr without changing answer stdout', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('Saved answer', 'token', [], 'chat-1'))
|
||||
const writeOutput = vi.fn()
|
||||
const writeProgress = vi.fn()
|
||||
|
||||
await program(async () => '', writeOutput, {
|
||||
showProgress: () => true,
|
||||
writeProgress,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'ask', 'Save this'])
|
||||
|
||||
expect(writeOutput).toHaveBeenCalledWith('Saved answer')
|
||||
expect(writeProgress).toHaveBeenCalledWith('chat: chat-1\n')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['json', '{"content":"Saved answer","chatId":"chat-1"}'],
|
||||
['yaml', 'content: Saved answer\nchatId: chat-1'],
|
||||
] as const)('returns content and reusable chat ID in %s output', async (format, expected) => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('Saved answer', 'token', [], 'chat-1'))
|
||||
mocks.output = format
|
||||
const writeOutput = vi.fn()
|
||||
const writeProgress = vi.fn()
|
||||
const logged: string[] = []
|
||||
const log = vi.spyOn(console, 'log').mockImplementation((line: string) => logged.push(line))
|
||||
|
||||
try {
|
||||
await program(async () => '', writeOutput, {
|
||||
showProgress: () => true,
|
||||
writeProgress,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'ask', 'Save this'])
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
}
|
||||
|
||||
expect(writeOutput).not.toHaveBeenCalled()
|
||||
expect(writeProgress).not.toHaveBeenCalled()
|
||||
expect(logged).toHaveLength(1)
|
||||
expect(format === 'json' ? JSON.stringify(JSON.parse(logged[0])) : logged[0]).toBe(expected)
|
||||
})
|
||||
|
||||
it('keeps workspace-key one-shot answers usable when no saved chat ID is available', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('Unsynced answer', 'token', [], null))
|
||||
const writeOutput = vi.fn()
|
||||
const writeProgress = vi.fn()
|
||||
|
||||
await program(async () => '', writeOutput, {
|
||||
showProgress: () => true,
|
||||
writeProgress,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'ask', 'Read this'])
|
||||
|
||||
expect(writeOutput).toHaveBeenCalledWith('Unsynced answer')
|
||||
expect(writeProgress).toHaveBeenCalledWith(
|
||||
'chat: not saved (a personal API key is required for resumable history)\n'
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes an existing chat by ID for one print-mode turn', async () => {
|
||||
mocks.request.mockResolvedValueOnce({
|
||||
data: {
|
||||
@@ -297,7 +375,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--chat',
|
||||
'chat-1',
|
||||
'Continue here',
|
||||
@@ -331,7 +409,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--read-only',
|
||||
'--chat',
|
||||
'chat-1',
|
||||
@@ -350,16 +428,13 @@ describe('chat print mode', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects --chat outside print mode', async () => {
|
||||
await expect(
|
||||
program(async () => '', vi.fn(), { isInteractive: () => true }).parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'--chat',
|
||||
'chat-1',
|
||||
])
|
||||
).rejects.toThrow('--chat can only be used with -p/--print')
|
||||
it('keeps --chat scoped to one-shot asks', async () => {
|
||||
const root = program(async () => '', vi.fn(), { isInteractive: () => true })
|
||||
const chat = root.commands.find((command) => command.name() === 'chat')
|
||||
const ask = chat?.commands.find((command) => command.name() === 'ask')
|
||||
|
||||
expect(chat?.helpInformation()).not.toContain('--chat')
|
||||
expect(ask?.helpInformation()).toContain('--chat <chatId>')
|
||||
|
||||
expect(mocks.request).not.toHaveBeenCalled()
|
||||
expect(mocks.requestRaw).not.toHaveBeenCalled()
|
||||
@@ -381,7 +456,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--chat',
|
||||
'chat-1',
|
||||
'Continue here',
|
||||
@@ -411,7 +486,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--chat',
|
||||
'chat-1',
|
||||
'Continue here',
|
||||
@@ -430,7 +505,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--chat',
|
||||
'missing-chat',
|
||||
'Continue here',
|
||||
@@ -440,15 +515,24 @@ describe('chat print mode', () => {
|
||||
expect(mocks.requestRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the profile shorthand distinct from chat -p', async () => {
|
||||
it('accepts the global profile shorthand after chat ask', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('answer'))
|
||||
|
||||
await program(async () => '').parseAsync(['node', 'sim', '-P', 'dev', 'chat', '-p', 'question'])
|
||||
await program(async () => '').parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'ask',
|
||||
'-p',
|
||||
'dev',
|
||||
'question',
|
||||
])
|
||||
|
||||
expect(mocks.requestRaw.mock.calls[0][1].body).toEqual({
|
||||
workspaceId: 'ws_local',
|
||||
prompt: 'question',
|
||||
})
|
||||
expect(mocks.selectedProfile).toHaveBeenCalledWith('dev')
|
||||
})
|
||||
|
||||
it('opts into query-only chat only when --read-only is passed', async () => {
|
||||
@@ -458,7 +542,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--read-only',
|
||||
'question',
|
||||
])
|
||||
@@ -477,7 +561,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'--print',
|
||||
'ask',
|
||||
'Explain',
|
||||
'this',
|
||||
])
|
||||
@@ -488,7 +572,7 @@ describe('chat print mode', () => {
|
||||
it('accepts piped input without a positional prompt', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('answer'))
|
||||
|
||||
await program(async () => 'question from stdin\n').parseAsync(['node', 'sim', 'chat', '-p'])
|
||||
await program(async () => 'question from stdin\n').parseAsync(['node', 'sim', 'chat', 'ask'])
|
||||
|
||||
expect(mocks.requestRaw.mock.calls[0][1].body.prompt).toBe('question from stdin\n')
|
||||
})
|
||||
@@ -506,7 +590,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'--file',
|
||||
'/private/local/notes.md',
|
||||
])
|
||||
@@ -521,9 +605,9 @@ describe('chat print mode', () => {
|
||||
})
|
||||
|
||||
it('requires a prompt, attachment, or stdin', async () => {
|
||||
await expect(program(async () => '').parseAsync(['node', 'sim', 'chat', '-p'])).rejects.toThrow(
|
||||
/Provide a prompt, attach a file, or pipe input/
|
||||
)
|
||||
await expect(
|
||||
program(async () => '').parseAsync(['node', 'sim', 'chat', 'ask'])
|
||||
).rejects.toThrow(/Provide a prompt, attach a file, or pipe input/)
|
||||
expect(mocks.requestRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -534,7 +618,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
])
|
||||
|
||||
await expect(result).rejects.toMatchObject({
|
||||
@@ -547,11 +631,11 @@ describe('chat print mode', () => {
|
||||
it('fails clearly instead of blocking when bare chat has no interactive terminal', async () => {
|
||||
await expect(
|
||||
program(async () => '').parseAsync(['node', 'sim', 'chat', 'question'])
|
||||
).rejects.toThrow(/Use sim chat -p/)
|
||||
).rejects.toThrow(/Use sim chat ask/)
|
||||
expect(mocks.requestRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never constructs a terminal prompt in -p mode', async () => {
|
||||
it('never constructs a terminal prompt for chat ask', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(completed('answer'))
|
||||
const createTerminal = vi.fn(() => {
|
||||
throw new Error('must not prompt')
|
||||
@@ -560,7 +644,7 @@ describe('chat print mode', () => {
|
||||
await program(async () => '', vi.fn(), {
|
||||
isInteractive: () => true,
|
||||
createTerminal,
|
||||
}).parseAsync(['node', 'sim', 'chat', '-p', 'question'])
|
||||
}).parseAsync(['node', 'sim', 'chat', 'ask', 'question'])
|
||||
|
||||
expect(createTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -574,18 +658,30 @@ describe('chat print mode', () => {
|
||||
)
|
||||
const writeOutput = vi.fn()
|
||||
|
||||
await program(async () => '', writeOutput).parseAsync(['node', 'sim', 'chat', '-p', 'question'])
|
||||
await program(async () => '', writeOutput).parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'ask',
|
||||
'question',
|
||||
])
|
||||
|
||||
expect(writeOutput).toHaveBeenCalledWith('Safe text')
|
||||
expect(writeOutput.mock.calls[0][0]).not.toContain(terminalEscape)
|
||||
})
|
||||
|
||||
it('trims whitespace owned by hidden options in print mode', async () => {
|
||||
it('trims whitespace owned by hidden options in one-shot output', async () => {
|
||||
const options = '<options>{"1":{"title":"Next","description":"Continue"}}</options>'
|
||||
mocks.requestRaw.mockResolvedValue(completed(`Answer\n\n${options}\n\n`))
|
||||
const writeOutput = vi.fn()
|
||||
|
||||
await program(async () => '', writeOutput).parseAsync(['node', 'sim', 'chat', '-p', 'question'])
|
||||
await program(async () => '', writeOutput).parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'ask',
|
||||
'question',
|
||||
])
|
||||
|
||||
expect(writeOutput).toHaveBeenCalledOnce()
|
||||
expect(writeOutput).toHaveBeenCalledWith('Answer')
|
||||
@@ -603,7 +699,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'find file',
|
||||
])
|
||||
|
||||
@@ -611,7 +707,7 @@ describe('chat print mode', () => {
|
||||
expect(writeOutput).toHaveBeenCalledWith('Q4 report')
|
||||
})
|
||||
|
||||
it('omits a trailing standalone workspace link in print mode', async () => {
|
||||
it('omits a trailing standalone workspace link in one-shot output', async () => {
|
||||
const resource =
|
||||
'<workspace_resource>{"type":"workflow","id":"wf-forceful","title":"forceful-arm"}</workspace_resource>'
|
||||
mocks.requestRaw.mockResolvedValue(completed(`Summary.\n\n${resource}`))
|
||||
@@ -621,7 +717,7 @@ describe('chat print mode', () => {
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'-p',
|
||||
'ask',
|
||||
'inspect forceful-arm',
|
||||
])
|
||||
|
||||
@@ -638,12 +734,12 @@ describe('chat print mode', () => {
|
||||
const writeOutput = vi.fn()
|
||||
|
||||
await expect(
|
||||
program(async () => '', writeOutput).parseAsync(['node', 'sim', 'chat', '-p', 'question'])
|
||||
program(async () => '', writeOutput).parseAsync(['node', 'sim', 'chat', 'ask', 'question'])
|
||||
).rejects.toThrow('No answer')
|
||||
expect(writeOutput).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps thinking and activity events silent in print mode', async () => {
|
||||
it('keeps thinking and activity events silent in one-shot output', async () => {
|
||||
mocks.requestRaw.mockResolvedValue(
|
||||
sse([
|
||||
'event: thinking\ndata: {"type":"thinking","delta":"Checking the workspace"}\n\n',
|
||||
@@ -655,10 +751,294 @@ describe('chat print mode', () => {
|
||||
])
|
||||
)
|
||||
const writeOutput = vi.fn()
|
||||
await program(async () => '', writeOutput).parseAsync(['node', 'sim', 'chat', '-p', 'question'])
|
||||
await program(async () => '', writeOutput).parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'ask',
|
||||
'question',
|
||||
])
|
||||
|
||||
expect(writeOutput).toHaveBeenCalledWith('Answer')
|
||||
})
|
||||
|
||||
it('starts an asynchronous run, closes the accepted stream, and prints a normal receipt', async () => {
|
||||
const accepted = openSse(
|
||||
'event: session\ndata: {"type":"session","runId":"run-1","chatId":"chat-1"}\n\n'
|
||||
)
|
||||
mocks.requestRaw.mockResolvedValue(accepted.response)
|
||||
mocks.output = 'json'
|
||||
const logged: string[] = []
|
||||
const log = vi.spyOn(console, 'log').mockImplementation((line: string) => logged.push(line))
|
||||
|
||||
try {
|
||||
await program(async () => '').parseAsync([
|
||||
'node',
|
||||
'sim',
|
||||
'chat',
|
||||
'ask',
|
||||
'--async',
|
||||
'inspect workspace',
|
||||
])
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
}
|
||||
|
||||
expect(mocks.requestRaw).toHaveBeenCalledWith('/api/v2/chat', {
|
||||
method: 'POST',
|
||||
headers: { accept: 'text/event-stream' },
|
||||
body: {
|
||||
workspaceId: 'ws_local',
|
||||
prompt: 'inspect workspace',
|
||||
persistChat: true,
|
||||
async: true,
|
||||
},
|
||||
signal: expect.any(AbortSignal),
|
||||
auth: 'optional',
|
||||
})
|
||||
expect(accepted.cancel).toHaveBeenCalledOnce()
|
||||
expect(JSON.parse(logged.join('\n'))).toEqual({
|
||||
runId: 'run-1',
|
||||
chatId: 'chat-1',
|
||||
status: 'active',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('chat follow', () => {
|
||||
const snapshot = (
|
||||
status: string,
|
||||
response: string,
|
||||
activities: Array<Record<string, unknown>> = []
|
||||
) => ({
|
||||
data: {
|
||||
runId: 'run-1',
|
||||
chatId: 'chat-1',
|
||||
chatTitle: 'Workspace audit',
|
||||
status,
|
||||
startedAt: '2026-08-08T12:00:00.000Z',
|
||||
completedAt: status === 'complete' ? '2026-08-08T12:00:02.000Z' : null,
|
||||
response,
|
||||
activities,
|
||||
},
|
||||
})
|
||||
|
||||
it('prints only newly accumulated response text and useful progress', async () => {
|
||||
mocks.request
|
||||
.mockResolvedValueOnce(
|
||||
snapshot('active', 'Hel', [
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Read file', state: 'running' },
|
||||
])
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
snapshot('active', 'Hello', [
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Read file', state: 'running' },
|
||||
])
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
snapshot('complete', 'Hello world', [
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Read file', state: 'running' },
|
||||
{ kind: 'tool', id: 'tool-1', label: 'Read file', state: 'complete' },
|
||||
])
|
||||
)
|
||||
const terminalWrites: string[] = []
|
||||
const writeStream = vi.fn((content: string) => terminalWrites.push(content))
|
||||
const writeProgress = vi.fn((content: string) => terminalWrites.push(content))
|
||||
const pollDelay = vi.fn(async () => {})
|
||||
|
||||
await program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
writeProgress,
|
||||
showProgress: () => true,
|
||||
pollDelay,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
|
||||
expect(mocks.request).toHaveBeenCalledTimes(3)
|
||||
for (const [path, options] of mocks.request.mock.calls) {
|
||||
expect(path).toBe('/api/v2/chat/runs/run-1')
|
||||
expect(options).toMatchObject({ query: { workspaceId: 'ws_local' }, auth: 'optional' })
|
||||
expect(options.signal).toBeInstanceOf(AbortSignal)
|
||||
}
|
||||
expect(pollDelay).toHaveBeenCalledTimes(2)
|
||||
expect(writeStream.mock.calls.map(([value]) => value)).toEqual(['Hel', 'lo', ' world', '\n'])
|
||||
expect(writeProgress.mock.calls.map(([value]) => value)).toEqual([
|
||||
'status: active\n',
|
||||
'● Read file\n',
|
||||
'status: complete\n',
|
||||
'✓ Read file\n',
|
||||
])
|
||||
expect(terminalWrites).toEqual([
|
||||
'status: active\n',
|
||||
'● Read file\n',
|
||||
'Hel',
|
||||
'lo',
|
||||
' world',
|
||||
'\n',
|
||||
'status: complete\n',
|
||||
'✓ Read file\n',
|
||||
])
|
||||
})
|
||||
|
||||
it('retries transient status failures without regressing accumulated output', async () => {
|
||||
mocks.request
|
||||
.mockRejectedValueOnce(new SimApiError('Progress unavailable', 503, 'SERVICE_UNAVAILABLE'))
|
||||
.mockResolvedValueOnce(snapshot('complete', 'Recovered answer'))
|
||||
const writeStream = vi.fn()
|
||||
const pollDelay = vi.fn(async () => {})
|
||||
|
||||
await program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
showProgress: () => false,
|
||||
pollDelay,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
|
||||
expect(mocks.request).toHaveBeenCalledTimes(2)
|
||||
expect(pollDelay).toHaveBeenCalledOnce()
|
||||
expect(writeStream.mock.calls.map(([value]) => value)).toEqual(['Recovered answer', '\n'])
|
||||
})
|
||||
|
||||
it('emits one safe final snapshot for JSON output', async () => {
|
||||
const terminalEscape = `${String.fromCharCode(27)}]0;owned\u0007`
|
||||
mocks.request.mockResolvedValueOnce(snapshot('complete', `${terminalEscape}Answer`))
|
||||
mocks.output = 'json'
|
||||
const writeStream = vi.fn()
|
||||
const writeProgress = vi.fn()
|
||||
const logged: string[] = []
|
||||
const log = vi.spyOn(console, 'log').mockImplementation((line: string) => logged.push(line))
|
||||
|
||||
try {
|
||||
await program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
writeProgress,
|
||||
showProgress: () => true,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
}
|
||||
|
||||
expect(writeStream).not.toHaveBeenCalled()
|
||||
expect(writeProgress).not.toHaveBeenCalled()
|
||||
expect(logged).toHaveLength(1)
|
||||
expect(JSON.parse(logged[0])).toMatchObject({
|
||||
runId: 'run-1',
|
||||
chatId: 'chat-1',
|
||||
status: 'complete',
|
||||
response: `${terminalEscape}Answer`,
|
||||
})
|
||||
})
|
||||
|
||||
it('streams through the normal structured renderer and omits a trailing resource', async () => {
|
||||
const options = '<options>{"1":{"title":"Next","description":"Continue"}}</options>'
|
||||
const resource =
|
||||
'<workspace_resource>{"type":"workflow","id":"wf-1","title":"forceful-arm"}</workspace_resource>'
|
||||
mocks.request
|
||||
.mockResolvedValueOnce(snapshot('active', 'Answer\n\n<op'))
|
||||
.mockResolvedValueOnce(snapshot('complete', `Answer\n\n${options}\n\n${resource}`))
|
||||
const writeStream = vi.fn()
|
||||
|
||||
await program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
showProgress: () => false,
|
||||
pollDelay: async () => {},
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
|
||||
expect(writeStream.mock.calls.map(([value]) => value)).toEqual(['Answer', '\n'])
|
||||
expect(writeStream.mock.calls.flat().join('')).not.toContain('<options>')
|
||||
expect(writeStream.mock.calls.flat().join('')).not.toContain('forceful-arm')
|
||||
})
|
||||
|
||||
it('prints the safe partial answer before failing an errored run', async () => {
|
||||
mocks.request.mockResolvedValueOnce(snapshot('error', 'Partial answer'))
|
||||
const writeStream = vi.fn()
|
||||
|
||||
await expect(
|
||||
program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
showProgress: () => false,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
).rejects.toMatchObject({
|
||||
message: 'Sim Chat run ended with status "error".',
|
||||
code: 'CHAT_RUN_FAILED',
|
||||
})
|
||||
|
||||
expect(writeStream.mock.calls.map(([value]) => value)).toEqual(['Partial answer', '\n'])
|
||||
})
|
||||
|
||||
it('emits one final JSON snapshot before failing a cancelled run', async () => {
|
||||
mocks.request.mockResolvedValueOnce(snapshot('cancelled', 'Stopped safely'))
|
||||
mocks.output = 'json'
|
||||
const logged: string[] = []
|
||||
const log = vi.spyOn(console, 'log').mockImplementation((line: string) => logged.push(line))
|
||||
|
||||
try {
|
||||
await expect(
|
||||
program(async () => '', vi.fn(), {
|
||||
showProgress: () => false,
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
).rejects.toMatchObject({ code: 'CHAT_RUN_FAILED' })
|
||||
} finally {
|
||||
log.mockRestore()
|
||||
}
|
||||
|
||||
expect(logged).toHaveLength(1)
|
||||
expect(JSON.parse(logged[0])).toMatchObject({
|
||||
runId: 'run-1',
|
||||
status: 'cancelled',
|
||||
response: 'Stopped safely',
|
||||
})
|
||||
})
|
||||
|
||||
it('detaches on Ctrl+C without cancelling the run', async () => {
|
||||
mocks.request.mockResolvedValueOnce(snapshot('active', 'partial'))
|
||||
let interrupt: (() => void) | undefined
|
||||
const writeStream = vi.fn()
|
||||
const pollDelay = vi.fn(async () => {
|
||||
interrupt?.()
|
||||
})
|
||||
|
||||
await program(async () => '', vi.fn(), {
|
||||
writeStream,
|
||||
showProgress: () => false,
|
||||
pollDelay,
|
||||
onInterrupt: (listener) => {
|
||||
interrupt = listener
|
||||
return () => {
|
||||
interrupt = undefined
|
||||
}
|
||||
},
|
||||
}).parseAsync(['node', 'sim', 'chat', 'follow', 'run-1'])
|
||||
|
||||
expect(mocks.request).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.request.mock.calls[0][0]).toBe('/api/v2/chat/runs/run-1')
|
||||
expect(writeStream.mock.calls.map(([value]) => value)).toEqual(['partial', '\n'])
|
||||
})
|
||||
|
||||
it('rejects extra positional arguments after the run ID', async () => {
|
||||
await expect(
|
||||
program(async () => '').parseAsync(['node', 'sim', 'chat', 'follow', 'run-1', 'unexpected'])
|
||||
).rejects.toThrow(/too many arguments/i)
|
||||
|
||||
expect(mocks.request).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('chat command composition', () => {
|
||||
it('merges the manual chat protocol into an existing generated chat group', () => {
|
||||
const root = new Command('sim')
|
||||
const generatedChat = new Command('chat')
|
||||
const runs = new Command('runs').addCommand(new Command('get'))
|
||||
generatedChat.addCommand(runs)
|
||||
root.addCommand(generatedChat)
|
||||
|
||||
attachProtocolCommands(root)
|
||||
|
||||
expect(root.commands.filter((command) => command.name() === 'chat')).toEqual([generatedChat])
|
||||
expect(generatedChat.commands.map((command) => command.name()).sort()).toEqual([
|
||||
'ask',
|
||||
'follow',
|
||||
'runs',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('interactive chat', () => {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { setTimeout as delay } from 'node:timers/promises'
|
||||
import { Command } from 'commander'
|
||||
import type { OutputFormat } from '../../config/index.js'
|
||||
import { clientFrom } from '../../context.js'
|
||||
import type {
|
||||
ChatBody,
|
||||
GetChatResponse,
|
||||
GetChatRunResponse,
|
||||
GetWorkspaceResponse,
|
||||
ListChatsResponse,
|
||||
ListFilesResponse,
|
||||
@@ -43,6 +46,7 @@ import {
|
||||
type ChatTerminalSelectResult,
|
||||
ReadlineChatTerminal,
|
||||
} from './chat-terminal.js'
|
||||
import { printProtocolResult } from './result.js'
|
||||
|
||||
export interface ChatDependencies {
|
||||
readInput: (maxBytes: number) => Promise<string>
|
||||
@@ -53,6 +57,11 @@ export interface ChatDependencies {
|
||||
clipboardAttachment: () => Promise<ChatAttachment | null>
|
||||
extractAttachmentPaths: (input: string) => Promise<ExtractedAttachments | null>
|
||||
formatMarkdown: () => boolean
|
||||
writeStream: (content: string) => void
|
||||
writeProgress: (content: string) => void
|
||||
showProgress: () => boolean
|
||||
pollDelay: (milliseconds: number, signal: AbortSignal) => Promise<void>
|
||||
onInterrupt: (listener: () => void) => () => void
|
||||
}
|
||||
|
||||
interface ChatEvent {
|
||||
@@ -62,6 +71,7 @@ interface ChatEvent {
|
||||
error?: unknown
|
||||
continuationToken?: unknown
|
||||
chatId?: unknown
|
||||
runId?: unknown
|
||||
title?: unknown
|
||||
}
|
||||
|
||||
@@ -86,10 +96,44 @@ export interface ReadChatTurnOptions {
|
||||
onTitle?: (title: string) => void | Promise<void>
|
||||
}
|
||||
|
||||
type ChatRequest = ChatBody
|
||||
interface ChatAcceptance {
|
||||
runId: string
|
||||
chatId: string
|
||||
}
|
||||
|
||||
interface ChatRunSnapshot {
|
||||
runId: string
|
||||
chatId: string
|
||||
chatTitle?: string | null
|
||||
status: GetChatRunResponse['data']['status']
|
||||
startedAt?: string | null
|
||||
completedAt?: string | null
|
||||
response: string
|
||||
activities: ChatActivityUpdate[]
|
||||
}
|
||||
|
||||
interface ParsedChatRunSnapshot {
|
||||
/** Sanitized and shape-checked values used by the human renderer. */
|
||||
snapshot: ChatRunSnapshot
|
||||
/** Exact API data used by JSON/YAML, which preserve wire values by convention. */
|
||||
raw: Record<string, unknown>
|
||||
}
|
||||
|
||||
const MAX_CHAT_PROMPT_BYTES = 10 * 1024 * 1024
|
||||
const MAX_LOG_SUGGESTIONS = 50
|
||||
const CHAT_RUN_POLL_MS = 3_000
|
||||
const CHAT_RUN_STATUSES = new Set<GetChatRunResponse['data']['status']>([
|
||||
...V2_OPERATIONS.listChatRuns.query.status.values,
|
||||
])
|
||||
const TERMINAL_CHAT_RUN_STATUSES = new Set<GetChatRunResponse['data']['status']>([
|
||||
'complete',
|
||||
'error',
|
||||
'cancelled',
|
||||
])
|
||||
const FAILED_CHAT_RUN_STATUSES = new Set<GetChatRunResponse['data']['status']>([
|
||||
'error',
|
||||
'cancelled',
|
||||
])
|
||||
|
||||
function inputTooLarge(): SimApiError {
|
||||
return new SimApiError('Chat input exceeds the 10 MiB limit.', 0)
|
||||
@@ -189,6 +233,63 @@ function streamError(event: ChatEvent): SimApiError {
|
||||
)
|
||||
}
|
||||
|
||||
function eventString(event: ChatEvent, field: 'runId' | 'chatId'): string | null {
|
||||
const direct = event[field]
|
||||
if (typeof direct === 'string' && direct) return direct
|
||||
if (!event.data || typeof event.data !== 'object') return null
|
||||
const nested = (event.data as Record<string, unknown>)[field]
|
||||
return typeof nested === 'string' && nested ? nested : null
|
||||
}
|
||||
|
||||
/** Reads only the accepted session for a detached chat run, then closes the HTTP reader. */
|
||||
export async function readChatAcceptance(response: Response): Promise<ChatAcceptance> {
|
||||
if (!response.body) throw new SimApiError('Sim Chat returned an empty response.', 0)
|
||||
|
||||
let eventLines: string[] = []
|
||||
let runId: string | null = null
|
||||
let chatId: string | null = null
|
||||
|
||||
const consume = (): ChatAcceptance | null => {
|
||||
const raw = dataFromEvent(eventLines)
|
||||
eventLines = []
|
||||
if (raw === null || raw === '[DONE]') return null
|
||||
|
||||
let parsed: ChatEvent
|
||||
try {
|
||||
parsed = JSON.parse(raw) as ChatEvent
|
||||
} catch {
|
||||
throw new SimApiError('Sim Chat returned malformed streaming data.', 0)
|
||||
}
|
||||
|
||||
if (parsed.type === 'error') throw streamError(parsed)
|
||||
if (parsed.type !== 'session') return null
|
||||
runId = eventString(parsed, 'runId') ?? runId
|
||||
chatId = eventString(parsed, 'chatId') ?? chatId
|
||||
return runId && chatId ? { runId, chatId } : null
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const line of linesOf(response.body)) {
|
||||
if (line !== '') {
|
||||
eventLines.push(line)
|
||||
continue
|
||||
}
|
||||
const accepted = consume()
|
||||
if (accepted) return accepted
|
||||
}
|
||||
if (eventLines.length > 0) {
|
||||
const accepted = consume()
|
||||
if (accepted) return accepted
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof SimApiError) throw error
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
throw new SimApiError(`Sim Chat stream failed: ${sanitize(message)}`, 0)
|
||||
}
|
||||
|
||||
throw new SimApiError('Sim Chat ended before accepting the asynchronous run.', 0)
|
||||
}
|
||||
|
||||
function tokenFrom(value: unknown): string | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const token = (value as { continuationToken?: unknown }).continuationToken
|
||||
@@ -222,6 +323,71 @@ function activityFrom(value: unknown): ChatActivityUpdate | null {
|
||||
: null
|
||||
}
|
||||
|
||||
function optionalSnapshotString(value: unknown, field: string): string | null | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (value === null) return null
|
||||
if (typeof value !== 'string') {
|
||||
throw new SimApiError(`Sim Chat returned an invalid ${field}.`, 0)
|
||||
}
|
||||
return sanitize(value)
|
||||
}
|
||||
|
||||
function parseChatRunSnapshot(value: unknown, expectedRunId: string): ParsedChatRunSnapshot {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new SimApiError('Sim Chat returned an invalid run status.', 0)
|
||||
}
|
||||
const envelope = value as Record<string, unknown>
|
||||
const raw =
|
||||
envelope.data && typeof envelope.data === 'object' && !Array.isArray(envelope.data)
|
||||
? (envelope.data as Record<string, unknown>)
|
||||
: envelope
|
||||
const runId = optionalSnapshotString(raw.runId, 'run ID')
|
||||
const chatId = optionalSnapshotString(raw.chatId, 'chat ID')
|
||||
const status = optionalSnapshotString(raw.status, 'run status')
|
||||
if (!runId || !chatId || !status) {
|
||||
throw new SimApiError('Sim Chat returned an incomplete run status.', 0)
|
||||
}
|
||||
if (runId !== expectedRunId) {
|
||||
throw new SimApiError('Sim Chat returned status for a different run.', 0)
|
||||
}
|
||||
if (!CHAT_RUN_STATUSES.has(status as GetChatRunResponse['data']['status'])) {
|
||||
throw new SimApiError(`Sim Chat returned unknown run status "${safeOneLine(status)}".`, 0)
|
||||
}
|
||||
if (raw.response !== undefined && raw.response !== null && typeof raw.response !== 'string') {
|
||||
throw new SimApiError('Sim Chat returned an invalid run response.', 0)
|
||||
}
|
||||
if (raw.activities !== undefined && !Array.isArray(raw.activities)) {
|
||||
throw new SimApiError('Sim Chat returned invalid run activity.', 0)
|
||||
}
|
||||
|
||||
return {
|
||||
raw,
|
||||
snapshot: {
|
||||
runId,
|
||||
chatId,
|
||||
status: status as GetChatRunResponse['data']['status'],
|
||||
// The structured stream parser owns human-output sanitization. Retaining
|
||||
// the exact cumulative string here also makes prefix checks meaningful.
|
||||
response: typeof raw.response === 'string' ? raw.response : '',
|
||||
activities: Array.isArray(raw.activities)
|
||||
? raw.activities.flatMap((activity) => {
|
||||
const parsed = activityFrom(activity)
|
||||
return parsed ? [parsed] : []
|
||||
})
|
||||
: [],
|
||||
...(raw.chatTitle !== undefined
|
||||
? { chatTitle: optionalSnapshotString(raw.chatTitle, 'chat title') }
|
||||
: {}),
|
||||
...(raw.startedAt !== undefined
|
||||
? { startedAt: optionalSnapshotString(raw.startedAt, 'start time') }
|
||||
: {}),
|
||||
...(raw.completedAt !== undefined
|
||||
? { completedAt: optionalSnapshotString(raw.completedAt, 'completion time') }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads one public chat turn, optionally forwarding raw text deltas to a safe renderer. */
|
||||
export async function readChatTurn(
|
||||
response: Response,
|
||||
@@ -312,7 +478,7 @@ export async function readChatResponse(response: Response): Promise<string> {
|
||||
return (await readChatTurn(response)).content
|
||||
}
|
||||
|
||||
function requestChat(client: SimClient, body: ChatRequest, signal: AbortSignal): Promise<Response> {
|
||||
function requestChat(client: SimClient, body: ChatBody, signal: AbortSignal): Promise<Response> {
|
||||
return client.requestRaw(V2_OPERATIONS.chat.path, {
|
||||
method: 'POST',
|
||||
headers: { accept: 'text/event-stream' },
|
||||
@@ -322,6 +488,178 @@ function requestChat(client: SimClient, body: ChatRequest, signal: AbortSignal):
|
||||
})
|
||||
}
|
||||
|
||||
function isMachineOutput(format: OutputFormat): boolean {
|
||||
return format === 'json' || format === 'yaml'
|
||||
}
|
||||
|
||||
function renderRunProgress(
|
||||
snapshot: ChatRunSnapshot,
|
||||
previousStatus: string | undefined,
|
||||
seenActivityUpdates: Set<string>,
|
||||
write: (content: string) => void
|
||||
): void {
|
||||
if (snapshot.status !== previousStatus) write(`status: ${safeOneLine(snapshot.status)}\n`)
|
||||
|
||||
snapshot.activities.forEach((activity, index) => {
|
||||
if (activity.kind === 'narration') {
|
||||
const narration = safeOneLine(activity.delta)
|
||||
if (!narration) return
|
||||
const key = `${index}:narration:${activity.parentId}:${narration}`
|
||||
if (seenActivityUpdates.has(key)) return
|
||||
seenActivityUpdates.add(key)
|
||||
write(` ${narration}\n`)
|
||||
return
|
||||
}
|
||||
|
||||
// The API returns a cumulative, chronological activity snapshot. Include
|
||||
// the stable position and full public transition in the identity so a
|
||||
// running -> complete pair is emitted once each rather than replayed on
|
||||
// every poll.
|
||||
const key = `${index}:${activity.kind}:${activity.id}:${activity.state}:${activity.label}`
|
||||
if (seenActivityUpdates.has(key)) return
|
||||
seenActivityUpdates.add(key)
|
||||
const marker = activity.state === 'running' ? '●' : activity.state === 'complete' ? '✓' : '✗'
|
||||
write(`${marker} ${safeOneLine(activity.label)}\n`)
|
||||
})
|
||||
}
|
||||
|
||||
async function followChatRun(
|
||||
client: SimClient,
|
||||
workspaceId: string,
|
||||
runId: string,
|
||||
format: OutputFormat,
|
||||
dependencies: ChatDependencies
|
||||
): Promise<void> {
|
||||
const controller = new AbortController()
|
||||
let interrupted = false
|
||||
const stopListening = dependencies.onInterrupt(() => {
|
||||
interrupted = true
|
||||
controller.abort()
|
||||
})
|
||||
const machineOutput = isMachineOutput(format)
|
||||
const progressEnabled = !machineOutput && dependencies.showProgress()
|
||||
const seenActivityUpdates = new Set<string>()
|
||||
const responseParser = machineOutput ? null : new ChatStructuredParser()
|
||||
const responseSegments: ChatStructuredSegment[] = []
|
||||
let observedResponse = ''
|
||||
let emittedResponse = ''
|
||||
let renderedProgressStatus: string | undefined
|
||||
let finalSnapshot: ChatRunSnapshot | undefined
|
||||
let finalRawSnapshot: Record<string, unknown> | undefined
|
||||
|
||||
try {
|
||||
while (!interrupted) {
|
||||
let result: GetChatRunResponse
|
||||
try {
|
||||
result = await client.request<GetChatRunResponse>(
|
||||
resolvePath(V2_OPERATIONS.getChatRun.path, { runId }),
|
||||
{
|
||||
query: { workspaceId },
|
||||
signal: controller.signal,
|
||||
auth: 'optional',
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
if (interrupted || controller.signal.aborted) break
|
||||
if (error instanceof SimApiError && (error.status === 429 || error.status >= 500)) {
|
||||
try {
|
||||
await dependencies.pollDelay(CHAT_RUN_POLL_MS, controller.signal)
|
||||
} catch (delayError) {
|
||||
if (interrupted || controller.signal.aborted) break
|
||||
throw delayError
|
||||
}
|
||||
continue
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
const parsed = parseChatRunSnapshot(result, runId)
|
||||
const { snapshot } = parsed
|
||||
finalSnapshot = snapshot
|
||||
finalRawSnapshot = parsed.raw
|
||||
|
||||
let displayDelta = ''
|
||||
if (!machineOutput) {
|
||||
if (!snapshot.response.startsWith(observedResponse)) {
|
||||
throw new SimApiError('Sim Chat returned a non-monotonic run response.', 0)
|
||||
}
|
||||
const responseDelta = snapshot.response.slice(observedResponse.length)
|
||||
observedResponse = snapshot.response
|
||||
if (responseDelta) responseSegments.push(...responseParser!.push(responseDelta))
|
||||
const terminal = TERMINAL_CHAT_RUN_STATUSES.has(snapshot.status)
|
||||
if (terminal) responseSegments.push(...responseParser!.finish())
|
||||
|
||||
const rendered = sanitize(
|
||||
renderChatStructured(
|
||||
withoutTrailingStandaloneResource(responseSegments),
|
||||
renderContext(false)
|
||||
).text
|
||||
)
|
||||
// A future structured tag may own the whitespace immediately before
|
||||
// it. Hold that tiny unstable suffix until more content or completion
|
||||
// makes its purpose known, while still streaming all substantive text.
|
||||
const stableRendered = terminal ? rendered : rendered.trimEnd()
|
||||
if (!stableRendered.startsWith(emittedResponse)) {
|
||||
throw new SimApiError('Sim Chat returned non-monotonic rendered output.', 0)
|
||||
}
|
||||
displayDelta = stableRendered.slice(emittedResponse.length)
|
||||
// Progress owns complete lines. Once response prose starts, defer any
|
||||
// later progress until the response has received its final newline so
|
||||
// stdout and stderr cannot concatenate on a shared terminal.
|
||||
if (progressEnabled && !emittedResponse) {
|
||||
renderRunProgress(
|
||||
snapshot,
|
||||
renderedProgressStatus,
|
||||
seenActivityUpdates,
|
||||
dependencies.writeProgress
|
||||
)
|
||||
renderedProgressStatus = snapshot.status
|
||||
}
|
||||
if (displayDelta) dependencies.writeStream(displayDelta)
|
||||
emittedResponse = stableRendered
|
||||
}
|
||||
|
||||
if (TERMINAL_CHAT_RUN_STATUSES.has(snapshot.status)) break
|
||||
try {
|
||||
await dependencies.pollDelay(CHAT_RUN_POLL_MS, controller.signal)
|
||||
} catch (error) {
|
||||
if (interrupted || controller.signal.aborted) break
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
stopListening()
|
||||
}
|
||||
|
||||
if (interrupted) {
|
||||
if (!machineOutput && emittedResponse && !emittedResponse.endsWith('\n')) {
|
||||
dependencies.writeStream('\n')
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!finalSnapshot) return
|
||||
if (machineOutput) {
|
||||
printProtocolResult(format, finalRawSnapshot ?? { ...finalSnapshot })
|
||||
} else {
|
||||
if (emittedResponse && !emittedResponse.endsWith('\n')) dependencies.writeStream('\n')
|
||||
if (progressEnabled && emittedResponse) {
|
||||
renderRunProgress(
|
||||
finalSnapshot,
|
||||
renderedProgressStatus,
|
||||
seenActivityUpdates,
|
||||
dependencies.writeProgress
|
||||
)
|
||||
}
|
||||
}
|
||||
if (FAILED_CHAT_RUN_STATUSES.has(finalSnapshot.status)) {
|
||||
throw new SimApiError(
|
||||
`Sim Chat run ended with status "${safeOneLine(finalSnapshot.status)}".`,
|
||||
0,
|
||||
'CHAT_RUN_FAILED'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function renderContext(interactive: boolean) {
|
||||
return { printMode: !interactive }
|
||||
}
|
||||
@@ -333,7 +671,9 @@ async function runOneShot(
|
||||
attachments: ChatAttachment[],
|
||||
readOnly: boolean,
|
||||
dependencies: ChatDependencies,
|
||||
continuationToken?: string
|
||||
output: OutputFormat,
|
||||
continuationToken?: string,
|
||||
asyncMode = false
|
||||
): Promise<void> {
|
||||
const controller = new AbortController()
|
||||
const cancel = () => controller.abort()
|
||||
@@ -345,18 +685,46 @@ async function runOneShot(
|
||||
{
|
||||
workspaceId,
|
||||
prompt,
|
||||
// The server's default persists a normal one-shot chat. Keep the new
|
||||
// field off the blocking wire for compatibility with older strict v2
|
||||
// servers; detached runs must opt in explicitly to both behaviors.
|
||||
...(asyncMode ? { async: true, persistChat: true } : {}),
|
||||
...(readOnly ? { readOnly: true } : {}),
|
||||
...(continuationToken ? { continuationToken } : {}),
|
||||
...(attachments.length ? { attachments } : {}),
|
||||
},
|
||||
controller.signal
|
||||
)
|
||||
const result = await readChatTurn(response)
|
||||
if (asyncMode) {
|
||||
const accepted = await readChatAcceptance(response)
|
||||
printProtocolResult(output, { ...accepted, status: 'active' })
|
||||
return
|
||||
}
|
||||
let chatId: string | null = null
|
||||
const result = await readChatTurn(response, {
|
||||
onChatId: (acceptedChatId) => {
|
||||
chatId = acceptedChatId
|
||||
},
|
||||
})
|
||||
const segments = withoutTrailingStandaloneResource(parseChatStructured(result.content))
|
||||
const rendered = renderChatStructured(segments, renderContext(false))
|
||||
// Print mode deliberately has no ANSI/OSC of its own, so a final defense at
|
||||
// the stdout boundary is safe and preserves shell composability.
|
||||
dependencies.writeOutput(sanitize(rendered.text))
|
||||
const content = sanitize(rendered.text)
|
||||
if (isMachineOutput(output)) {
|
||||
// Machine formats preserve the server's exact completed content. JSON
|
||||
// and YAML encode control bytes safely and are the lossless API surface.
|
||||
printProtocolResult(output, { content: result.content, chatId })
|
||||
return
|
||||
}
|
||||
dependencies.writeOutput(content)
|
||||
if (dependencies.showProgress()) {
|
||||
dependencies.writeProgress(
|
||||
chatId
|
||||
? `chat: ${safeOneLine(chatId)}\n`
|
||||
: 'chat: not saved (a personal API key is required for resumable history)\n'
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw new SimApiError('Sim Chat cancelled.', 0)
|
||||
throw error
|
||||
@@ -1450,8 +1818,24 @@ function collectFile(value: string, previous: string[] = []): string[] {
|
||||
return [...previous, value]
|
||||
}
|
||||
|
||||
/** Creates print-mode and interactive workspace chat. */
|
||||
export function chatCommand(overrides: Partial<ChatDependencies> = {}): Command {
|
||||
interface ChatCommandOptions {
|
||||
async?: boolean
|
||||
chat?: string
|
||||
file?: string[]
|
||||
readOnly?: boolean
|
||||
}
|
||||
|
||||
function addChatInputOptions(command: Command): Command {
|
||||
return command
|
||||
.option('-f, --file <path>', 'Attach a local file (repeatable)', collectFile, [])
|
||||
.option('--read-only', 'Restrict Sim Chat to read-only workspace tools')
|
||||
}
|
||||
|
||||
/** Creates one-shot and interactive workspace chat. */
|
||||
export function chatCommand(
|
||||
overrides: Partial<ChatDependencies> = {},
|
||||
target = new Command('chat')
|
||||
): Command {
|
||||
const dependencies: ChatDependencies = {
|
||||
readInput: readPipedInput,
|
||||
writeOutput: writeCompletedAnswer,
|
||||
@@ -1465,97 +1849,127 @@ export function chatCommand(overrides: Partial<ChatDependencies> = {}): Command
|
||||
// propagated TERM=dumb value must not leave model Markdown visible inside
|
||||
// an otherwise fully rendered TUI.
|
||||
formatMarkdown: () => Boolean(process.stdout.isTTY),
|
||||
writeStream: (content) => process.stdout.write(content),
|
||||
writeProgress: (content) => process.stderr.write(content),
|
||||
showProgress: () => Boolean(process.stderr.isTTY),
|
||||
pollDelay: (milliseconds, signal) => delay(milliseconds, undefined, { signal }),
|
||||
onInterrupt: (listener) => {
|
||||
process.once('SIGINT', listener)
|
||||
return () => process.removeListener('SIGINT', listener)
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
|
||||
return new Command('chat')
|
||||
.description('Ask Sim Chat about the active workspace')
|
||||
.argument('[prompt...]', 'Question to ask')
|
||||
.option('-p, --print', 'Print the final response and exit')
|
||||
.option('--chat <chatId>', 'Resume an existing chat by ID (print mode only)')
|
||||
.option('-f, --file <path>', 'Attach a local file (repeatable)', collectFile, [])
|
||||
.option('--read-only', 'Restrict Sim Chat to read-only workspace tools')
|
||||
.action(
|
||||
async (
|
||||
promptParts: string[],
|
||||
options: { print?: boolean; chat?: string; file: string[]; readOnly?: boolean },
|
||||
command: Command
|
||||
) => {
|
||||
const positionalPrompt = promptParts.join(' ')
|
||||
const positionalBytes = utf8Bytes(positionalPrompt)
|
||||
if (positionalBytes > MAX_CHAT_PROMPT_BYTES) throw inputTooLarge()
|
||||
const run = async (promptParts: string[], oneShot: boolean, command: Command): Promise<void> => {
|
||||
const options = command.optsWithGlobals() as ChatCommandOptions
|
||||
const positionalPrompt = promptParts.join(' ')
|
||||
const positionalBytes = utf8Bytes(positionalPrompt)
|
||||
if (positionalBytes > MAX_CHAT_PROMPT_BYTES) throw inputTooLarge()
|
||||
|
||||
const chatId = options.chat?.trim()
|
||||
if (options.chat !== undefined && !chatId) {
|
||||
throw new SimApiError('Chat ID must not be empty.', 0)
|
||||
}
|
||||
if (chatId && !options.print) {
|
||||
throw new SimApiError(
|
||||
'--chat can only be used with -p/--print. Use /chats in interactive mode.',
|
||||
0
|
||||
)
|
||||
}
|
||||
const chatId = options.chat?.trim()
|
||||
if (options.chat !== undefined && !chatId) {
|
||||
throw new SimApiError('Chat ID must not be empty.', 0)
|
||||
}
|
||||
|
||||
const interactive = !options.print && dependencies.isInteractive()
|
||||
if (!options.print && !interactive) {
|
||||
throw new SimApiError(
|
||||
'Interactive Sim Chat requires a terminal. Use sim chat -p for pipelines or redirected output.',
|
||||
0
|
||||
)
|
||||
}
|
||||
const separatorBytes = positionalPrompt ? 1 : 0
|
||||
const pipedInput = interactive
|
||||
? ''
|
||||
: await dependencies.readInput(MAX_CHAT_PROMPT_BYTES - positionalBytes - separatorBytes)
|
||||
const prompt = composeChatPrompt(promptParts, pipedInput)
|
||||
if (utf8Bytes(prompt) > MAX_CHAT_PROMPT_BYTES) throw inputTooLarge()
|
||||
const interactive = !oneShot && dependencies.isInteractive()
|
||||
if (!oneShot && !interactive) {
|
||||
throw new SimApiError(
|
||||
'Interactive Sim Chat requires a terminal. Use sim chat ask for pipelines or redirected output.',
|
||||
0
|
||||
)
|
||||
}
|
||||
const separatorBytes = positionalPrompt ? 1 : 0
|
||||
const pipedInput = interactive
|
||||
? ''
|
||||
: await dependencies.readInput(MAX_CHAT_PROMPT_BYTES - positionalBytes - separatorBytes)
|
||||
const prompt = composeChatPrompt(promptParts, pipedInput)
|
||||
if (utf8Bytes(prompt) > MAX_CHAT_PROMPT_BYTES) throw inputTooLarge()
|
||||
|
||||
const attachments = await dependencies.loadAttachments(options.file ?? [])
|
||||
if (!interactive && !prompt.trim() && attachments.length === 0) {
|
||||
throw new SimApiError('Provide a prompt, attach a file, or pipe input to sim chat -p.', 0)
|
||||
}
|
||||
const attachments = await dependencies.loadAttachments(options.file ?? [])
|
||||
if (!interactive && !prompt.trim() && attachments.length === 0) {
|
||||
throw new SimApiError('Provide a prompt, attach a file, or pipe input to sim chat ask.', 0)
|
||||
}
|
||||
|
||||
const { client, profile } = clientFrom(command)
|
||||
const workspaceId = client.requireWorkspace(undefined, { auth: 'optional' })
|
||||
if (interactive) {
|
||||
await runInteractive(
|
||||
client,
|
||||
workspaceId,
|
||||
prompt,
|
||||
attachments,
|
||||
options.readOnly === true,
|
||||
dependencies,
|
||||
profile.name
|
||||
)
|
||||
return
|
||||
}
|
||||
let continuationToken: string | undefined
|
||||
if (chatId) {
|
||||
const chat = await loadChat(client, workspaceId, chatId, options.readOnly === true)
|
||||
if (!chat.continuationToken) {
|
||||
throw new SimApiError(
|
||||
'Sim Chat did not return a continuation token for the selected chat.',
|
||||
0
|
||||
)
|
||||
}
|
||||
if (chat.active) {
|
||||
throw new SimApiError(
|
||||
'The selected chat is currently active in another client. Wait for it to finish before resuming it.',
|
||||
409,
|
||||
'CONFLICT'
|
||||
)
|
||||
}
|
||||
continuationToken = chat.continuationToken
|
||||
}
|
||||
await runOneShot(
|
||||
client,
|
||||
workspaceId,
|
||||
prompt,
|
||||
attachments,
|
||||
options.readOnly === true,
|
||||
dependencies,
|
||||
continuationToken
|
||||
const { client, profile } = clientFrom(command)
|
||||
const workspaceId = client.requireWorkspace(undefined, { auth: 'optional' })
|
||||
if (interactive) {
|
||||
await runInteractive(
|
||||
client,
|
||||
workspaceId,
|
||||
prompt,
|
||||
attachments,
|
||||
options.readOnly === true,
|
||||
dependencies,
|
||||
profile.name
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let continuationToken: string | undefined
|
||||
if (chatId) {
|
||||
const chat = await loadChat(client, workspaceId, chatId, options.readOnly === true)
|
||||
if (!chat.continuationToken) {
|
||||
throw new SimApiError(
|
||||
'Sim Chat did not return a continuation token for the selected chat.',
|
||||
0
|
||||
)
|
||||
}
|
||||
if (chat.active) {
|
||||
throw new SimApiError(
|
||||
'The selected chat is currently active in another client. Wait for it to finish before resuming it.',
|
||||
409,
|
||||
'CONFLICT'
|
||||
)
|
||||
}
|
||||
continuationToken = chat.continuationToken
|
||||
}
|
||||
await runOneShot(
|
||||
client,
|
||||
workspaceId,
|
||||
prompt,
|
||||
attachments,
|
||||
options.readOnly === true,
|
||||
dependencies,
|
||||
profile.output,
|
||||
continuationToken,
|
||||
options.async === true
|
||||
)
|
||||
}
|
||||
|
||||
const chat = addChatInputOptions(target)
|
||||
.description('Ask Sim Chat about the active workspace')
|
||||
.argument('[prompt...]', 'Question to ask')
|
||||
.action((promptParts: string[], _options: ChatCommandOptions, command: Command) =>
|
||||
run(promptParts, false, command)
|
||||
)
|
||||
|
||||
const ask = addChatInputOptions(new Command('ask'))
|
||||
.description('Ask once, save the chat, print the response, and exit')
|
||||
.argument('[prompt...]', 'Question to ask')
|
||||
.option('--chat <chatId>', 'Continue an existing chat by ID')
|
||||
.option('--async', 'Start the chat run and return immediately')
|
||||
.action((promptParts: string[], _options: ChatCommandOptions, command: Command) =>
|
||||
run(promptParts, true, command)
|
||||
)
|
||||
|
||||
const follow = new Command('follow')
|
||||
.description('Follow a chat run until it finishes')
|
||||
.argument('<runId>', 'Chat run ID returned by chat ask --async')
|
||||
.allowExcessArguments(false)
|
||||
.action(async (runId: string, _options: unknown, command: Command) => {
|
||||
const normalizedRunId = runId.trim()
|
||||
if (!normalizedRunId) throw new SimApiError('Run ID must not be empty.', 0)
|
||||
const { client, profile } = clientFrom(command)
|
||||
await followChatRun(
|
||||
client,
|
||||
client.requireWorkspace(undefined, { auth: 'optional' }),
|
||||
normalizedRunId,
|
||||
profile.output,
|
||||
dependencies
|
||||
)
|
||||
})
|
||||
|
||||
chat.addCommand(ask)
|
||||
chat.addCommand(follow)
|
||||
return chat
|
||||
}
|
||||
@@ -16,7 +16,7 @@ function group(program: Command, name: string): Command {
|
||||
|
||||
/** Attaches commands whose multi-request or binary protocols cannot be generated. */
|
||||
export function attachProtocolCommands(program: Command): void {
|
||||
program.addCommand(chatCommand())
|
||||
chatCommand({}, group(program, 'chat'))
|
||||
|
||||
const files = group(program, 'files')
|
||||
attachFileUpload(files)
|
||||
|
||||
@@ -317,6 +317,30 @@ export const CLI_CONTRACT: CliContract = {
|
||||
{ header: 'active', format: 'bool' },
|
||||
],
|
||||
},
|
||||
listChatRuns: {
|
||||
describe: 'List recent Sim Chat runs',
|
||||
auth: 'optional',
|
||||
flags: { status: { describe: 'Filter by durable run status' } },
|
||||
columns: [
|
||||
{ header: 'started', path: 'startedAt', format: 'timestamp' },
|
||||
{ header: 'status' },
|
||||
{ header: 'title', path: 'chatTitle' },
|
||||
{ header: 'chat', path: 'chatId' },
|
||||
{ header: 'run', path: 'runId' },
|
||||
],
|
||||
},
|
||||
getChatRun: {
|
||||
describe: 'Show chat run status (response and activity are included in JSON or YAML output)',
|
||||
auth: 'optional',
|
||||
fields: [
|
||||
{ header: 'run', path: 'runId' },
|
||||
{ header: 'chat', path: 'chatId' },
|
||||
{ header: 'title', path: 'chatTitle' },
|
||||
{ header: 'status' },
|
||||
{ header: 'started', path: 'startedAt', format: 'timestamp' },
|
||||
{ header: 'completed', path: 'completedAt', format: 'timestamp' },
|
||||
],
|
||||
},
|
||||
renameChat: {
|
||||
command: 'chats rename',
|
||||
describe: 'Rename a chat',
|
||||
|
||||
@@ -135,6 +135,8 @@ export interface CommandSpec {
|
||||
variants?: readonly CommandVariantSpec[]
|
||||
/** One-line help. Falls back to the OpenAPI summary for the operation. */
|
||||
describe?: string
|
||||
/** Allow an auth-disabled self-hosted route to run without a locally stored API key. */
|
||||
auth?: 'required' | 'optional'
|
||||
/** Per-field flag overrides, keyed by the contract's field name. */
|
||||
flags?: Record<string, FlagSpec>
|
||||
/** Friendly mutually-exclusive flags for an otherwise opaque union body. */
|
||||
|
||||
@@ -358,6 +358,8 @@ export type ChatBody = {
|
||||
prompt: string
|
||||
continuationToken?: string
|
||||
readOnly?: boolean
|
||||
async?: boolean
|
||||
persistChat?: boolean
|
||||
attachments?: Array<{
|
||||
name: string
|
||||
mediaType: string
|
||||
@@ -1661,6 +1663,11 @@ export type DeployWorkflowParams = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type DeployWorkflowBody = {
|
||||
name?: string
|
||||
description?: string | null
|
||||
}
|
||||
|
||||
export type DeployWorkflowResponse = {
|
||||
data: {
|
||||
id: string
|
||||
@@ -1978,6 +1985,41 @@ export type GetChatResponse = {
|
||||
}
|
||||
}
|
||||
|
||||
/** `GET /api/v2/chat/runs/[runId]` */
|
||||
export type GetChatRunParams = {
|
||||
runId: string
|
||||
}
|
||||
|
||||
export type GetChatRunQuery = {
|
||||
workspaceId: string
|
||||
}
|
||||
|
||||
export type GetChatRunResponse = {
|
||||
data: {
|
||||
runId: string
|
||||
chatId: string
|
||||
chatTitle: string | null
|
||||
status: 'active' | 'paused_waiting_for_tool' | 'resuming' | 'complete' | 'error' | 'cancelled'
|
||||
startedAt: string
|
||||
completedAt: string | null
|
||||
response: string
|
||||
activities: Array<
|
||||
| {
|
||||
kind: 'subagent' | 'tool'
|
||||
id: string
|
||||
parentId?: string
|
||||
label: string
|
||||
state: 'running' | 'complete' | 'error'
|
||||
}
|
||||
| {
|
||||
kind: 'narration'
|
||||
parentId: string
|
||||
delta: string
|
||||
}
|
||||
>
|
||||
}
|
||||
}
|
||||
|
||||
/** `GET /api/v2/custom-tools/[id]` */
|
||||
export type GetCustomToolParams = {
|
||||
id: string
|
||||
@@ -2663,6 +2705,26 @@ export type ListBillingLogsResponse = {
|
||||
nextCursor: string | null
|
||||
}
|
||||
|
||||
/** `GET /api/v2/chat/runs` */
|
||||
export type ListChatRunsQuery = {
|
||||
workspaceId: string
|
||||
status?: 'active' | 'paused_waiting_for_tool' | 'resuming' | 'complete' | 'error' | 'cancelled'
|
||||
limit?: number
|
||||
cursor?: string
|
||||
}
|
||||
|
||||
export type ListChatRunsResponse = {
|
||||
data: Array<{
|
||||
runId: string
|
||||
chatId: string
|
||||
chatTitle: string | null
|
||||
status: 'active' | 'paused_waiting_for_tool' | 'resuming' | 'complete' | 'error' | 'cancelled'
|
||||
startedAt: string
|
||||
completedAt: string | null
|
||||
}>
|
||||
nextCursor: string | null
|
||||
}
|
||||
|
||||
/** `GET /api/v2/chats` */
|
||||
export type ListChatsQuery = {
|
||||
workspaceId: string
|
||||
@@ -3548,6 +3610,10 @@ export type RollbackWorkflowParams = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type RollbackWorkflowBody = {
|
||||
version?: number
|
||||
}
|
||||
|
||||
export type RollbackWorkflowResponse = {
|
||||
data: {
|
||||
id: string
|
||||
@@ -4432,6 +4498,8 @@ export const V2_OPERATIONS = {
|
||||
prompt: { kind: 'string', required: true },
|
||||
continuationToken: { kind: 'string' },
|
||||
readOnly: { kind: 'boolean', default: false },
|
||||
async: { kind: 'boolean', default: false },
|
||||
persistChat: { kind: 'boolean', default: true },
|
||||
attachments: { kind: 'array' },
|
||||
contexts: { kind: 'array' },
|
||||
},
|
||||
@@ -4933,6 +5001,10 @@ export const V2_OPERATIONS = {
|
||||
pathParams: ['id'] as const,
|
||||
responseMode: 'json',
|
||||
summary: 'Deploy Workflow',
|
||||
body: {
|
||||
name: { kind: 'string' },
|
||||
description: { kind: 'string' },
|
||||
},
|
||||
},
|
||||
downloadFile: {
|
||||
method: 'GET',
|
||||
@@ -5013,6 +5085,16 @@ export const V2_OPERATIONS = {
|
||||
readOnly: { kind: 'boolean' },
|
||||
},
|
||||
},
|
||||
getChatRun: {
|
||||
method: 'GET',
|
||||
path: '/api/v2/chat/runs/[runId]',
|
||||
pathParams: ['runId'] as const,
|
||||
responseMode: 'json',
|
||||
summary: 'Get Sim Chat Run',
|
||||
query: {
|
||||
workspaceId: { kind: 'string', required: true },
|
||||
},
|
||||
},
|
||||
getCustomTool: {
|
||||
method: 'GET',
|
||||
path: '/api/v2/custom-tools/[id]',
|
||||
@@ -5239,6 +5321,29 @@ export const V2_OPERATIONS = {
|
||||
cursor: { kind: 'string' },
|
||||
},
|
||||
},
|
||||
listChatRuns: {
|
||||
method: 'GET',
|
||||
path: '/api/v2/chat/runs',
|
||||
pathParams: [] as const,
|
||||
responseMode: 'json',
|
||||
summary: 'List Sim Chat Runs',
|
||||
query: {
|
||||
workspaceId: { kind: 'string', required: true },
|
||||
status: {
|
||||
kind: 'enum',
|
||||
values: [
|
||||
'active',
|
||||
'paused_waiting_for_tool',
|
||||
'resuming',
|
||||
'complete',
|
||||
'error',
|
||||
'cancelled',
|
||||
] as const,
|
||||
},
|
||||
limit: { kind: 'number', default: 30 },
|
||||
cursor: { kind: 'string' },
|
||||
},
|
||||
},
|
||||
listChats: {
|
||||
method: 'GET',
|
||||
path: '/api/v2/chats',
|
||||
@@ -5737,6 +5842,9 @@ export const V2_OPERATIONS = {
|
||||
pathParams: ['id'] as const,
|
||||
responseMode: 'json',
|
||||
summary: 'Rollback Workflow',
|
||||
body: {
|
||||
version: { kind: 'integer' },
|
||||
},
|
||||
},
|
||||
runRowEnrichment: {
|
||||
method: 'POST',
|
||||
|
||||
@@ -32,7 +32,7 @@ program
|
||||
.name('sim')
|
||||
.description('Talk to the Sim API from your terminal')
|
||||
.version(readPackageVersion())
|
||||
.option('-P, --profile <name>', 'Profile to use (env: SIM_PROFILE)')
|
||||
.option('-p, --profile <name>', 'Profile to use (env: SIM_PROFILE)')
|
||||
.option('--endpoint <url>', 'Sim deployment to talk to (env: SIM_ENDPOINT)')
|
||||
.option('-w, --workspace <id>', 'Workspace to target (env: SIM_WORKSPACE)')
|
||||
.addOption(
|
||||
@@ -55,12 +55,12 @@ program.addHelpText(
|
||||
'after',
|
||||
`
|
||||
Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in
|
||||
~/.sim/credentials (0600). Select one with -P, --profile, or SIM_PROFILE.
|
||||
~/.sim/credentials (0600). Select one with -p, --profile, or SIM_PROFILE.
|
||||
|
||||
Examples:
|
||||
$ sim login Authorize the default profile
|
||||
$ sim login --profile dev --endpoint http://localhost:3000
|
||||
$ sim chat -p "Which workflows handle support tickets?"
|
||||
$ sim chat ask "Which workflows handle support tickets?"
|
||||
$ sim workflows list
|
||||
$ sim logs list --level error --limit 20
|
||||
$ sim --output json tables get tbl_123 Override output for one command
|
||||
|
||||
@@ -158,6 +158,41 @@ describe('commands parsed through commander', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes pollable chat runs under the manual chat command group', async () => {
|
||||
expect(
|
||||
commandAt('chat', 'runs')
|
||||
.commands.map((command) => command.name())
|
||||
.sort()
|
||||
).toEqual(['get', 'list'])
|
||||
|
||||
const listHelp = commandAt('chat', 'runs', 'list').helpInformation()
|
||||
expect(listHelp).toContain('--status <value>')
|
||||
expect(listHelp).toContain('--limit <n>')
|
||||
const [listPath, listOptions] = await run([
|
||||
'chat',
|
||||
'runs',
|
||||
'list',
|
||||
'--status',
|
||||
'active',
|
||||
'--limit',
|
||||
'5',
|
||||
])
|
||||
expect(listPath).toBe('/api/v2/chat/runs')
|
||||
expect(listOptions.query).toMatchObject({
|
||||
workspaceId: 'ws_local',
|
||||
status: 'active',
|
||||
limit: 5,
|
||||
})
|
||||
expect(listOptions.auth).toBe('optional')
|
||||
|
||||
const get = commandAt('chat', 'runs', 'get')
|
||||
expect(get.description()).toContain('response and activity')
|
||||
const [getPath, getOptions] = await run(['chat', 'runs', 'get', 'run_1'])
|
||||
expect(getPath).toBe('/api/v2/chat/runs/run_1')
|
||||
expect(getOptions.query).toEqual({ workspaceId: 'ws_local' })
|
||||
expect(getOptions.auth).toBe('optional')
|
||||
})
|
||||
|
||||
it('describes generated resource and sub-resource groups', () => {
|
||||
expect(commandAt('tables').description()).toBe('Manage tables')
|
||||
expect(commandAt('tables', 'rows').description()).toBe('Manage table rows')
|
||||
|
||||
@@ -54,6 +54,7 @@ export async function executeOperation(
|
||||
}
|
||||
|
||||
const { client, profile } = clientFrom(host)
|
||||
const auth = commandSpec.auth
|
||||
const hasWorkspaceField = Boolean(
|
||||
(operationSpec.query && PROFILE_INJECTED_FIELD in operationSpec.query) ||
|
||||
(operationSpec.body && PROFILE_INJECTED_FIELD in operationSpec.body)
|
||||
@@ -63,7 +64,11 @@ export async function executeOperation(
|
||||
operation,
|
||||
positional,
|
||||
requestFlags,
|
||||
hasWorkspaceField && !omitsWorkspace ? client.requireWorkspace() : profile.workspaceId
|
||||
hasWorkspaceField && !omitsWorkspace
|
||||
? auth
|
||||
? client.requireWorkspace(undefined, { auth })
|
||||
: client.requireWorkspace()
|
||||
: profile.workspaceId
|
||||
)
|
||||
const paging = cursorSlot(operationSpec)
|
||||
|
||||
@@ -87,6 +92,7 @@ export async function executeOperation(
|
||||
paging === 'body'
|
||||
? { ...(request.body ?? {}), ...pageLimit, ...(cursor ? { cursor } : {}) }
|
||||
: request.body,
|
||||
...(auth ? { auth } : {}),
|
||||
})
|
||||
rows.push(...page.data)
|
||||
cursor = page.nextCursor
|
||||
@@ -100,6 +106,7 @@ export async function executeOperation(
|
||||
method: operationSpec.method,
|
||||
query: request.query,
|
||||
body: request.body,
|
||||
...(auth ? { auth } : {}),
|
||||
})
|
||||
renderResult(operation, profile.output, result?.data ?? result, commandSpec, {
|
||||
expandedTrace: requestFlags.trace === true,
|
||||
|
||||
@@ -9,8 +9,8 @@ const QUERY_HOOKS_DIR = path.join(ROOT, 'apps/sim/hooks/queries')
|
||||
const SELECTOR_HOOKS_DIR = path.join(ROOT, 'apps/sim/hooks/selectors')
|
||||
|
||||
const BASELINE = {
|
||||
totalRoutes: 1093,
|
||||
zodRoutes: 1093,
|
||||
totalRoutes: 1095,
|
||||
zodRoutes: 1095,
|
||||
nonZodRoutes: 0,
|
||||
} as const
|
||||
|
||||
|
||||
Reference in new issue
Block a user