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
57 changes: 56 additions & 1 deletion apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ import { validateState } from "../widgets/registry.ts";
import { deferralCardActions, deferralCardActionsReady } from "../widgets/deferralCard.ts";
import * as ChoiceCard from "../widgets/choiceCard.ts";
import { undoDeferral } from "../triggers/KinTriggerService.ts";
import * as ScheduledTasks from "../widgets/scheduledTaskCard.ts";
import * as ReminderCard from "../widgets/reminderCard.ts";
import * as Hub from "./KinChatHub.ts";
import { KinPresence } from "../reply/KinPresence.ts";
import * as Repository from "./KinChatRepository.ts";
Expand Down Expand Up @@ -249,6 +251,14 @@ const requireRecord = Effect.fn("KinChatService.requireRecord")(function* <A, E,
return Option.isSome(value) ? value.value : yield* notFound;
});

/** A card tap's failure as the client sees it: the refusal, a storage error, or a stale card. */
const cardTapError = (cause: KinChatError | SqlError.SqlError | Schema.SchemaError) =>
isKinChatError(cause)
? cause
: SqlError.isSqlError(cause)
? toPersistenceSqlError("KinChatService.cardTap")(cause)
: new KinChatError({ reason: "invalid_state", message: "Invalid widget state." });

const taskCardWidgetId = (input: { readonly chatId: KinChatId; readonly threadId: ThreadId }) =>
encodeAction([input.chatId, input.threadId]).pipe(
Effect.orDie,
Expand Down Expand Up @@ -477,12 +487,23 @@ const make = Effect.gen(function* () {
reaction: { readonly emoji: KinReactionEmoji } | null,
) {
const choice = widget.type === "choice" ? yield* ChoiceCard.readChoice(widget, request) : null;
const reminder =
widget.type === "reminder"
? yield* ReminderCard.describeReminderTap(widget, request.actionId, request.value)
: null;
const scheduled =
widget.type === "scheduled_task"
? yield* ScheduledTasks.describeScheduledTaskTap(widget, request.actionId, request.value)
: null;
const tap = choice ?? reminder ?? scheduled;
const body = yield* encodeAction({
widgetId: request.widgetId,
revision: request.revision,
actionId: request.actionId,
...(request.value === undefined ? {} : { value: request.value }),
...(choice === null ? {} : { text: choice.text }),
...(tap === null ? {} : { text: tap.text }),
// The server finished this tap itself, so it doesn't wake the lead.
...((reminder ?? scheduled)?.wake === false ? { handled: true } : {}),
}).pipe(Effect.mapError(() => invalidState));
const previous = yield* repo.findClientMessage({
...member,
Expand Down Expand Up @@ -535,6 +556,34 @@ const make = Effect.gen(function* () {
hub.publish({ type: "widget.updated", orgId: identity.orgId, widget: closed }),
);
}
if (reminder !== null || scheduled !== null) {
const nowMs = yield* Clock.currentTimeMillis;
let applied: { readonly state: unknown; readonly closed: boolean } | null = null;
if (reminder !== null) {
const state = yield* ReminderCard.applyReminderTap(widget, reminder, nowMs).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
Effect.mapError(cardTapError),
);
applied = state === null ? null : { state, closed: false };
} else if (scheduled !== null)
applied = yield* ScheduledTasks.applyScheduledTaskTap(widget, scheduled, nowMs).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
Effect.mapError(cardTapError),
);
if (applied !== null) {
const at = yield* now;
const updated = yield* repo.updateWidget({
...widget,
state: applied.state,
expectedRevision: widget.revision,
closedAt: applied.closed ? at : widget.closedAt,
updatedAt: at,
});
yield* sql.afterCommit(
hub.publish({ type: "widget.updated", orgId: identity.orgId, widget: updated }),
);
}
}
const answer =
choice === null
? null
Expand Down Expand Up @@ -1392,6 +1441,12 @@ const make = Effect.gen(function* () {
)
return yield* invalidState;
}
// Reminders and scheduled tasks act for the owner, so only the owner taps them.
if (
(widget.type === "reminder" || widget.type === "scheduled_task") &&
member.role !== "owner"
)
return yield* notAllowed;
// Any writing member of the card's chat may undo; the other taps wait on the dispatcher.
if (
widget.type === "deferral" &&
Expand Down
13 changes: 8 additions & 5 deletions apps/server/src/kin/lead/ChatWake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ import { KinPresence } from "../reply/KinPresence.ts";
import { KinEventQueue } from "./KinEventQueue.ts";

const decodeTap = Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.Struct({ actionId: TrimmedNonEmptyString })),
Schema.fromJsonString(
Schema.Struct({ actionId: TrimmedNonEmptyString, handled: Schema.optional(Schema.Boolean) }),
),
);
// Matches the resume expiry: older unanswered messages are not worth a wake-up after downtime.
const CATCH_UP_WINDOW = { hours: 24 } as const;
Expand Down Expand Up @@ -64,12 +66,13 @@ const make = Effect.gen(function* () {
);
const targets = mentioned.length > 0 ? mentioned : leads.slice(0, 1);
if (targets.length === 0) return;
const actionId =
const tap =
message.kind === "widget_action"
? (yield* decodeTap(message.body).pipe(Effect.option)).pipe(
Option.map((tap) => tap.actionId),
)
? yield* decodeTap(message.body).pipe(Effect.option)
: Option.none();
// A tap the server finished alone, such as Snooze or Pause, is not the lead's to answer.
if (Option.isSome(tap) && tap.value.handled === true) return;
const actionId = tap.pipe(Option.map((value) => value.actionId));
if (message.kind === "widget_action" && Option.isNone(actionId))
return yield* Effect.logWarning("Kin widget action has no readable action id", {
orgId: message.orgId,
Expand Down
50 changes: 50 additions & 0 deletions apps/server/src/kin/lead/LeadDelivery.testkit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { KinOrgId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));

/**
* Stands in for the lead's wake-up for one queued event: it claims the event, posts `body` in
* the lane as the lead when given, and ends `completed` or `failed`. Returns the message id.
*/
export const leadWakeup = Effect.fn("test.leadWakeup")(function* (input: {
readonly orgId: KinOrgId;
readonly eventId: string;
readonly chatId: string;
readonly body?: string;
readonly status?: "completed" | "failed";
}) {
const sql = yield* SqlClient.SqlClient;
const now = yield* Clock.currentTimeMillis;
const status = input.status ?? "completed";
const wakeupId = `wakeup-${input.eventId}`;
const [lead] = yield* sql<{ agentId: string; ownerPersonId: string; memberId: string }>`
SELECT e.agent_id AS "agentId", a.owner_person_id AS "ownerPersonId", m.member_id AS "memberId"
FROM kin_events e
JOIN kin_agents a ON a.org_id = e.org_id AND a.agent_id = e.agent_id
JOIN kin_chat_members m ON m.org_id = e.org_id AND m.chat_id = ${input.chatId}
AND m.principal_kind = 'agent' AND m.agent_id = e.agent_id
WHERE e.org_id = ${input.orgId} AND e.event_id = ${input.eventId} ORDER BY e.event_id`;
if (lead === undefined) return yield* Effect.die("no queued event for that lead and chat");
yield* sql`INSERT INTO kin_wakeups (org_id, wakeup_id, agent_id, model, started_at, ended_at,
status, event_ids)
VALUES (${input.orgId}, ${wakeupId}, ${lead.agentId}, 'fixture', ${now}, ${now + 2_000},
${status}, '[]')`;
yield* sql`UPDATE kin_events SET state = ${status === "completed" ? "done" : "failed"},
wakeup_id = ${wakeupId}
WHERE org_id = ${input.orgId} AND event_id = ${input.eventId}`;
if (input.body === undefined) return null;
const messageId = `lead-message-${input.eventId}`;
const [chat] = yield* sql<{ seq: number }>`UPDATE kin_chats SET last_seq = last_seq + 1
WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} RETURNING last_seq AS seq`;
yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind,
author_agent_id, author_owner_person_id, author_thread_id, author_member_id, author_role,
kind, body, intent, mentions_json, status, created_at)
VALUES (${messageId}, ${input.orgId}, ${input.chatId}, ${chat?.seq ?? 1}, 'agent',
${lead.agentId}, ${lead.ownerPersonId}, 'thread-fixture', ${lead.memberId}, 'member',
'text', ${input.body}, 'evidence', '[]', 'posted', ${iso(now + 1_000)})`;
return messageId;
});
Loading