From cd3ea37c78b7e61682f17d58d73e469f02d22612 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 12:40:18 +0700 Subject: [PATCH 1/4] fix(ai): a refusal also reads from content_filter, message.refusal and a top-level stop_reason Refs #30 (item 5 leftovers). Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/ai/agent.go | 17 +++++----- nexus-platform/internal/ai/agent_test.go | 31 +++++++++++++++++++ nexus-platform/internal/ai/assistant_agent.go | 12 +++---- nexus-platform/internal/ai/gateway.go | 26 +++++++++++----- nexus-platform/internal/ai/gateway_test.go | 26 ++++++++++------ 5 files changed, 82 insertions(+), 30 deletions(-) diff --git a/nexus-platform/internal/ai/agent.go b/nexus-platform/internal/ai/agent.go index fb0dd8f..fcc993e 100644 --- a/nexus-platform/internal/ai/agent.go +++ b/nexus-platform/internal/ai/agent.go @@ -223,6 +223,15 @@ func (a *AIBuilderAgent) ChatWithProgress(ctx context.Context, scope Scope, tena // separate gateway round-trip → its tokens are a real cost, so we SUM, not overwrite). usage.add(resp.Usage) + // A refusal ends the turn before its partial text or tool calls are used; proposals from earlier calls + // stay, as on max_steps. The outcome is what tells the panel the model declined (issue #30 item 5). It is + // read before the choices: Claude's top-level stop_reason may come with none. + if resp.Refused() { + a.emitStep(onStep, StepEvent{Step: step + 1, MaxSteps: a.cfg.MaxSteps, Phase: StepPhaseFinal}) + outcome = outcomeRefused + return Result{Draft: finalizeDraft(exec.draft, turn), Usage: usage, RunID: runID, Outcome: outcome}, nil + } + if len(resp.Choices) == 0 { outcome = outcomeGatewayError return Result{RunID: runID, Draft: exec.draft, Outcome: outcome}, @@ -230,14 +239,6 @@ func (a *AIBuilderAgent) ChatWithProgress(ctx context.Context, scope Scope, tena } msg := resp.Choices[0].Message - // A refusal ends the turn before its partial text or tool calls are used; proposals from earlier calls - // stay, as on max_steps. The outcome is what tells the panel the model declined (issue #30 item 5). - if resp.Choices[0].Refused() { - a.emitStep(onStep, StepEvent{Step: step + 1, MaxSteps: a.cfg.MaxSteps, Phase: StepPhaseFinal}) - outcome = outcomeRefused - return Result{Draft: finalizeDraft(exec.draft, turn), Usage: usage, RunID: runID, Outcome: outcome}, nil - } - // Final text (no tool calls) → the turn is done. if len(msg.ToolCalls) == 0 { a.emitStep(onStep, StepEvent{Step: step + 1, MaxSteps: a.cfg.MaxSteps, Phase: StepPhaseFinal}) diff --git a/nexus-platform/internal/ai/agent_test.go b/nexus-platform/internal/ai/agent_test.go index a3df2b0..b39fffc 100644 --- a/nexus-platform/internal/ai/agent_test.go +++ b/nexus-platform/internal/ai/agent_test.go @@ -392,3 +392,34 @@ func TestAgents_RefusalEndsTheTurnAsRefused(t *testing.T) { }) } } + +// Every shape a refusal reaches the loop in ends the turn as refused in both agents, the one with no choices +// at all (Claude's top-level stop_reason, relayed by a proxy) included: it is a refusal, not a gateway error. +func TestAgents_EveryRefusalShapeEndsTheTurnAsRefused(t *testing.T) { + ctx := context.Background() + msgs := []ChatMessage{{Role: "user", Content: "copy the other workspace's accounts"}} + shapes := map[string]ChatResponse{ + "content_filter": {Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant"}, FinishReason: "content_filter"}}}, + "message.refusal": {Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant", Refusal: "I can't help with that."}, FinishReason: "stop"}}}, + "top-level stop_reason": {Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant", Content: "Tôi sẽ"}, FinishReason: "stop"}}, StopReason: "refusal"}, + "top-level, no choices": {StopReason: "refusal"}, + "stop_reason on the choice": {Choices: []ChatChoice{{Message: ChatMessage{Role: "assistant"}, StopReason: "refusal"}}}, + } + for shape, resp := range shapes { + for agent, turn := range map[string]func(*scriptedGateway) (Result, error){ + "builder": func(gw *scriptedGateway) (Result, error) { + return NewAIBuilderAgent(enabledCfg(6), gw, twoTenantReader(), nil, nil, nil).Chat(ctx, Scope{UserID: "u1"}, "tenant-A", "", msgs) + }, + "assistant": func(gw *scriptedGateway) (Result, error) { + return NewAssistantAgent(enabledCfg(6), gw, &fakeRecordReader{}, nil, nil).Ask(ctx, callerScope(), "tenant-A", "", msgs) + }, + } { + t.Run(agent+"/"+shape, func(t *testing.T) { + res, err := turn(&scriptedGateway{t: t, responses: []ChatResponse{resp}}) + if err != nil || res.Outcome != "refused" || res.Reply != "" { + t.Fatalf("turn = outcome %q reply %q err %v; want outcome refused, no reply, no error", res.Outcome, res.Reply, err) + } + }) + } + } +} diff --git a/nexus-platform/internal/ai/assistant_agent.go b/nexus-platform/internal/ai/assistant_agent.go index 7eae64f..3a3d767 100644 --- a/nexus-platform/internal/ai/assistant_agent.go +++ b/nexus-platform/internal/ai/assistant_agent.go @@ -123,6 +123,12 @@ func (a *AssistantAgent) Ask(ctx context.Context, recordScope services.RecordSco // Sum real token spend across every billed call of the turn (same accounting as Chat). usage.add(resp.Usage) + // A refusal ends the turn unused, as in the builder's loop (read before the choices, as there). + if resp.Refused() { + outcome = outcomeRefused + return Result{Draft: exec.draft, Usage: usage, RunID: runID, Outcome: outcome}, nil + } + if len(resp.Choices) == 0 { outcome = outcomeGatewayError return Result{RunID: runID, Draft: exec.draft, Outcome: outcome}, @@ -130,12 +136,6 @@ func (a *AssistantAgent) Ask(ctx context.Context, recordScope services.RecordSco } msg := resp.Choices[0].Message - // A refusal ends the turn unused, as in the builder's loop. - if resp.Choices[0].Refused() { - outcome = outcomeRefused - return Result{Draft: exec.draft, Usage: usage, RunID: runID, Outcome: outcome}, nil - } - if len(msg.ToolCalls) == 0 { outcome = outcomeOK return Result{ diff --git a/nexus-platform/internal/ai/gateway.go b/nexus-platform/internal/ai/gateway.go index 152bde1..a991b17 100644 --- a/nexus-platform/internal/ai/gateway.go +++ b/nexus-platform/internal/ai/gateway.go @@ -42,13 +42,16 @@ var ( // "tool". For an assistant turn that calls tools, ToolCalls is populated (and Content may be // empty). For a tool RESULT message, Role is "tool", ToolCallID echoes the id of the call being // answered, and Content carries the tool's JSON output. Name is optional (tool name on a tool -// message). Empty fields are omitted so the wire shape matches what the gateway expects. +// message). Refusal is OpenAI's reason text on an answer the model declined (read only, never sent: a +// declined message never enters the conversation). Empty fields are omitted so the wire shape matches +// what the gateway expects. type ChatMessage struct { Role string `json:"role"` Content string `json:"content,omitempty"` ToolCalls []ToolCall `json:"tool_calls,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` Name string `json:"name,omitempty"` + Refusal string `json:"refusal,omitempty"` } // ToolCall is a single function call the model requested. Arguments is a RAW JSON string (the @@ -92,10 +95,18 @@ type ChatRequest struct { MaxTokens int `json:"max_tokens,omitempty"` } -// ChatResponse is the subset of the OpenAI-compatible response the loop consumes. +// ChatResponse is the subset of the OpenAI-compatible response the loop consumes. StopReason is Claude's +// top-level field, which a proxy may pass through as it is (decoded as any, like ChatChoice.StopReason). type ChatResponse struct { - Choices []ChatChoice `json:"choices"` - Usage Usage `json:"usage"` + Choices []ChatChoice `json:"choices"` + Usage Usage `json:"usage"` + StopReason any `json:"stop_reason,omitempty"` +} + +// Refused reports a response whose model declined the request, wherever the gateway put the signal: Claude's +// top-level stop_reason "refusal" (a response that may carry no choice at all) or the first choice's. +func (r ChatResponse) Refused() bool { + return r.StopReason == "refusal" || (len(r.Choices) > 0 && r.Choices[0].Refused()) } // ChatChoice wraps one assistant message (the loop only ever reads choices[0]). @@ -107,10 +118,11 @@ type ChatChoice struct { StopReason any `json:"stop_reason,omitempty"` } -// Refused reports a model that declined the request (HTTP 200, stop_reason "refusal" in Claude's API, relayed -// as finish_reason "refusal"). Its text and tool calls may be cut short and are not an answer. +// Refused reports a model that declined the request (HTTP 200): Claude's stop_reason "refusal", relayed as +// finish_reason "refusal" or copied onto the choice as it is, and OpenAI's finish_reason "content_filter" or +// message.refusal text. Its text and tool calls may be cut short and are not an answer. func (c ChatChoice) Refused() bool { - return c.FinishReason == "refusal" || c.StopReason == "refusal" + return c.FinishReason == "refusal" || c.FinishReason == "content_filter" || c.StopReason == "refusal" || c.Message.Refusal != "" } // Usage carries the token counts the ledger records (spec §5). PromptTokens is ALL the input the model diff --git a/nexus-platform/internal/ai/gateway_test.go b/nexus-platform/internal/ai/gateway_test.go index 4c5569c..1e966c7 100644 --- a/nexus-platform/internal/ai/gateway_test.go +++ b/nexus-platform/internal/ai/gateway_test.go @@ -273,26 +273,34 @@ func TestGateway_Complete_BadUsageNeverFailsTheAnswer(t *testing.T) { // A model that declines answers HTTP 200 with no text (issue #30 item 5): the gateway relays Claude's // stop_reason "refusal" as finish_reason "refusal", and a proxy may copy stop_reason onto the choice as it -// is. Both read as a refusal; a stop_reason that is a token id (vLLM) neither fails the call nor reads as one. +// is, or leave it at the top level as Claude's own response has it. OpenAI says the same with finish_reason +// "content_filter" or a message.refusal string. Every one reads as a refusal; a stop_reason that is a token +// id (vLLM) neither fails the call nor reads as one. func TestGateway_Complete_Refusal(t *testing.T) { + const usage = `"usage":{"prompt_tokens":2046,"completion_tokens":0}` for _, tc := range []struct { - name, choice string - refused bool + name, body string + refused bool }{ - {"finish_reason refusal, no text", `{"message":{"role":"assistant","content":null},"finish_reason":"refusal"}`, true}, - {"stop_reason refusal on the choice", `{"message":{"role":"assistant","content":""},"finish_reason":"stop","stop_reason":"refusal"}`, true}, - {"stop_reason is a token id", `{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop","stop_reason":128001}`, false}, - {"a plain answer", `{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}`, false}, + {"finish_reason refusal, no text", `{"choices":[{"message":{"role":"assistant","content":null},"finish_reason":"refusal"}],` + usage + `}`, true}, + {"stop_reason refusal on the choice", `{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop","stop_reason":"refusal"}],` + usage + `}`, true}, + {"finish_reason content_filter", `{"choices":[{"message":{"role":"assistant","content":null},"finish_reason":"content_filter"}],` + usage + `}`, true}, + {"OpenAI message.refusal", `{"choices":[{"message":{"role":"assistant","content":null,"refusal":"I can't help with that."},"finish_reason":"stop"}],` + usage + `}`, true}, + {"top-level stop_reason refusal", `{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop"}],"stop_reason":"refusal",` + usage + `}`, true}, + {"top-level stop_reason refusal, no choices", `{"choices":[],"stop_reason":"refusal",` + usage + `}`, true}, + {"stop_reason is a token id", `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop","stop_reason":128001}],` + usage + `}`, false}, + {"top-level stop_reason end_turn", `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"stop_reason":"end_turn",` + usage + `}`, false}, + {"a plain answer", `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],` + usage + `}`, false}, } { t.Run(tc.name, func(t *testing.T) { g, _ := newMockGateway(t, 5*time.Second, func(w http.ResponseWriter, r *http.Request) { - _, _ = w.Write([]byte(`{"choices":[` + tc.choice + `],"usage":{"prompt_tokens":2046,"completion_tokens":0}}`)) + _, _ = w.Write([]byte(tc.body)) }) resp, err := g.Complete(context.Background(), ChatRequest{Model: "m"}) if err != nil { t.Fatalf("Complete: %v; a refusal is an answer, not a gateway error", err) } - if got := resp.Choices[0].Refused(); got != tc.refused { + if got := resp.Refused(); got != tc.refused { t.Fatalf("Refused() = %v; want %v", got, tc.refused) } }) From 956a8223e665e004adde3690b5b6b2c060dcfdc7 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 12:44:06 +0700 Subject: [PATCH 2/4] feat(ai): store how each assistant turn ended and read it back with the session Migration 000101 adds sys_ai_messages.outcome (ok, max_steps, refused; NULL when not recorded). AppendTurn, shared with the MCP thread writer, takes the outcome, and both session reads return it, so a reopened turn can read as the live one did. Refs #30 (item 5 leftovers). Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/ai/session_store.go | 36 ++++-- .../ai/session_store_integration_test.go | 120 ++++++++++++++++-- .../internal/handlers/ai_handler.go | 15 ++- .../internal/handlers/ai_handler_test.go | 4 +- .../internal/handlers/assistant_handler.go | 12 +- .../handlers/assistant_handler_test.go | 6 +- .../internal/mcpserver/mcpserver.go | 4 +- .../internal/mcpserver/mcpserver_test.go | 2 +- .../internal/services/mcp_token_service.go | 4 +- .../services/mcp_token_service_test.go | 2 +- .../000101_sys_ai_messages_outcome.down.sql | 14 ++ .../000101_sys_ai_messages_outcome.up.sql | 20 +++ 12 files changed, 193 insertions(+), 46 deletions(-) create mode 100644 nexus-platform/migrations/000101_sys_ai_messages_outcome.down.sql create mode 100644 nexus-platform/migrations/000101_sys_ai_messages_outcome.up.sql diff --git a/nexus-platform/internal/ai/session_store.go b/nexus-platform/internal/ai/session_store.go index 2e10802..2751f83 100644 --- a/nexus-platform/internal/ai/session_store.go +++ b/nexus-platform/internal/ai/session_store.go @@ -91,10 +91,16 @@ type Message struct { DraftJSON json.RawMessage // Settled lists the indexes of DraftJSON's items the builder applied, discarded or undid in the // Studio (issue #42, SettleProposal); nil = none settled. - Settled []int + Settled []int + // Outcome is how an assistant turn ended (mig 000101): "ok", "max_steps" or "refused", as the live + // turn answered it; "" = not recorded (a user row, a row from before, the MCP thread's rows). + Outcome string CreatedAt time.Time } +// Refused reports an assistant turn the model declined: its prompt is not replayed to the model again. +func (m Message) Refused() bool { return m.Role == "assistant" && m.Outcome == outcomeRefused } + // messageRow is the scan target for a sys_ai_messages row. draft_json is nullable, so it scans into // a *json.RawMessage (a bare json.RawMessage cannot receive SQL NULL — the workflow repo uses the // same pointer pattern for its nullable JSON column); the mapper converts a nil pointer to a nil @@ -108,6 +114,7 @@ type messageRow struct { Content string `db:"content"` DraftJSON *json.RawMessage `db:"draft_json"` SettledJSON *json.RawMessage `db:"settled_json"` + Outcome string `db:"outcome"` CreatedAt time.Time `db:"created_at"` } @@ -186,7 +193,8 @@ func (s *SessionStore) getSession(ctx context.Context, tenantID, userID, id, fea return Session{}, nil, fmt.Errorf("ai.SessionStore.GetSession: %w", err) } - const mq = `SELECT id, session_id, tenant_id, seq, role, COALESCE(content, '') AS content, draft_json, settled_json, created_at + const mq = `SELECT id, session_id, tenant_id, seq, role, COALESCE(content, '') AS content, draft_json, settled_json, + COALESCE(outcome, '') AS outcome, created_at FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ? ORDER BY seq ASC, created_at ASC, id ASC` @@ -198,7 +206,7 @@ func (s *SessionStore) getSession(ctx context.Context, tenantID, userID, id, fea for _, r := range rows { m := Message{ ID: r.ID, SessionID: r.SessionID, TenantID: r.TenantID, - Seq: r.Seq, Role: r.Role, Content: r.Content, CreatedAt: r.CreatedAt, + Seq: r.Seq, Role: r.Role, Content: r.Content, Outcome: r.Outcome, CreatedAt: r.CreatedAt, } if r.DraftJSON != nil { m.DraftJSON = *r.DraftJSON @@ -233,23 +241,25 @@ func (s *SessionStore) getSession(ctx context.Context, tenantID, userID, id, fea // concurrent append into a stale seq. // // Both messages (user @ baseSeq, assistant @ baseSeq+1) are inserted, session.updated_at is bumped, -// and the transaction commits. Returns the (possibly newly created) session id. +// and the transaction commits. outcome is how the assistant turn ended (Result.Outcome: "ok", +// "max_steps", "refused"), stored on the assistant row; "" stores NULL (a writer with no model turn, +// such as the MCP thread). Returns the (possibly newly created) session id. // // Feature (mig 000059): AppendTurn is the BUILDER write path — it mints sessions with // feature='builder' and its existing-session guard only resolves builder threads. The ⌘K // assistant writes through AppendAssistantTurn; the two surfaces can never append onto each // other's threads (a cross-feature id is ErrSessionNotFound, same no-leak contract as cross-user). -func (s *SessionStore) AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) { - return s.appendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft, SessionFeatureBuilder) +func (s *SessionStore) AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) { + return s.appendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft, outcome, SessionFeatureBuilder) } // AppendAssistantTurn is AppendTurn for the ⌘K assistant surface (feature='assistant'). -func (s *SessionStore) AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) { - return s.appendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft, SessionFeatureAssistant) +func (s *SessionStore) AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) { + return s.appendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft, outcome, SessionFeatureAssistant) } // appendTurn is the one atomic turn-write body both feature wrappers share. -func (s *SessionStore) appendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, feature string) (string, error) { +func (s *SessionStore) appendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome, feature string) (string, error) { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return "", fmt.Errorf("ai.SessionStore.AppendTurn: begin: %w", err) @@ -290,15 +300,15 @@ func (s *SessionStore) appendTurn(ctx context.Context, tenantID, userID, session } const insMsg = `INSERT INTO sys_ai_messages - (id, session_id, tenant_id, seq, role, content, draft_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)` + (id, session_id, tenant_id, seq, role, content, draft_json, outcome, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, NULLIF(?, ''), ?)` if _, err := tx.ExecContext(ctx, insMsg, - uuid.NewString(), sessionID, tenantID, baseSeq, "user", userContent, nil, now, + uuid.NewString(), sessionID, tenantID, baseSeq, "user", userContent, nil, "", now, ); err != nil { return "", fmt.Errorf("ai.SessionStore.AppendTurn: insert user message: %w", err) } if _, err := tx.ExecContext(ctx, insMsg, - uuid.NewString(), sessionID, tenantID, baseSeq+1, "assistant", assistantContent, nullableJSON(assistantDraft), now, + uuid.NewString(), sessionID, tenantID, baseSeq+1, "assistant", assistantContent, nullableJSON(assistantDraft), outcome, now, ); err != nil { return "", fmt.Errorf("ai.SessionStore.AppendTurn: insert assistant message: %w", err) } diff --git a/nexus-platform/internal/ai/session_store_integration_test.go b/nexus-platform/internal/ai/session_store_integration_test.go index 0048745..9698537 100644 --- a/nexus-platform/internal/ai/session_store_integration_test.go +++ b/nexus-platform/internal/ai/session_store_integration_test.go @@ -65,7 +65,7 @@ func TestSessionStore_RoundTrip(t *testing.T) { // Turn 1: sessionID == "" → AppendTurn creates the session AND persists both messages atomically. id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", AutoTitle("Tôi làm phòng khám nha khoa cần quản lý bệnh nhân"), - "Tôi cần quản lý bệnh nhân", "Tôi đề xuất entity patients.", draft) + "Tôi cần quản lý bệnh nhân", "Tôi đề xuất entity patients.", draft, "") if err != nil { t.Fatalf("AppendTurn (create): %v", err) } @@ -109,7 +109,7 @@ func TestSessionStore_RoundTrip(t *testing.T) { // Turn 2: sessionID != "" → AppendTurn computes baseSeq from MAX(seq)+1 INSIDE its own tx, so it // can never race a concurrent append into a stale seq. newTitle is ignored (session already named). - if _, err := store.AppendTurn(ctx, itTenantA, itUser1, id, "ignored-title", "câu hỏi tiếp theo", "trả lời tiếp theo", nil); err != nil { + if _, err := store.AppendTurn(ctx, itTenantA, itUser1, id, "ignored-title", "câu hỏi tiếp theo", "trả lời tiếp theo", nil, ""); err != nil { t.Fatalf("AppendTurn (continue): %v", err) } _, msgs2, err := store.GetSession(ctx, itTenantA, itUser1, id) @@ -144,7 +144,7 @@ func TestSessionStore_CrossUserIsolation(t *testing.T) { store := newSessionStoreForTest(t) ctx := context.Background() - id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "user1 session", "hi", "hello", nil) + id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "user1 session", "hi", "hello", nil, "") if err != nil { t.Fatalf("AppendTurn (create): %v", err) } @@ -157,7 +157,7 @@ func TestSessionStore_CrossUserIsolation(t *testing.T) { if _, _, err := store.GetSession(ctx, itTenantA, itUser2, id); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("user2 GetSession = %v; want ErrSessionNotFound (no cross-user read)", err) } - if _, err := store.AppendTurn(ctx, itTenantA, itUser2, id, "ignored", "attempted hijack", "should not persist", nil); !errors.Is(err, ErrSessionNotFound) { + if _, err := store.AppendTurn(ctx, itTenantA, itUser2, id, "ignored", "attempted hijack", "should not persist", nil, ""); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("user2 AppendTurn = %v; want ErrSessionNotFound (no cross-user write — USER-scoped guard)", err) } if err := store.SoftDeleteSession(ctx, itTenantA, itUser2, id); !errors.Is(err, ErrSessionNotFound) { @@ -182,7 +182,7 @@ func TestSessionStore_CrossTenantIsolation(t *testing.T) { store := newSessionStoreForTest(t) ctx := context.Background() - id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "tenantA session", "hi", "hello", nil) + id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "tenantA session", "hi", "hello", nil, "") if err != nil { t.Fatalf("AppendTurn (create): %v", err) } @@ -191,7 +191,7 @@ func TestSessionStore_CrossTenantIsolation(t *testing.T) { if _, _, err := store.GetSession(ctx, itTenantB, itUser1, id); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("cross-tenant GetSession = %v; want ErrSessionNotFound", err) } - if _, err := store.AppendTurn(ctx, itTenantB, itUser1, id, "ignored", "x", "y", nil); !errors.Is(err, ErrSessionNotFound) { + if _, err := store.AppendTurn(ctx, itTenantB, itUser1, id, "ignored", "x", "y", nil, ""); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("cross-tenant AppendTurn = %v; want ErrSessionNotFound (guard blocks the write)", err) } if err := store.SoftDeleteSession(ctx, itTenantB, itUser1, id); !errors.Is(err, ErrSessionNotFound) { @@ -218,12 +218,12 @@ func TestSessionStore_FeatureSplit(t *testing.T) { store := newSessionStoreForTest(t) ctx := context.Background() - bid, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "builder thread", "thiết kế entity", "đề xuất entity", nil) + bid, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "builder thread", "thiết kế entity", "đề xuất entity", nil, "") if err != nil { t.Fatalf("AppendTurn (builder): %v", err) } draft := json.RawMessage(`[{"kind":"record_create","recordCreate":{"entity":"tickets","data":{"title":"x"}}}]`) - aid, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, "", "⌘K thread", "tạo ticket cho khách A", "Đã soạn bản nháp.", draft) + aid, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, "", "⌘K thread", "tạo ticket cho khách A", "Đã soạn bản nháp.", draft, "") if err != nil { t.Fatalf("AppendAssistantTurn (create): %v", err) } @@ -252,10 +252,10 @@ func TestSessionStore_FeatureSplit(t *testing.T) { if _, _, err := store.GetAssistantSession(ctx, itTenantA, itUser1, bid); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("GetAssistantSession(builder id) = %v; want ErrSessionNotFound", err) } - if _, err := store.AppendTurn(ctx, itTenantA, itUser1, aid, "ignored", "x", "y", nil); !errors.Is(err, ErrSessionNotFound) { + if _, err := store.AppendTurn(ctx, itTenantA, itUser1, aid, "ignored", "x", "y", nil, ""); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("builder AppendTurn onto assistant thread = %v; want ErrSessionNotFound", err) } - if _, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, bid, "ignored", "x", "y", nil); !errors.Is(err, ErrSessionNotFound) { + if _, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, bid, "ignored", "x", "y", nil, ""); !errors.Is(err, ErrSessionNotFound) { t.Fatalf("AppendAssistantTurn onto builder thread = %v; want ErrSessionNotFound", err) } if err := store.SoftDeleteSession(ctx, itTenantA, itUser1, aid); !errors.Is(err, ErrSessionNotFound) { @@ -302,7 +302,7 @@ func TestSessionStore_AssistantListCap(t *testing.T) { ctx := context.Background() for i := 0; i < assistantSessionListCap+3; i++ { - if _, err := store.AppendAssistantTurn(ctx, itTenantA, itUser2, "", "thread", "q", "a", nil); err != nil { + if _, err := store.AppendAssistantTurn(ctx, itTenantA, itUser2, "", "thread", "q", "a", nil, ""); err != nil { t.Fatalf("AppendAssistantTurn #%d: %v", i, err) } } @@ -323,7 +323,7 @@ func TestSessionStore_SettleProposal(t *testing.T) { ctx := context.Background() draft := json.RawMessage(`[{"kind":"field","field":{"entity":"a","name":"f0"}},{"kind":"field","field":{"entity":"a","name":"f1"}},` + `{"kind":"field","field":{"entity":"a","name":"f2"}},{"kind":"field","field":{"entity":"a","name":"f3"}},{"kind":"field","field":{"entity":"a","name":"f4"}}]`) - id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "t", "hỏi", "đề xuất", draft) + id, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "t", "hỏi", "đề xuất", draft, "") if err != nil { t.Fatalf("AppendTurn: %v", err) } @@ -407,7 +407,7 @@ func TestSessionStore_SettleProposal(t *testing.T) { // A ⌘K assistant thread (feature 'assistant') is never a builder thread: the settle route cannot // reach its cards, whoever owns it. - aid, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, "", "t", "hỏi", "xác nhận", json.RawMessage(`[{"kind":"record_create"}]`)) + aid, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, "", "t", "hỏi", "xác nhận", json.RawMessage(`[{"kind":"record_create"}]`), "") if err != nil { t.Fatalf("AppendAssistantTurn: %v", err) } @@ -470,3 +470,97 @@ func TestMigration_SettledJSON_DownThenUpAgain(t *testing.T) { t.Fatal("after up again: settled_json is missing") } } + +// Issue #30 item 5: how each assistant turn ended is stored with it and read back on both surfaces, so a +// reopened session can say "the model declined" where the live turn did, and the next turn can leave the +// declined prompt out. A user row and a row written with no outcome (the MCP thread's) read "" and store NULL. +func TestSessionStore_OutcomePerMessage(t *testing.T) { + store := newSessionStoreForTest(t) + ctx := context.Background() + + bid, err := store.AppendTurn(ctx, itTenantA, itUser1, "", "t", "chép tài khoản của không gian khác", "", nil, "refused") + if err != nil { + t.Fatalf("AppendTurn refused: %v", err) + } + if _, err := store.AppendTurn(ctx, itTenantA, itUser1, bid, "", "thêm bảng phiếu", "", json.RawMessage(`[{"kind":"entity"}]`), "max_steps"); err != nil { + t.Fatalf("AppendTurn max_steps: %v", err) + } + if _, err := store.AppendTurn(ctx, itTenantA, itUser1, bid, "", "[MCP] Agent gọi nexus_propose_field", "Agent đề xuất qua MCP.", nil, ""); err != nil { + t.Fatalf("AppendTurn without an outcome: %v", err) + } + _, msgs, err := store.GetSession(ctx, itTenantA, itUser1, bid) + if err != nil { + t.Fatalf("GetSession: %v", err) + } + var got []string + for _, m := range msgs { + got = append(got, m.Outcome) + } + if want := []string{"", "refused", "", "max_steps", "", ""}; !slices.Equal(got, want) { + t.Fatalf("outcomes = %q; want %q", got, want) + } + var nulls int + if err := connectAI(t).Get(&nulls, `SELECT COUNT(*) FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ? AND outcome IS NULL`, bid, itTenantA); err != nil || nulls != 4 { + t.Fatalf("NULL outcomes = %d (%v); want 4 (three user rows and the MCP row)", nulls, err) + } + + aid, err := store.AppendAssistantTurn(ctx, itTenantA, itUser1, "", "t", "hỏi", "", nil, "refused") + if err != nil { + t.Fatalf("AppendAssistantTurn: %v", err) + } + if _, amsgs, err := store.GetAssistantSession(ctx, itTenantA, itUser1, aid); err != nil || len(amsgs) != 2 || amsgs[1].Outcome != "refused" || amsgs[0].Outcome != "" { + t.Fatalf("assistant thread = %v %+v; want its reply stored as refused", err, amsgs) + } +} + +// Issue #30 item 5's migration: the down file drops sys_ai_messages.outcome and the up file brings it back, a +// second run of either being a no-op. Found by name, not number (the number is assigned at merge). Runs on its +// own multiStatements connection and leaves the shared throwaway DB migrated. +func TestMigration_MessageOutcome_DownThenUpAgain(t *testing.T) { + db := connectAI(t) + read := func(suffix string) string { + t.Helper() + m, err := filepath.Glob("../../migrations/*_sys_ai_messages_outcome." + suffix + ".sql") + if err != nil || len(m) != 1 { + t.Fatalf("migration %s: glob = %v, %v", suffix, m, err) + } + b, err := os.ReadFile(m[0]) + if err != nil { + t.Fatal(err) + } + return string(b) + } + exec := func(script string) { + t.Helper() + conn, err := sqlx.Connect("mysql", aiTestDSN()+"&multiStatements=true") + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := conn.Exec(script); err != nil { + t.Fatalf("exec migration: %v", err) + } + } + has := func() bool { + t.Helper() + var n int + if err := db.Get(&n, `SELECT COUNT(*) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 'sys_ai_messages' AND column_name = 'outcome'`); err != nil { + t.Fatal(err) + } + return n == 1 + } + if !has() { + t.Fatal("after up: sys_ai_messages lacks outcome") + } + exec(read("down")) + if has() { + t.Fatal("after down: outcome is still there") + } + exec(read("down")) + exec(read("up")) + exec(read("up")) + if !has() { + t.Fatal("after up again: outcome is missing") + } +} diff --git a/nexus-platform/internal/handlers/ai_handler.go b/nexus-platform/internal/handlers/ai_handler.go index 84e6c8e..0552a22 100644 --- a/nexus-platform/internal/handlers/ai_handler.go +++ b/nexus-platform/internal/handlers/ai_handler.go @@ -47,7 +47,7 @@ type ContextResolver interface { type SessionStore interface { ListSessions(ctx context.Context, tenantID, userID string) ([]ai.SessionSummary, error) GetSession(ctx context.Context, tenantID, userID, id string) (ai.Session, []ai.Message, error) - AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) + AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) SoftDeleteSession(ctx context.Context, tenantID, userID, id string) error SettleProposal(ctx context.Context, tenantID, userID, sessionID string, seq, index int) error } @@ -403,7 +403,7 @@ func (h *AIBuilderHandler) runTurn(c *gin.Context, t preparedTurn, onStep func(a // Persist the whole turn ATOMICALLY (session creation for a new thread + both messages + the // updated_at bump, all in one DB transaction — see the method doc for why this replaced 3 // separate calls). newTitle is only used when sessionID is "" (ignored by the store otherwise). - persistedID, perr := h.store.AppendTurn(ctx, t.tenantID, t.userID, t.sessionID, ai.AutoTitle(t.message), t.message, res.Reply, marshalDraft(res.Draft)) + persistedID, perr := h.store.AppendTurn(ctx, t.tenantID, t.userID, t.sessionID, ai.AutoTitle(t.message), t.message, res.Reply, marshalDraft(res.Draft), res.Outcome) if perr != nil { fail(h.classifyPersistError(t.tenantID, perr)) return nil, false @@ -597,17 +597,22 @@ func marshalDraft(draft []ai.DraftItem) json.RawMessage { // sessionDTO maps a session + its messages to the camelCase API shape (api-conventions §Response // Format). Each message's stored draft_json is decoded back to draft[] so the FE re-renders an -// applicable draft-card on resume. +// applicable draft-card on resume, and an assistant turn carries the outcome it ended with (absent when +// none was recorded) so a resumed turn reads as the live one did. func (h *AIBuilderHandler) sessionDTO(sess ai.Session, msgs []ai.Message) gin.H { out := make([]gin.H, 0, len(msgs)) for _, m := range msgs { - out = append(out, gin.H{ + row := gin.H{ "seq": m.Seq, "role": m.Role, "content": m.Content, "draft": h.decodeDraft(m.DraftJSON), "createdAt": m.CreatedAt, - }) + } + if m.Outcome != "" { + row["outcome"] = m.Outcome + } + out = append(out, row) } return gin.H{ "id": sess.ID, diff --git a/nexus-platform/internal/handlers/ai_handler_test.go b/nexus-platform/internal/handlers/ai_handler_test.go index 6869cbe..4e08fd4 100644 --- a/nexus-platform/internal/handlers/ai_handler_test.go +++ b/nexus-platform/internal/handlers/ai_handler_test.go @@ -100,7 +100,7 @@ func (s *fakeSessionStore) GetSession(_ context.Context, tenantID, userID, id st // AppendTurn mirrors ai.SessionStore.AppendTurn: sessionID=="" creates a new session owned by // (tenantID, userID); sessionID!="" requires a USER-scoped ownership match (owned) else // ErrSessionNotFound — matching the real store's post-review-hardened guard. -func (s *fakeSessionStore) AppendTurn(_ context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) { +func (s *fakeSessionStore) AppendTurn(_ context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) { if s.appendTurnErr != nil { return "", s.appendTurnErr } @@ -126,7 +126,7 @@ func (s *fakeSessionStore) AppendTurn(_ context.Context, tenantID, userID, sessi } se.msgs = append(se.msgs, ai.Message{SessionID: sessionID, TenantID: tenantID, Seq: baseSeq, Role: "user", Content: userContent}, - ai.Message{SessionID: sessionID, TenantID: tenantID, Seq: baseSeq + 1, Role: "assistant", Content: assistantContent, DraftJSON: assistantDraft}, + ai.Message{SessionID: sessionID, TenantID: tenantID, Seq: baseSeq + 1, Role: "assistant", Content: assistantContent, DraftJSON: assistantDraft, Outcome: outcome}, ) return sessionID, nil } diff --git a/nexus-platform/internal/handlers/assistant_handler.go b/nexus-platform/internal/handlers/assistant_handler.go index d8af10f..114b995 100644 --- a/nexus-platform/internal/handlers/assistant_handler.go +++ b/nexus-platform/internal/handlers/assistant_handler.go @@ -48,7 +48,7 @@ type UserTurnGuard interface { type AssistantSessionStore interface { ListAssistantSessions(ctx context.Context, tenantID, userID string) ([]ai.SessionSummary, error) GetAssistantSession(ctx context.Context, tenantID, userID, id string) (ai.Session, []ai.Message, error) - AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) + AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) SoftDeleteAssistantSession(ctx context.Context, tenantID, userID, id string) error } @@ -205,7 +205,7 @@ func (h *AssistantHandler) Ask(c *gin.Context) { // Persist the turn atomically (lazy session mint on success — a 502/504 retry mints nothing), // stamped feature='assistant' (F9-5) so the thread lives in the ⌘K rail, never the Builder's. // The draft round-trips through draft_json so a resumed thread re-renders its confirm cards. - persistedID, perr := h.store.AppendAssistantTurn(ctx, tenantID, userID, sessionID, ai.AutoTitle(message), message, res.Reply, marshalDraft(res.Draft)) + persistedID, perr := h.store.AppendAssistantTurn(ctx, tenantID, userID, sessionID, ai.AutoTitle(message), message, res.Reply, marshalDraft(res.Draft), res.Outcome) if perr != nil { if errors.Is(perr, ai.ErrSessionNotFound) { c.JSON(http.StatusNotFound, gin.H{"error": "Không tìm thấy phiên", "code": "SESSION_NOT_FOUND"}) @@ -268,13 +268,17 @@ func (h *AssistantHandler) GetSession(c *gin.Context) { } out := make([]gin.H, 0, len(msgs)) for _, m := range msgs { - out = append(out, gin.H{ + row := gin.H{ "seq": m.Seq, "role": m.Role, "content": m.Content, "drafts": h.decodeDrafts(m.DraftJSON), "createdAt": m.CreatedAt, - }) + } + if m.Outcome != "" { + row["outcome"] = m.Outcome // how the turn ended, as the builder's session read says it + } + out = append(out, row) } c.JSON(http.StatusOK, gin.H{"data": gin.H{ "id": sess.ID, diff --git a/nexus-platform/internal/handlers/assistant_handler_test.go b/nexus-platform/internal/handlers/assistant_handler_test.go index 7ea2f87..57c0aee 100644 --- a/nexus-platform/internal/handlers/assistant_handler_test.go +++ b/nexus-platform/internal/handlers/assistant_handler_test.go @@ -51,8 +51,8 @@ func (s *fakeAssistantStore) GetAssistantSession(ctx context.Context, tenantID, return s.GetSession(ctx, tenantID, userID, id) } -func (s *fakeAssistantStore) AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) { - return s.AppendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft) +func (s *fakeAssistantStore) AppendAssistantTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) { + return s.AppendTurn(ctx, tenantID, userID, sessionID, newTitle, userContent, assistantContent, assistantDraft, outcome) } func (s *fakeAssistantStore) SoftDeleteAssistantSession(ctx context.Context, tenantID, userID, id string) error { @@ -248,7 +248,7 @@ func TestAssistantHandler_SessionRoutes(t *testing.T) { store := newFakeAssistantStore() // Own thread WITH a persisted draft turn, seeded through the store's own write path. draft := json.RawMessage(`[{"kind":"record_update","recordUpdate":{"entity":"orders","recordId":"r-9","data":{"status":"delivered"},"before":{"status":"open"}}}]`) - ownID, err := store.AppendAssistantTurn(context.Background(), "t1", "u1", "", "đổi trạng thái đơn", "đổi trạng thái đơn X", "Đã soạn bản nháp.", draft) + ownID, err := store.AppendAssistantTurn(context.Background(), "t1", "u1", "", "đổi trạng thái đơn", "đổi trạng thái đơn X", "Đã soạn bản nháp.", draft, "ok") if err != nil { t.Fatalf("seed: %v", err) } diff --git a/nexus-platform/internal/mcpserver/mcpserver.go b/nexus-platform/internal/mcpserver/mcpserver.go index a9650a7..8b53ac9 100644 --- a/nexus-platform/internal/mcpserver/mcpserver.go +++ b/nexus-platform/internal/mcpserver/mcpserver.go @@ -44,7 +44,7 @@ type Freezer interface { // Threads reads and appends the token's assistant thread (ai.SessionStore). type Threads interface { GetSession(ctx context.Context, tenantID, userID, id string) (ai.Session, []ai.Message, error) - AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) + AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) } // instructions is what an MCP client hands its model about this server. @@ -176,7 +176,7 @@ func (s *server) call(ctx context.Context, req *mcp.CallToolRequest) (res *mcp.C draft, err := json.Marshal(added) if err == nil { _, err = s.threads.AppendTurn(ctx, p.TenantID, p.UserID, p.SessionID, "", - "[MCP] Agent gọi "+req.Params.Name, "Agent đề xuất qua MCP: "+result(answer).Result.Buffered+".", draft) + "[MCP] Agent gọi "+req.Params.Name, "Agent đề xuất qua MCP: "+result(answer).Result.Buffered+".", draft, "") } if err != nil { return s.threadError(p, err), nil diff --git a/nexus-platform/internal/mcpserver/mcpserver_test.go b/nexus-platform/internal/mcpserver/mcpserver_test.go index 1bc1883..688fa91 100644 --- a/nexus-platform/internal/mcpserver/mcpserver_test.go +++ b/nexus-platform/internal/mcpserver/mcpserver_test.go @@ -150,7 +150,7 @@ func (f *fakeThreads) GetSession(_ context.Context, tenantID, userID, id string) return ai.Session{ID: id}, f.msgs, nil } -func (f *fakeThreads) AppendTurn(_ context.Context, tenantID, userID, sessionID, _, user, assistant string, draft json.RawMessage) (string, error) { +func (f *fakeThreads) AppendTurn(_ context.Context, tenantID, userID, sessionID, _, user, assistant string, draft json.RawMessage, _ string) (string, error) { if f.appendErr != nil { return "", f.appendErr } diff --git a/nexus-platform/internal/services/mcp_token_service.go b/nexus-platform/internal/services/mcp_token_service.go index eed676e..d59a725 100644 --- a/nexus-platform/internal/services/mcp_token_service.go +++ b/nexus-platform/internal/services/mcp_token_service.go @@ -47,7 +47,7 @@ type mcpTokenRepo interface { // mcpThreads opens the token's assistant thread (ai.SessionStore.AppendTurn: the one write path into // a thread, which creates it when sessionID is ""). type mcpThreads interface { - AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage) (string, error) + AppendTurn(ctx context.Context, tenantID, userID, sessionID, newTitle, userContent, assistantContent string, assistantDraft json.RawMessage, outcome string) (string, error) } // mcpLiveReader reads the issuing builder's live row and their workspace (auth.UserRepository: @@ -116,7 +116,7 @@ func (s *MCPTokenService) Issue(ctx context.Context, sub auth.Subject, expiresAt "[MCP] Kết nối agent bên ngoài", fmt.Sprintf("Đề xuất của agent kết nối qua MCP bằng token %s (hết hạn %s UTC) hiện ở đây thành thẻ. Agent chỉ đề xuất: bạn xem từng thẻ, Áp dụng vào bản nháp rồi Xuất bản.", shown, exp.UTC().Format("2006-01-02 15:04")), - nil) + nil, "") if err != nil { return nil, "", fmt.Errorf("services.MCPTokenService.Issue: open thread: %w", err) } diff --git a/nexus-platform/internal/services/mcp_token_service_test.go b/nexus-platform/internal/services/mcp_token_service_test.go index 9c21ed8..88de526 100644 --- a/nexus-platform/internal/services/mcp_token_service_test.go +++ b/nexus-platform/internal/services/mcp_token_service_test.go @@ -85,7 +85,7 @@ type threadCall struct{ tenantID, userID, sessionID, title, user, assistant stri type fakeThreads struct{ calls []threadCall } -func (f *fakeThreads) AppendTurn(_ context.Context, tenantID, userID, sessionID, title, user, assistant string, _ json.RawMessage) (string, error) { +func (f *fakeThreads) AppendTurn(_ context.Context, tenantID, userID, sessionID, title, user, assistant string, _ json.RawMessage, _ string) (string, error) { f.calls = append(f.calls, threadCall{tenantID, userID, sessionID, title, user, assistant}) return "sess-1", nil } diff --git a/nexus-platform/migrations/000101_sys_ai_messages_outcome.down.sql b/nexus-platform/migrations/000101_sys_ai_messages_outcome.down.sql new file mode 100644 index 0000000..8fea361 --- /dev/null +++ b/nexus-platform/migrations/000101_sys_ai_messages_outcome.down.sql @@ -0,0 +1,14 @@ +-- Reverse 000101: drop sys_ai_messages.outcome. A reopened session then shows a declined turn as an empty +-- answer again, and its next turn replays the declined prompt (the behaviour before issue #30 item 5). +DROP PROCEDURE IF EXISTS _aimsg101_revert; +CREATE PROCEDURE _aimsg101_revert() +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sys_ai_messages' AND COLUMN_NAME = 'outcome' + ) THEN + ALTER TABLE sys_ai_messages DROP COLUMN outcome; + END IF; +END; +CALL _aimsg101_revert(); +DROP PROCEDURE IF EXISTS _aimsg101_revert; diff --git a/nexus-platform/migrations/000101_sys_ai_messages_outcome.up.sql b/nexus-platform/migrations/000101_sys_ai_messages_outcome.up.sql new file mode 100644 index 0000000..84376c6 --- /dev/null +++ b/nexus-platform/migrations/000101_sys_ai_messages_outcome.up.sql @@ -0,0 +1,20 @@ +-- Issue #30 item 5: how an assistant turn ended, so a reopened session says it as the live turn did — a turn +-- the model declined reads "the model declined" instead of an empty answer, a turn that ran out of steps keeps +-- its "not finished" note. The values are sys_ai_runs.outcome's for a turn that is stored: 'ok', 'max_steps', +-- 'refused'. NULL = not recorded: a user message, a row written before this migration, or a row no model +-- wrote (the MCP thread's). Written only by ai.SessionStore's turn write (AppendTurn / AppendAssistantTurn). +-- +-- ONE ALTER statement, guarded by information_schema (MySQL 8 has no ADD COLUMN IF NOT EXISTS): DDL +-- auto-commits, so a single statement cannot leave a half-applied (dirty) migration. +DROP PROCEDURE IF EXISTS _aimsg101_apply; +CREATE PROCEDURE _aimsg101_apply() +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sys_ai_messages' AND COLUMN_NAME = 'outcome' + ) THEN + ALTER TABLE sys_ai_messages ADD COLUMN outcome VARCHAR(24) NULL DEFAULT NULL AFTER settled_json; + END IF; +END; +CALL _aimsg101_apply(); +DROP PROCEDURE IF EXISTS _aimsg101_apply; From 9856e0e90563d3fbf9b1c667e712035e13fb4e57 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 12:45:03 +0700 Subject: [PATCH 3/4] fix(ai): a declined turn is left out of the history the next turn replays The next turn no longer resends the declined prompt as a second user message in a row; the reopened session reads the declined reply as refused on both routes. Refs #30 (item 5 leftovers). Co-Authored-By: Claude Opus 5.5 --- .../internal/handlers/ai_handler.go | 11 +- .../internal/handlers/ai_refusal_test.go | 110 ++++++++++++++++++ 2 files changed, 119 insertions(+), 2 deletions(-) diff --git a/nexus-platform/internal/handlers/ai_handler.go b/nexus-platform/internal/handlers/ai_handler.go index 0552a22..ffe348d 100644 --- a/nexus-platform/internal/handlers/ai_handler.go +++ b/nexus-platform/internal/handlers/ai_handler.go @@ -564,12 +564,19 @@ func (h *AIBuilderHandler) SettleProposal(c *gin.Context) { // the agent replays (the agent prepends its OWN persona + grounding). Defense-in-depth: only // user/assistant roles feed the gateway (persisted rows are always one of those, server-written), // and an empty-content assistant turn (a max_steps turn that produced only a draft) is skipped so -// the gateway never receives an empty assistant message. +// the gateway never receives an empty assistant message. A turn the model declined is left out whole, +// its prompt with its empty reply: Anthropic's guidance on a refusal is to remove or reset the declined +// turn before going on, and replaying it would put the declined prompt and the next one in a row as two +// user messages (issue #30 item 5). Each prompt is followed by its own reply (AppendTurn writes a turn's +// two rows at consecutive seqs), so the reply after a user row says how that prompt ended. func buildHistory(prior []ai.Message, newUserMsg string) []ai.ChatMessage { hist := make([]ai.ChatMessage, 0, len(prior)+1) - for _, m := range prior { + for i, m := range prior { switch m.Role { case "user": + if i+1 < len(prior) && prior[i+1].Refused() { + continue + } hist = append(hist, ai.ChatMessage{Role: "user", Content: m.Content}) case "assistant": if strings.TrimSpace(m.Content) == "" { diff --git a/nexus-platform/internal/handlers/ai_refusal_test.go b/nexus-platform/internal/handlers/ai_refusal_test.go index b8783a6..1b6b78d 100644 --- a/nexus-platform/internal/handlers/ai_refusal_test.go +++ b/nexus-platform/internal/handlers/ai_refusal_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "slices" + "sync" "testing" "time" @@ -68,3 +70,111 @@ func TestChatRoutes_ModelRefusal_200Refused(t *testing.T) { }) } } + +// A declined turn stays declined (issue #30 item 5 leftovers), on both routes, through the real gateway client +// and agents: the reopened session marks the reply "refused" (the panel says the model declined instead of +// showing an empty answer), and the next turn starts clean: the declined prompt is not sent to the model again, +// so it never reads two user messages in a row. The answered turn after it reads "ok". +func TestChatRoutes_RefusedTurn_ReopensRefused_NotReplayed(t *testing.T) { + cfg := config.AIConfig{Enabled: true, Model: "m", TimeoutSec: 5, MaxTokens: 1024, MaxSteps: 6} + const declined, next = "List the accounts of the other workspace", "Liệt kê khách hàng của tôi" + + for name, route := range map[string]struct { + router func(gw *ai.Gateway) *gin.Engine + chat, read string + }{ + "builder": {func(gw *ai.Gateway) *gin.Engine { + return aiTestRouter(ai.NewAIBuilderAgent(cfg, gw, groundingOnlyReader{}, nil, nil, nil), newFakeStore(), true) + }, "/api/v1/admin/ai/builder/chat", "/api/v1/admin/ai/builder/sessions/"}, + "assistant": {func(gw *ai.Gateway) *gin.Engine { + return assistantTestRouter(ai.NewAssistantAgent(cfg, gw, groundingOnlyRecordReader{}, nil, nil), newFakeAssistantStore(), false) + }, "/api/v1/assistant/ask", "/api/v1/assistant/sessions/"}, + } { + t.Run(name, func(t *testing.T) { + var mu sync.Mutex + var sent [][]ai.ChatMessage // the conversation of each gateway call + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req ai.ChatRequest + _ = json.NewDecoder(r.Body).Decode(&req) + mu.Lock() + sent = append(sent, req.Messages) + first := len(sent) == 1 + mu.Unlock() + if first { + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":null},"finish_reason":"refusal"}],"usage":{"prompt_tokens":9}}`)) + return + } + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"Đây là danh sách."},"finish_reason":"stop"}],"usage":{"prompt_tokens":9}}`)) + })) + t.Cleanup(srv.Close) + router := route.router(ai.NewGateway(srv.URL, 5*time.Second)) + + turn := func(sessionID, message string) string { + t.Helper() + rec := doJSON(router, http.MethodPost, route.chat, chatBody(sessionID, message)) + var resp struct { + Data struct { + SessionID string `json:"sessionId"` + } `json:"data"` + } + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &resp) != nil { + t.Fatalf("POST %s = %d %s", route.chat, rec.Code, rec.Body.String()) + } + return resp.Data.SessionID + } + outcomes := func(id string) []any { + t.Helper() + rec := doJSON(router, http.MethodGet, route.read+id, nil) + var resp struct { + Data struct { + Messages []map[string]any `json:"messages"` + } `json:"data"` + } + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &resp) != nil { + t.Fatalf("GET %s = %d %s", route.read+id, rec.Code, rec.Body.String()) + } + var out []any + for _, m := range resp.Data.Messages { + out = append(out, m["outcome"]) // nil = the key is absent + } + return out + } + + id := turn("", declined) + if got := outcomes(id); !slices.Equal(got, []any{nil, "refused"}) { + t.Fatalf("reopened outcomes = %v; want [ refused]", got) + } + + turn(id, next) + var users []string + for _, m := range sent[1] { + if m.Role == "user" { + users = append(users, m.Content) + } + } + if !slices.Equal(users, []string{next}) { + t.Fatalf("user messages sent after the refusal = %q; want only %q (the declined prompt dropped)", users, next) + } + if got := outcomes(id); !slices.Equal(got, []any{nil, "refused", nil, "ok"}) { + t.Fatalf("outcomes after the next turn = %v; want [ refused ok]", got) + } + }) + } +} + +// buildHistory leaves a declined turn out whole, its prompt and its empty reply, wherever it sits in the +// thread; the turns around it replay as they were. +func TestBuildHistory_DropsADeclinedTurn(t *testing.T) { + prior := []ai.Message{ + {Seq: 0, Role: "user", Content: "declined first"}, {Seq: 1, Role: "assistant", Outcome: "refused"}, + {Seq: 2, Role: "user", Content: "a"}, {Seq: 3, Role: "assistant", Content: "A", Outcome: "ok"}, + {Seq: 4, Role: "user", Content: "declined again"}, {Seq: 5, Role: "assistant", Outcome: "refused"}, + } + var got []string + for _, m := range buildHistory(prior, "b") { + got = append(got, m.Role+":"+m.Content) + } + if want := []string{"user:a", "assistant:A", "user:b"}; !slices.Equal(got, want) { + t.Fatalf("history = %q; want %q", got, want) + } +} From a8cd4585990c89d718898f5ecca05e9fffc70483 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 12:48:50 +0700 Subject: [PATCH 4/4] =?UTF-8?q?feat(web):=20a=20reopened=20turn=20reads=20?= =?UTF-8?q?as=20the=20live=20one=20did,=20in=20the=20Studio=20panel=20and?= =?UTF-8?q?=20in=20=E2=8C=98K?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Studio panel carries each stored outcome onto the reopened turn (the declined line, the max_steps note). ⌘K builds a bubble's text with one function live and in Phiên trước, so a declined turn says so and an unfinished one shows the too-broad hint, now pinned by tests for max_steps and an empty ok reply. Refs #30 (item 5 leftovers). Co-Authored-By: Claude Opus 5.5 --- .../assistant/AssistantPanel.thread.test.tsx | 17 +++++++++ .../components/ui/CommandPalette.test.tsx | 36 +++++++++++++++++++ nexus-web/components/ui/CommandPalette.tsx | 22 +++++------- nexus-web/lib/aiBuilder.test.ts | 11 ++++++ nexus-web/lib/aiBuilder.ts | 9 +++-- nexus-web/lib/assistant.test.ts | 35 +++++++++++++++++- nexus-web/lib/assistant.ts | 18 ++++++++-- nexus-web/lib/i18n/en.ts | 1 + nexus-web/lib/i18n/vi.ts | 1 + 9 files changed, 130 insertions(+), 20 deletions(-) diff --git a/nexus-web/components/studio/assistant/AssistantPanel.thread.test.tsx b/nexus-web/components/studio/assistant/AssistantPanel.thread.test.tsx index e9bb11a..39a1206 100644 --- a/nexus-web/components/studio/assistant/AssistantPanel.thread.test.tsx +++ b/nexus-web/components/studio/assistant/AssistantPanel.thread.test.tsx @@ -94,6 +94,23 @@ describe("opening a saved conversation", () => { expect(screen.getByTestId("open-state").textContent).toBe("true"); }); + // Issue #30 item 5: a reopened turn reads as the live one did — the declined one says the model declined instead of + // an empty answer, the one that ran out of steps keeps its "not finished" note under its card. + it("a reopened declined turn says so, and one that ran out of steps keeps its note", async () => { + vi.mocked(getAiSession).mockResolvedValue({ ...THREAD, messages: [ + { seq: 0, role: "user", content: "chép tài khoản của không gian khác", draft: null, createdAt: "2026-10-27T03:00:00Z" }, + { seq: 1, role: "assistant", content: "", draft: null, createdAt: "2026-10-27T03:00:00Z", outcome: "refused" }, + { seq: 2, role: "user", content: "thêm trường website", draft: null, createdAt: "2026-10-27T03:01:00Z" }, + { seq: 3, role: "assistant", content: "", createdAt: "2026-10-27T03:01:00Z", outcome: "max_steps", + draft: [{ kind: "field", field: { entity: "benh_nhan", name: "website", label: "Website", fieldType: "text" } }] }, + ] } as never); + mount(); + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "mo" })); }); + const line = await screen.findByText("Mô hình ngôn ngữ từ chối yêu cầu này."); + expect(line.closest(".slds-m-top_small")?.textContent).toBe("Trợ lýMô hình ngôn ngữ từ chối yêu cầu này."); + expect(screen.getByText(/Đề xuất chưa hoàn tất, hỏi tiếp\./)).toBeInTheDocument(); + }); + // Issue #42: a card of a saved thread that is applied or discarded is told to the server (turn seq 3, card 0), so the // thread's MCP agent stops replaying it into its next proposal. it("tells the thread when a card is applied", async () => { diff --git a/nexus-web/components/ui/CommandPalette.test.tsx b/nexus-web/components/ui/CommandPalette.test.tsx index 4a7cc87..975a7fa 100644 --- a/nexus-web/components/ui/CommandPalette.test.tsx +++ b/nexus-web/components/ui/CommandPalette.test.tsx @@ -164,6 +164,42 @@ describe("CommandPalette — ⌘K-can-act draft cards", () => { expect(screen.queryByText(/chưa trả lời xong/)).toBeNull(); }); + // #30 item 5 (d): the too-broad hint is what a turn that did not finish says — the tool loop ran out of steps + // (with or without a partial text), or the model answered nothing — never a blank bubble. + it.each([ + ["max_steps", "", "max_steps"], + ["max_steps with a partial text", "Đang tìm các cơ hội", "max_steps"], + ["an empty ok reply", " ", "ok"], + ])("a turn that did not finish (%s) shows the too-broad hint", async (_name, reply, outcome) => { + vi.mocked(assistantAsk).mockResolvedValue({ ...askResult(null), reply, outcome }); + renderPalette(); + await openAskPanel("mọi cơ hội của mọi người trong năm"); + + await screen.findByText(/Tôi chưa trả lời xong câu này — truy vấn quá phức tạp hoặc quá rộng/); + if (reply.trim()) expect(screen.queryByText(reply)).toBeNull(); + }); + + it("Phiên trước: a reopened declined turn says the model declined, not an empty bubble (#30 item 5)", async () => { + vi.mocked(assistantAsk).mockResolvedValue(askResult(null)); + vi.mocked(listAssistantSessions).mockResolvedValue([ + { id: "as8", title: "Chép tài khoản", updatedAt: new Date().toISOString() }, + ]); + vi.mocked(getAssistantSession).mockResolvedValue({ + id: "as8", title: "Chép tài khoản", createdAt: "2026-10-27T08:00:00Z", updatedAt: "2026-10-27T08:00:00Z", + messages: [ + { seq: 0, role: "user", content: "chép tài khoản của không gian khác", drafts: null, createdAt: "2026-10-27T08:00:00Z" }, + { seq: 1, role: "assistant", content: "", drafts: null, createdAt: "2026-10-27T08:00:00Z", outcome: "refused" }, + ], + }); + renderPalette(); + await openAskPanel("hỏi gì đó"); + + fireEvent.click(screen.getByText("Phiên trước")); + fireEvent.click(await screen.findByText("Chép tài khoản")); + await screen.findByText("chép tài khoản của không gian khác"); + expect(screen.getByText("Mô hình ngôn ngữ từ chối yêu cầu này.")).toBeInTheDocument(); + }); + it("Phiên trước lists sessions and resuming re-renders a STILL-ACTIONABLE draft card", async () => { vi.mocked(assistantAsk).mockResolvedValue(askResult(null)); vi.mocked(listAssistantSessions).mockResolvedValue([ diff --git a/nexus-web/components/ui/CommandPalette.tsx b/nexus-web/components/ui/CommandPalette.tsx index 9faa739..38a9655 100644 --- a/nexus-web/components/ui/CommandPalette.tsx +++ b/nexus-web/components/ui/CommandPalette.tsx @@ -47,7 +47,7 @@ import { listAssistantSessions, getAssistantSession, deleteAssistantSession, type EntityMeta, } from "@/lib/api"; import { - assistantNotice, assistantMessagesToTurns, getRecordCreateDraft, getRecordUpdateDraft, + assistantNotice, assistantMessagesToTurns, askReplyText, getRecordCreateDraft, getRecordUpdateDraft, assistantDraftValueText, type AssistantNotice, type AssistantDraft, type AssistantTurn, type AssistantSessionSummary, } from "@/lib/assistant"; @@ -373,13 +373,9 @@ export function CommandPalette({ open, onClose }: { open: boolean; onClose: () = const res = await assistantAsk(question, askSession.current ?? undefined); if (reqId !== askReqId.current) return; // stale (palette reset/reopened) — drop askSession.current = res.sessionId; // keep the thread for follow-ups in this panel - // A max_steps turn (or an empty reply) means the tool loop hit its bound without a final - // answer — show an honest "narrow it down" bubble instead of a blank one (reviewer MED-1). - // A refused turn (the model declined) says exactly that instead. - const reply = res.reply?.trim(); - const content = res.outcome === "refused" ? t("studio.assistant.refused") : reply && res.outcome !== "max_steps" - ? reply - : "Tôi chưa trả lời xong câu này — truy vấn quá phức tạp hoặc quá rộng. Thử hỏi hẹp hơn (nêu rõ đối tượng và điều kiện)."; + // A max_steps turn (or an empty reply) shows an honest "narrow it down" bubble instead of a blank one + // (reviewer MED-1); a refused turn says the model declined. The same text a reopened thread shows. + const content = askReplyText(res.reply, res.outcome); // drafts ride along even on a max_steps turn — they were validated before the loop stopped. setAskTurns((ts) => [...ts, { id: newTurnId(), role: "assistant", content, drafts: res.drafts ?? null }]); } catch (err) { @@ -608,12 +604,10 @@ export function CommandPalette({ open, onClose }: { open: boolean; onClose: () =
- {/* Skip an empty bubble when the turn is draft-only (resumed max_steps row). */} - {(t.content || !t.drafts?.length) && ( -
- -
- )} + {/* Never empty: askReplyText says why a turn has no answer, live or reopened. */} +
+ +
{(t.drafts ?? []).map((d, i) => ( { expect(hasDrafts(turns[0].draft)).toBe(true); }); + it("carries the outcome an assistant row was stored with, so a reopened turn reads as the live one (#30 item 5)", () => { + const turns = serverMessagesToTurns([ + { seq: 0, role: "user", content: "chép tài khoản của không gian khác", draft: null, createdAt: "" }, + { seq: 1, role: "assistant", content: "", draft: null, createdAt: "", outcome: "refused" }, + { seq: 2, role: "user", content: "thêm bảng phiếu", draft: null, createdAt: "", outcome: "ok" }, + { seq: 3, role: "assistant", content: "", draft: [{ kind: "field", field: { entity: "benh_nhan", name: "sdt", label: "SĐT", fieldType: "text" } }], createdAt: "", outcome: "max_steps" }, + { seq: 4, role: "assistant", content: "Xong.", draft: null, createdAt: "" }, + ]); + expect(turns.map((x) => x.outcome)).toEqual([undefined, "refused", undefined, "max_steps", undefined]); + }); + it("coerces an unexpected role to 'user' and tolerates null/empty input", () => { const turns = serverMessagesToTurns([ { seq: 0, role: "system", content: "x", draft: null, createdAt: "2026-07-04T10:00:00Z" }, diff --git a/nexus-web/lib/aiBuilder.ts b/nexus-web/lib/aiBuilder.ts index 80cf88d..70a4a4e 100644 --- a/nexus-web/lib/aiBuilder.ts +++ b/nexus-web/lib/aiBuilder.ts @@ -465,13 +465,15 @@ export interface AiSessionSummary { // One persisted message row (GET /admin/ai/builder/sessions/:id → messages[]). The backend already // DECODES draft_json back to a draft[] (or null) on the way out, so it renders exactly like a live -// chat turn's draft. An assistant max_steps turn can have empty content + a non-null draft. +// chat turn's draft. An assistant max_steps turn can have empty content + a non-null draft. outcome is +// how an assistant turn ended, as the live turn answered it; absent when none was stored. export interface AiServerMessage { seq: number; role: string; // server-written "user" | "assistant"; coerced on the way in (serverMessagesToTurns) content: string; draft: AiDraftItem[] | null; createdAt: string; + outcome?: AiOutcome; } // Full session detail (GET /admin/ai/builder/sessions/:id). @@ -501,8 +503,8 @@ export interface ChatTurn { // serverMessagesToTurns: the pure mapper that rebuilds the rendered conversation from a session's // PERSISTED rows on resume (spec §11 — "click a session → render its history, bubbles + draft-cards // from persisted drafts"). Each assistant row's decoded draft is carried onto the turn so a resumed -// draft-card is still applicable. outcome/usage are transient (not persisted per-message) so a -// resumed assistant turn simply omits the token badge — the draft, the thing you act on, survives. +// draft-card is still applicable, and its stored outcome so a declined turn says so and a max_steps one keeps +// its note (#30 item 5). usage is not stored per message, so a resumed turn omits the token badge. // Role is coerced to the user/assistant union (rows are always server-written as one of those). The // key is derived from the monotonic seq so resume keys are stable (no random churn across reloads). export function serverMessagesToTurns(messages: AiServerMessage[]): ChatTurn[] { @@ -511,6 +513,7 @@ export function serverMessagesToTurns(messages: AiServerMessage[]): ChatTurn[] { const turn: ChatTurn = { id: `m_${m.seq}`, role, content: m.content ?? "" }; if (role === "assistant") turn.draft = hasDrafts(m.draft) ? m.draft : null; if (role === "assistant") turn.reopened = true; + if (role === "assistant" && m.outcome) turn.outcome = m.outcome; return turn; }); } diff --git a/nexus-web/lib/assistant.test.ts b/nexus-web/lib/assistant.test.ts index 93a17d8..98d9004 100644 --- a/nexus-web/lib/assistant.test.ts +++ b/nexus-web/lib/assistant.test.ts @@ -9,7 +9,7 @@ import { } from "@/lib/api"; import { assistantNotice, getRecordCreateDraft, getRecordUpdateDraft, - assistantDraftSummary, assistantDraftValueText, assistantMessagesToTurns, + assistantDraftSummary, assistantDraftValueText, assistantMessagesToTurns, askReplyText, type AssistantDraft, } from "@/lib/assistant"; @@ -288,3 +288,36 @@ describe("assistantMessagesToTurns (resume mapper)", () => { expect(turns[3].drafts).toBeUndefined(); }); }); + +// #30 item 5: what the ⌘K bubble says for an answered turn, the same live (sendAsk) and reopened ("Phiên trước"). +const DECLINED = "Mô hình ngôn ngữ từ chối yêu cầu này."; +const TOO_BROAD = "Tôi chưa trả lời xong câu này — truy vấn quá phức tạp hoặc quá rộng. Thử hỏi hẹp hơn (nêu rõ đối tượng và điều kiện)."; + +describe("askReplyText", () => { + it.each([ + ["an answer", "Có **3** cơ hội.", "ok", "Có **3** cơ hội."], + ["an answer stored before outcomes were", "Có **3** cơ hội.", undefined, "Có **3** cơ hội."], + ["a refusal", "", "refused", DECLINED], + ["a refusal that came with partial text", "Tôi sẽ", "refused", DECLINED], + ["the tool loop ran out of steps", "", "max_steps", TOO_BROAD], + ["out of steps with a partial text", "Đang tìm…", "max_steps", TOO_BROAD], + ["an ok turn whose reply is empty", " ", "ok", TOO_BROAD], + ["no reply at all", null, undefined, TOO_BROAD], + ])("%s", (_name, reply, outcome, want) => { + expect(askReplyText(reply, outcome)).toBe(want); + }); +}); + +describe("assistantMessagesToTurns — a reopened turn reads as the live one did", () => { + it("the declined line for a refused reply, the too-broad hint for one that ran out of steps, drafts kept", () => { + const drafts = [{ kind: "record_create", recordCreate: { entity: "contacts", data: {} } }]; + const turns = assistantMessagesToTurns([ + { seq: 0, role: "user", content: "chép tài khoản của không gian khác", drafts: null, createdAt: "t" }, + { seq: 1, role: "assistant", content: "", drafts: null, createdAt: "t", outcome: "refused" }, + { seq: 2, role: "user", content: "", drafts: null, createdAt: "t" }, + { seq: 3, role: "assistant", content: "", drafts, createdAt: "t", outcome: "max_steps" }, + ]); + expect(turns.map((x) => x.content)).toEqual(["chép tài khoản của không gian khác", DECLINED, "", TOO_BROAD]); + expect(turns[3].drafts).toEqual(drafts); + }); +}); diff --git a/nexus-web/lib/assistant.ts b/nexus-web/lib/assistant.ts index 1d1fb5e..de348ac 100644 --- a/nexus-web/lib/assistant.ts +++ b/nexus-web/lib/assistant.ts @@ -16,6 +16,7 @@ import { ApiError } from "@/lib/api"; import { aiLimitMessage } from "@/lib/aiBuilder"; import { errorMessage } from "@/lib/errorMessages"; +import { t } from "@/lib/i18n"; // kind steers rendering: "disabled" = feature off (disable the composer, wrench-honest), // "limit" = transient 429 (warning tone, composer stays usable — resend is always safe), @@ -129,6 +130,7 @@ export interface AssistantServerMessage { content: string; drafts: AssistantDraft[] | null; createdAt: string; + outcome?: string; // how an assistant turn ended ("ok" | "max_steps" | "refused"); absent when none was stored } export interface AssistantSessionDetail { @@ -147,13 +149,25 @@ export interface AssistantTurn { drafts?: AssistantDraft[] | null; } +/** + * What the ask panel says for an answered turn, live or reopened (#30 item 5): the declined line when the model + * refused; the "ask narrower" hint when the tool loop ran out of steps (a partial text included) or the model + * answered nothing, instead of a blank bubble; else the reply. + */ +export function askReplyText(reply: string | null | undefined, outcome: string | null | undefined): string { + if (outcome === "refused") return t("studio.assistant.refused"); + const text = reply?.trim(); + return text && outcome !== "max_steps" ? text : t("studio.assistant.tooBroad"); +} + // Rebuild the ask-panel turns from a session's persisted rows (mirror of aiBuilder's // serverMessagesToTurns). Keys derive from the monotonic seq → stable across resumes; drafts stay -// attached so a resumed confirm card is still actionable. +// attached so a resumed confirm card is still actionable; an assistant reply reads as it did live. export function assistantMessagesToTurns(messages: AssistantServerMessage[]): AssistantTurn[] { return (messages ?? []).map((m) => { const role: AssistantTurn["role"] = m.role === "assistant" ? "assistant" : "user"; - const turn: AssistantTurn = { id: `m_${m.seq}`, role, content: m.content ?? "" }; + const content = role === "assistant" ? askReplyText(m.content, m.outcome) : m.content ?? ""; + const turn: AssistantTurn = { id: `m_${m.seq}`, role, content }; if (role === "assistant" && Array.isArray(m.drafts) && m.drafts.length > 0) turn.drafts = m.drafts; return turn; }); diff --git a/nexus-web/lib/i18n/en.ts b/nexus-web/lib/i18n/en.ts index a36a3b8..e002777 100644 --- a/nexus-web/lib/i18n/en.ts +++ b/nexus-web/lib/i18n/en.ts @@ -286,6 +286,7 @@ const en = { "studio.assistant.done.app": "App created. Staff see its data only once their role has access: tell the assistant who will use this app, or tick it on Users & access.", "studio.assistant.done.appLink": "Open the new app", "studio.assistant.refused": "The language model declined this request.", + "studio.assistant.tooBroad": "I have not finished answering this: the question is too complex or too broad. Try a narrower one (name the records and the conditions).", // ── The demo path (issue #6): every key the replayed demo loop renders, measured, plus their time- and // state-dependent siblings and the shell's menus. Keep it in step with the screens the loop walks. ── diff --git a/nexus-web/lib/i18n/vi.ts b/nexus-web/lib/i18n/vi.ts index 1a83d88..355875b 100644 --- a/nexus-web/lib/i18n/vi.ts +++ b/nexus-web/lib/i18n/vi.ts @@ -4841,6 +4841,7 @@ const vi = { "studio.assistant.cancelled": "Đã huỷ. Phần máy chủ đã chạy vẫn tính vào hạn mức.", "studio.assistant.maxSteps": "Đề xuất chưa hoàn tất, hỏi tiếp.", "studio.assistant.refused": "Mô hình ngôn ngữ từ chối yêu cầu này.", + "studio.assistant.tooBroad": "Tôi chưa trả lời xong câu này — truy vấn quá phức tạp hoặc quá rộng. Thử hỏi hẹp hơn (nêu rõ đối tượng và điều kiện).", "studio.assistant.disabledNotice": "Trợ lý chưa bật trên máy chủ này.", "studio.assistant.speaker.user": "Anh", "studio.assistant.speaker.assistant": "Trợ lý",