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
80 changes: 62 additions & 18 deletions apps/server/src/kin/chat/KinGroups.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,27 +854,26 @@ it.effect(
["expired"],
);
// What it was asked goes unanswered, and the chat hears it once, where Sam reads too.
const told = "Tech lead didn't reply: someone joined before it answered. Send it again.";
const told = "A message sent just before someone joined went unanswered. Send it again.";
const lines = sql<{ messageId: KinMessageId; body: string }>`SELECT message_id AS
"messageId", body FROM kin_messages WHERE chat_id = ${chatId} AND author_kind = 'system'
ORDER BY seq`;
assert.deepStrictEqual(
(yield* lines).map((row) => row.body),
[told],
[told, told, told],
);
assert.deepStrictEqual(
(yield* chats.history([sam], { chatId, beforeSeq: 1000, limit: 50 })).messages.map(
(message) => message.body,
),
[told],
[told, told, told],
);
// The join handled again, or its line retried, posts nothing more.
const again = yield* sql.withTransaction(
ChatSharing.onPersonJoined({ orgId, chatId, personId: sam.personId }),
);
assert.deepStrictEqual(again.stopped, []);
yield* ChatSharing.tellStopped({ orgId, chatId, lines: yield* lines });
assert.lengthOf(yield* lines, 1);
assert.lengthOf(yield* lines, 3);
yield* queue.finish({ orgId, wakeupId: running.wakeupId, status: "completed" });
// Said after Sam joined, and a tap there on the card from before: only the first is his.
const after = yield* say(sam, chatId, "Invented-sam-question");
Expand All @@ -883,7 +882,7 @@ it.effect(
WHERE message_id = ${tap.messageId}`;
const turn = yield* wake(tech);
yield* sql`UPDATE kin_wakeups SET audience = 'shared' WHERE wakeup_id = ${turn.wakeupId}`;
assert.deepStrictEqual(yield* seen(turn), [told, "Invented-sam-question"]);
assert.deepStrictEqual(yield* seen(turn), [told, told, told, "Invented-sam-question"]);
assert.deepStrictEqual(
(yield* chats.read(turn, { chatId, afterSeq: after.seq - 1, limit: 1 })).map(
(message) => message.messageId,
Expand All @@ -899,19 +898,19 @@ it.effect.each([
joiner: "member",
before: "a tool call",
lines: [
"Tech lead didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.",
"A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.",
],
},
{
joiner: "member",
before: "still queued",
lines: ["Tech lead didn't reply: someone joined before it answered. Send it again."],
lines: ["A message sent just before someone joined went unanswered. Send it again."],
},
// `historyFloor` exempts only the chat's own owner member: a co-owner's join moves it too.
{
joiner: "co_owner",
before: "nothing",
lines: ["Tech lead didn't reply: someone joined before it answered. Send it again."],
lines: ["A message sent just before someone joined went unanswered. Send it again."],
},
] as const)(
"a join that leaves a person's question unanswered says so in the chat once ($joiner, $before)",
Expand All @@ -930,14 +929,18 @@ it.effect.each([
if (before === "a tool call" && running !== undefined)
yield* sql`INSERT INTO kin_lead_tool_calls (org_id, wakeup_id, call_key, request_hash)
VALUES (${orgId}, ${running.wakeupId}, 'item:task-1', 'fixture-hash')`;
yield* groups.addMember([owner], {
chatId,
principal: { _tag: "person", personId: priya.personId },
});
assert.deepStrictEqual(
yield* sql`SELECT body FROM kin_messages WHERE chat_id = ${chatId}
yield* sql.withTransaction(
Effect.gen(function* () {
yield* groups.addMember([owner], {
chatId,
principal: { _tag: "person", personId: priya.personId },
});
assert.deepStrictEqual(
yield* sql`SELECT body FROM kin_messages WHERE chat_id = ${chatId}
AND author_kind = 'system' ORDER BY seq`,
lines.map((body) => ({ body })),
lines.map((body) => ({ body })),
);
}),
);
// After the line, the stopped run failing or a restart neither answers nor tells it again.
if (running !== undefined && before === "a tool call")
Expand All @@ -958,13 +961,53 @@ it.effect.each([
}).pipe(Effect.provide(layer)),
);

