Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions apps/web/src/lib/server/conversation-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ describe("deriveConversationReplyState", () => {
prompt: "What time should I schedule it?",
reason: "time",
open: true,
parentTargetRef: null,
},
},
];
Expand All @@ -171,6 +172,7 @@ describe("deriveConversationReplyState", () => {

createdAt: "2026-03-22T16:01:00.000Z",
createdTurnId: "assistant:1",
parentTargetRef: null,
},
],
mode: "clarifying",
Expand Down Expand Up @@ -276,6 +278,7 @@ describe("deriveConversationReplyState", () => {
prompt: "What time should I schedule it?",
reason: "time",
open: true,
parentTargetRef: null,
},
},
];
Expand All @@ -292,6 +295,7 @@ describe("deriveConversationReplyState", () => {
status: "pending",
createdAt: "2026-03-22T16:01:00.000Z",
createdTurnId: "assistant:1",
parentTargetRef: null,
},
],
mode: "clarifying",
Expand Down Expand Up @@ -331,6 +335,153 @@ describe("deriveConversationReplyState", () => {
]),
);
});

it("sets parentTargetRef on clarification entity from resolvedOperation targetRef", () => {
const op = buildPendingWriteOperation({
targetRef: { entityId: "task-1" },
resolvedFields: { scheduleFields: { day: "tomorrow" } },
missingFields: ["scheduleFields.time"],
});

const result = deriveConversationReplyState({
snapshot: buildSnapshot(),
policy: {
action: "ask_clarification",
clarificationSlots: ["scheduleFields.time"],
resolvedOperation: op,
},
interpretation: {
turnType: "planning_request",
confidence: 0.58,
resolvedEntityIds: [],
ambiguity: "high",
missingFields: ["scheduleFields.time"],
},
reply: "What time should I schedule it?",
userTurnText: "schedule gym tomorrow",
summaryText: null,
occurredAt: "2026-03-22T16:05:00.000Z",
});

const clarEntity = result.entityRegistry.find(
(e) => e.kind === "clarification",
);
expect(clarEntity).toBeDefined();
expect(clarEntity!.data.parentTargetRef).toEqual({
entityId: "task-1",
});
});

it("sets parentTargetRef to null on clarification entity for new plans", () => {
const op = buildPendingWriteOperation({
targetRef: null,
resolvedFields: { scheduleFields: { day: "tomorrow" } },
missingFields: ["scheduleFields.time"],
});

const result = deriveConversationReplyState({
snapshot: buildSnapshot(),
policy: {
action: "ask_clarification",
clarificationSlots: ["scheduleFields.time"],
resolvedOperation: op,
},
interpretation: {
turnType: "planning_request",
confidence: 0.58,
resolvedEntityIds: [],
ambiguity: "high",
missingFields: ["scheduleFields.time"],
},
reply: "What time should I schedule it?",
userTurnText: "schedule gym tomorrow",
summaryText: null,
occurredAt: "2026-03-22T16:05:00.000Z",
});

const clarEntity = result.entityRegistry.find(
(e) => e.kind === "clarification",
);
expect(clarEntity).toBeDefined();
expect(clarEntity!.data.parentTargetRef).toBeNull();
});

it("closes prior open clarification when a new one is created", () => {
const snapshot = buildSnapshot();
snapshot.entityRegistry = [
{
id: "clar-old",
conversationId: "conversation-1",
kind: "clarification",
label: "Need a time",
status: "active",
createdAt: "2026-03-22T16:01:00.000Z",
updatedAt: "2026-03-22T16:01:00.000Z",
data: {
prompt: "What time?",
reason: "scheduleFields.time",
open: true,
parentTargetRef: null,
},
},
];
snapshot.discourseState = {
focus_entity_id: "clar-old",
currently_editable_entity_id: null,
last_user_mentioned_entity_ids: [],
last_presented_items: [],
pending_clarifications: [
{
id: "clar-old",
slot: "scheduleFields.time",
question: "What time?",
status: "pending",
createdAt: "2026-03-22T16:01:00.000Z",
createdTurnId: "assistant:1",
parentTargetRef: null,
},
],
mode: "clarifying",
};

const op = buildPendingWriteOperation({
targetRef: null,
resolvedFields: { scheduleFields: { day: "tomorrow" } },
missingFields: ["scheduleFields.duration"],
});

const result = deriveConversationReplyState({
snapshot,
policy: {
action: "ask_clarification",
clarificationSlots: ["scheduleFields.duration"],
resolvedOperation: op,
},
interpretation: {
turnType: "clarification_answer",
confidence: 0.8,
resolvedEntityIds: [],
ambiguity: "high",
missingFields: ["scheduleFields.duration"],
},
reply: "Got it, 5pm. How long should it be?",
userTurnText: "5pm",
summaryText: null,
occurredAt: "2026-03-22T16:06:00.000Z",
});

const oldClar = result.entityRegistry.find((e) => e.id === "clar-old");
expect(oldClar).toMatchObject({
status: "resolved",
data: expect.objectContaining({ open: false }),
});

const newClars = result.entityRegistry.filter(
(e) => e.kind === "clarification" && e.data.open === true,
);
expect(newClars).toHaveLength(1);
expect(newClars[0]!.data).toMatchObject({ reason: "scheduleFields.duration" });
});
});

