Skip to content
Merged
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
131 changes: 131 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 Down Expand Up @@ -276,6 +277,7 @@ describe("deriveConversationReplyState", () => {
prompt: "What time should I schedule it?",
reason: "time",
open: true,
parentTargetRef: null,
},
},
];
Expand Down Expand Up @@ -331,6 +333,134 @@ 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" },
],
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 +479,7 @@ describe("deriveMutationState", () => {
prompt: "What time should I schedule it?",
reason: "time",
open: true,
parentTargetRef: null,
},
},
];
Expand Down
19 changes: 19 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 Down Expand Up @@ -277,6 +295,7 @@ export function deriveMutationState(input: DeriveMutationStateInput) {
prompt: input.processing.followUpMessage,
reason: input.processing.reason,
open: true,
parentTargetRef: null,
},
},
);
Expand Down
133 changes: 133 additions & 0 deletions apps/web/src/lib/server/turn-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,139 @@ describe("resolveWriteTarget", () => {
expect(result).toEqual({});
});

it("follows parentTargetRef from entity registry when focus points at a clarification", () => {
const result = resolveWriteTarget(
{
focus_entity_id: "clar-1",
currently_editable_entity_id: null,
last_user_mentioned_entity_ids: [],
last_presented_items: [],
pending_clarifications: [],
mode: "clarifying",
},
[
{
id: "clar-1",
conversationId: "c-1",
kind: "clarification",
label: "What time?",
status: "active",
createdAt: "2026-04-09T10:00:00.000Z",
updatedAt: "2026-04-09T10:00:00.000Z",
data: {
prompt: "What time?",
reason: "scheduleFields.time",
open: true,
parentTargetRef: { entityId: "task-1" },
},
},
],
"clarification_answer",
);

expect(result.targetEntityId).toBe("task-1");
});

it("follows parentTargetRef regardless of turn type", () => {
const result = resolveWriteTarget(
{
focus_entity_id: "clar-1",
currently_editable_entity_id: null,
last_user_mentioned_entity_ids: [],
last_presented_items: [],
pending_clarifications: [],
mode: "clarifying",
},
[
{
id: "clar-1",
conversationId: "c-1",
kind: "clarification",
label: "What time?",
status: "active",
createdAt: "2026-04-09T10:00:00.000Z",
updatedAt: "2026-04-09T10:00:00.000Z",
data: {
prompt: "What time?",
reason: "scheduleFields.time",
open: true,
parentTargetRef: { entityId: "task-1" },
},
},
],
"edit_request",
);

expect(result.targetEntityId).toBe("task-1");
});

it("uses candidate ID as-is when entity has no parentTargetRef", () => {
const result = resolveWriteTarget(
{
focus_entity_id: "task-1",
currently_editable_entity_id: null,
last_user_mentioned_entity_ids: [],
last_presented_items: [],
pending_clarifications: [],
mode: "planning",
},
[
{
id: "task-1",
conversationId: "c-1",
kind: "task",
label: "Gym",
status: "active",
createdAt: "2026-04-09T10:00:00.000Z",
updatedAt: "2026-04-09T10:00:00.000Z",
data: {
taskId: "t-1",
title: "Gym",
lifecycleState: "scheduled",
scheduledStartAt: null,
scheduledEndAt: null,
},
},
],
"edit_request",
);

expect(result.targetEntityId).toBe("task-1");
});

it("uses entity's own ID when parentTargetRef is null", () => {
const result = resolveWriteTarget(
{
focus_entity_id: "clar-1",
currently_editable_entity_id: null,
last_user_mentioned_entity_ids: [],
last_presented_items: [],
pending_clarifications: [],
mode: "clarifying",
},
[
{
id: "clar-1",
conversationId: "c-1",
kind: "clarification",
label: "What time?",
status: "active",
createdAt: "2026-04-09T10:00:00.000Z",
updatedAt: "2026-04-09T10:00:00.000Z",
data: {
prompt: "What time?",
reason: "scheduleFields.time",
open: true,
parentTargetRef: null,
},
},
],
"clarification_answer",
);

expect(result.targetEntityId).toBe("clar-1");
});

it("attaches resolvedProposalId for non-confirmation turns when single proposal exists", () => {
const result = resolveWriteTarget(
null,
Expand Down
23 changes: 23 additions & 0 deletions apps/web/src/lib/server/turn-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ export type WriteTarget = {
resolvedProposalId?: string;
};

/** Extract the parent entity ID from entity kinds that carry a parentTargetRef. */
function getParentEntityId(entity: ConversationEntity): string | undefined {
switch (entity.kind) {
case "clarification":
return entity.data.parentTargetRef?.entityId;
default:
return undefined;
}
}

export function resolveWriteTarget(
discourseState: ConversationDiscourseState | null,
entityRegistry: ConversationEntity[],
Expand All @@ -44,6 +54,19 @@ export function resolveWriteTarget(
discourseState?.focus_entity_id ?? null,
]);

// Generic parent ref resolution: if the candidate entity carries a
// non-null parentTargetRef, follow it to the actual write target.
// A null parentTargetRef means the entity itself is the target.
if (resolvedEntityIds[0]) {
const entity = entityRegistry.find((e) => e.id === resolvedEntityIds[0]);
if (entity) {
const parentId = getParentEntityId(entity);
if (parentId) {
resolvedEntityIds[0] = parentId;
}
}
}

const activeProposals = entityRegistry.filter(
(e): e is Extract<ConversationEntity, { kind: "proposal_option" }> =>
e.kind === "proposal_option" &&
Expand Down
Loading