it.effect.each([false, true])(
"one join handles a message sent to two leads (already answered: %s)",
(answered) =>
Effect.gen(function* () {
const { sql, groups, queue, owner, orgId, tech, growth, priya, say, wake, events } =
yield* seed;
const { chatId } = yield* groups.create([owner], {
orgId,
title: "Planning",
agentIds: [tech, growth],
personIds: [],
});
const { members } = yield* groups.members([owner], { chatId });
const mentions = members
.filter((member) => member.principal._tag === "agent")
.map(({ memberId }) => memberId);
const ask = yield* say(owner, chatId, "What goes on the launch board?", mentions);
const running = yield* wake(tech);
if (answered) {
const earlier = yield* wake(growth);
yield* sql`UPDATE kin_events SET replied_at = 1 WHERE wakeup_id = ${earlier.wakeupId}`;
yield* queue.finish({ orgId, wakeupId: earlier.wakeupId, status: "completed" });
}
yield* groups.addMember([owner], {
chatId,
principal: { _tag: "person", personId: priya.personId },
});
yield* queue.finish({ orgId, wakeupId: running.wakeupId, status: "interrupted" });
assert.sameMembers(
(yield* events).filter((row) => row.messageId === ask.messageId).map(({ state }) => state),
answered ? ["expired", "done"] : ["expired", "expired"],
);
assert.lengthOf(
yield* sql`SELECT 1 FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${chatId}
AND kind = 'system'`,
answered ? 0 : 1,
);
}).pipe(Effect.provide(layer)),
);

// Reply model of 25 Nov: a join after the reply posted, mid-run, told the asker to ask again.
it.effect.each([
{ unanswered: false, lines: [] },
{
unanswered: true,
lines: [
"Tech lead didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.",
"A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.",
],
},
] as const)(
Expand Down Expand Up @@ -1081,7 +1124,8 @@ it.effect(
(message) => message.body,
),
[
"Tech lead didn't reply: someone joined before it answered. Send it again.",
"A message sent just before someone joined went unanswered. Send it again.",
"A message sent just before someone joined went unanswered. Send it again.",
"Invented-priya-is-back",
],
);
Expand Down
87 changes: 43 additions & 44 deletions apps/server/src/kin/lead/ChatSharing.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- a synchronous notice id that does not expose the fenced message id.
import * as NodeCrypto from "node:crypto";