describe("deriveMutationState", () => {
Expand All @@ -349,6 +500,7 @@ describe("deriveMutationState", () => {
prompt: "What time should I schedule it?",
reason: "time",
open: true,
parentTargetRef: null,
},
},
];
Expand All @@ -366,6 +518,7 @@ describe("deriveMutationState", () => {

createdAt: "2026-03-22T16:01:00.000Z",
createdTurnId: "assistant:1",
parentTargetRef: null,
},
],
mode: "clarifying",
Expand Down
21 changes: 21 additions & 0 deletions apps/web/src/lib/server/conversation-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,23 @@ export function deriveConversationReplyState(
);
}

const parentTargetRef =
input.policy.resolvedOperation?.targetRef ?? null;

// Close any prior open clarifications (one-open-per-workflow)
for (let i = 0; i < entityRegistry.length; i++) {
const entity = entityRegistry[i]!;
if (entity.kind === "clarification" && entity.data.open) {
entityRegistry[i] = {
...entity,
status: "resolved" as const,
updatedAt: occurredAt,
data: { ...entity.data, open: false },
};
resolvedClarificationIds.push(entity.id);
}
}

const clarificationEntity = buildConversationEntity(
input.snapshot.conversation.id,
{
Expand All @@ -141,6 +158,7 @@ export function deriveConversationReplyState(
prompt: input.reply,
reason: clarificationSlot,
open: true,
parentTargetRef,
},
},
);
Expand All @@ -153,6 +171,7 @@ export function deriveConversationReplyState(
status: "pending",
createdAt: occurredAt,
createdTurnId: `assistant:${occurredAt}`,
parentTargetRef,
});
nextFocusEntityId ??= clarificationEntity.id;
}
Expand Down Expand Up @@ -277,6 +296,7 @@ export function deriveMutationState(input: DeriveMutationStateInput) {
prompt: input.processing.followUpMessage,
reason: input.processing.reason,
open: true,
parentTargetRef: null,
},
},
);
Expand All @@ -290,6 +310,7 @@ export function deriveMutationState(input: DeriveMutationStateInput) {
status: "pending",
createdAt: occurredAt,
createdTurnId: `assistant:${occurredAt}`,
parentTargetRef: null,
});
}

Expand Down
16 changes: 12 additions & 4 deletions apps/web/src/lib/server/decide-turn-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
type CommitPolicyOutput,
containsWriteVerb,
type ConversationEntity,
conversationEntitySchema,
deriveAmbiguity,
deriveConsentRequirement,
type TurnAmbiguity,
Expand Down Expand Up @@ -39,6 +40,9 @@ export function decideTurnPolicy(
): TurnPolicyDecision {
const { classification, commitResult } = input;
const targetEntityId = input.targetEntityId;
const entityRegistry = (input.routingContext.entityRegistry ?? []).map((e) =>
conversationEntitySchema.parse(e),
);
const ambiguity = deriveAmbiguity({
classifierConfidence: classification.confidence,
missingFields: commitResult.missingFields,
Expand Down Expand Up @@ -69,7 +73,7 @@ export function decideTurnPolicy(
const proposalId =
input.resolvedProposalId ??
resolveSingleActiveProposalId(
input.routingContext.entityRegistry ?? [],
entityRegistry,
);

if (proposalId) {
Expand Down Expand Up @@ -165,8 +169,10 @@ function deriveStructuredWriteReadiness(
}

if (classification.turnType === "clarification_answer") {
const entityRegistry = input.routingContext.entityRegistry ?? [];
const alreadyConfirmed = entityRegistry.some(
const parsedRegistry = (input.routingContext.entityRegistry ?? []).map((e) =>
conversationEntitySchema.parse(e),
);
const alreadyConfirmed = parsedRegistry.some(
(e) =>
e.kind === "proposal_option" &&
e.id === input.resolvedProposalId &&
Expand All @@ -187,7 +193,9 @@ function deriveStructuredWriteReadiness(
...(input.resolvedProposalId
? { resolvedProposalId: input.resolvedProposalId }
: {}),
entityRegistry: input.routingContext.entityRegistry ?? [],
entityRegistry: (input.routingContext.entityRegistry ?? []).map((e) =>
conversationEntitySchema.parse(e),
),
resolvedFields: commitResult.resolvedFields,
turnType: classification.turnType,
});
Expand Down
Loading