import {
KinCardAsker,
KinChatId,
Expand Down Expand Up @@ -38,10 +41,10 @@ const PERSON_ASK_TAGS = ["chat.message", "widget.action"] as const;
* The line a chat hears when a join stopped an agent before it answered a person, on every path
* that stops it (`onPersonJoined`, `KinReplyBridge`). `partway`: the turn did something visible.
*/
export const stoppedByJoinNotice = (leadName: string, partway: boolean) =>
export const stoppedByJoinNotice = (partway: boolean) =>
partway
? `${leadName} didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.`
: `${leadName} didn't reply: someone joined before it answered. Send it again.`;
? "A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer."
: "A message sent just before someone joined went unanswered. Send it again.";

/** The fixed line a delegated task's card in a shared chat shows instead of its own. */
const movedCardTitle = (lead: string) => `Moved to your private chat with ${lead}`;
Expand All @@ -65,8 +68,8 @@ const endChatThreads = Effect.fnUntraced(function* (
/**
* In every join's transaction, after `recordJoin`: aborts the running turns there and ends the
* chat's lead threads; expires waiting events below the history floor; names the tasks agents
* delegated there, whose cards the caller freezes, as only owner-only turns delegate. Returns what
* runs after commit, the chat's lines for asks it left unanswered (`tellStopped`) included.
* delegated there, whose cards the caller freezes. The caller must run `finishPersonJoin` before
* committing, so event expiry and failure lines are durable together.
*/
export const onPersonJoined = Effect.fn("KinChatSharing.onPersonJoined")(function* (input: {
readonly orgId: KinOrgId;
Expand Down Expand Up @@ -102,10 +105,16 @@ export const onPersonJoined = Effect.fn("KinChatSharing.onPersonJoined")(functio
UPDATE kin_events AS e SET state = 'expired'
WHERE ${asked} AND (e.state = 'queued' OR (${heldByAborted}))
RETURNING agent_id AS "agentId", event_id AS "eventId"`;
return { turns, threads, expired, moved, stopped: yield* stoppedLines(sql, input, expired) };
return {
turns,
threads,
expired,
moved,
stopped: yield* stoppedLines(sql, input.orgId, expired),
};
});

/** Commit the live effects only after the reader and the transcript fence have committed. */
/** Make the failure line durable with the expiry. Publish it and stop the old run after commit. */
export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(function* (
chat: { readonly orgId: KinOrgId; readonly chatId: string },
join: Effect.Success<ReturnType<typeof onPersonJoined>>,
Expand All @@ -119,6 +128,11 @@ export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(fun
) {
const sql = yield* SqlClient.SqlClient;
const { identity, stop, presence, repo, hub } = services;
if (join.stopped.length > 0)
yield* tellStopped({ ...chat, lines: join.stopped }).pipe(
Effect.provideService(KinChatRepository, repo),
Effect.provideService(KinChatHub, hub),
);
yield* sql.afterCommit(
Effect.gen(function* () {
if (identity !== undefined)
Expand All @@ -134,65 +148,50 @@ export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(fun
yield* syncQueued(presence, chat.orgId, agentId).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
);
if (join.stopped.length > 0)
yield* tellStopped({ ...chat, lines: join.stopped }).pipe(
Effect.provideService(KinChatRepository, repo),
Effect.provideService(KinChatHub, hub),
Effect.ignore({ log: "Warn", message: "KinChatSharing.tellStopped" }),
);
}),
);
});

/**
* One line per agent whose person's ask this join expired, its id from the join so a retry
* posts it once. Read in the join's transaction: the aborted turn does nothing after it.
*/
/** One line per unanswered human message, even when it woke several leads. */
const stoppedLines = Effect.fnUntraced(function* (
sql: SqlClient.SqlClient,
input: { readonly orgId: KinOrgId; readonly chatId: string; readonly personId: string },
orgId: KinOrgId,
expired: ReadonlyArray<{ readonly eventId: string }>,
) {
if (expired.length === 0) return [];
const [join] = yield* sql<{ memberId: string; joinedSeq: number | null }>`
SELECT member_id AS "memberId", joined_seq AS "joinedSeq" FROM kin_chat_members
WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND principal_kind = 'person'
AND person_id = ${input.personId} AND left_at IS NULL
ORDER BY member_id LIMIT 1`;
if (join === undefined) return [];
const asked = yield* sql<{ agentId: KinAgentId; leadName: string; wakeupId: string | null }>`
SELECT DISTINCT e.agent_id AS "agentId", l.name AS "leadName", e.wakeup_id AS "wakeupId"
FROM kin_events e JOIN kin_leads l ON l.org_id = e.org_id AND l.agent_id = e.agent_id
JOIN kin_messages m ON m.org_id = e.org_id
const asked = yield* sql<{ messageId: string; wakeupId: string | null }>`
SELECT DISTINCT m.message_id AS "messageId", e.wakeup_id AS "wakeupId"
FROM kin_events e JOIN kin_messages m ON m.org_id = e.org_id
AND m.message_id = json_extract(e.json, '$.messageId')
WHERE e.org_id = ${input.orgId} AND e.event_id IN ${sql.in(expired.map((row) => row.eventId))}
WHERE e.org_id = ${orgId} AND e.event_id IN ${sql.in(expired.map((row) => row.eventId))}
AND e.tag IN ${sql.in(PERSON_ASK_TAGS)} AND m.author_kind = 'human'
ORDER BY 1, 3`;
const lines = new Map<KinAgentId, { leadName: string; partway: boolean }>();
AND NOT EXISTS (SELECT 1 FROM kin_events answered
WHERE answered.org_id = m.org_id AND answered.replied_at IS NOT NULL
AND answered.tag IN ${sql.in(PERSON_ASK_TAGS)}
AND json_extract(answered.json, '$.messageId') = m.message_id)
ORDER BY m.seq, m.message_id, e.wakeup_id`;
const lines = new Map<string, boolean>();
for (const row of asked) {
const partway =
row.wakeupId !== null &&
(yield* didVisibleWork({ orgId: input.orgId, wakeupId: KinWakeupId.make(row.wakeupId) }));
const line = lines.get(row.agentId);
lines.set(row.agentId, {
leadName: row.leadName,
partway: partway || line?.partway === true,
});
lines.get(row.messageId) === true ||
(row.wakeupId !== null &&
(yield* didVisibleWork({ orgId, wakeupId: KinWakeupId.make(row.wakeupId) })));
lines.set(row.messageId, partway);
}
return [...lines].map(([agentId, line]) => ({
return [...lines].map(([messageId, partway]) => ({
messageId: KinMessageId.make(
`kin-join-stopped:${join.memberId}:${join.joinedSeq ?? 0}:${agentId}`,
`kin-join-stopped:${NodeCrypto.createHash("sha256").update(messageId).digest("hex")}`,
),
body: stoppedByJoinNotice(line.leadName, line.partway),
body: stoppedByJoinNotice(partway),
}));
});

/** After the join commits: posts its `stoppedLines` where everyone in the chat now reads. */
export const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (input: {
const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (input: {
readonly orgId: KinOrgId;
readonly chatId: string;
readonly lines: ReadonlyArray<{ readonly messageId: KinMessageId; readonly body: string }>;
}) {
const sql = yield* SqlClient.SqlClient;
const repo = yield* KinChatRepository;
const hub = yield* KinChatHub;
for (const line of input.lines) {
Expand All @@ -217,7 +216,7 @@ export const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (in
createdAt: DateTime.formatIso(DateTime.makeUnsafe(yield* Clock.currentTimeMillis)),
editedAt: null,
});
yield* hub.publish({ type: "message.posted", orgId: input.orgId, message });
yield* sql.afterCommit(hub.publish({ type: "message.posted", orgId: input.orgId, message }));
}
});

Expand Down
Loading
Loading