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
53 changes: 31 additions & 22 deletions apps/server/src/kin/chat/KinChatService.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { environment } from "./TaskCard.testkit.ts";
import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts";
import { CommandId } from "@t3tools/contracts";
import { startWakeupRun, authorityLayer } from "./WakeupAuthority.testkit.ts";
import { startWakeupRun, authorityLayer, startAgentWakeup } from "./WakeupAuthority.testkit.ts";
import { assert, describe, it } from "@effect/vitest";
import {
AuthSessionId,
Expand Down Expand Up @@ -88,7 +88,7 @@ const state = Schema.decodeSync(KinTaskCardState)({
lastError: null,
updatedAt: timestamp,
});
const seed = Effect.gen(function* () {
const seed = Effect.fn("test.seed")(function* (notice = false) {
const repo = yield* Repository.KinChatRepository;
const service = yield* Service.KinChatService;
const identity = yield* Identity.KinIdentity.pipe(Effect.provide(identityLayer));
Expand All @@ -107,10 +107,19 @@ const seed = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id)
VALUES (${agentId}, ${person.orgId}, 'Lead', 0, '{}', '[]', ${chat.chatId})`;
yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids)
VALUES ('service-wakeup', ${person.orgId}, ${agentId}, ${threadId}, 'test', 0, 'running', '[]')`;
const run = yield* startWakeupRun(threadId, "service-wakeup");
yield* sql`UPDATE kin_wakeups SET run_id = ${run.id} WHERE wakeup_id = 'service-wakeup'`;
const prompt = notice
? undefined
: yield* service.send(person, {
chatId: chat.chatId,
body: "Owner question",
clientMessageId: "seed-human",
});
yield* startAgentWakeup({
orgId: person.orgId,
agentId,
threadId,
...(prompt === undefined ? {} : { message: prompt }),
});
yield* startWakeupRun(state.threadId!, "worker");
const agent = yield* identity.resolveAgent(caller);
return { repo, service, identity, person, agent, chat };
Expand All @@ -121,7 +130,7 @@ describe("KinChatService", () => {
"creates exactly two members, derives authors from identity, and deduplicates sends",
() =>
Effect.gen(function* () {
const { repo, service, person, agent, chat } = yield* seed;
const { repo, service, person, agent, chat } = yield* seed();
const retries = yield* Effect.all(
Array.from({ length: 5 }, () =>
service.createDirect(person, { orgId: person.orgId, agentId }),
Expand Down Expand Up @@ -162,7 +171,7 @@ describe("KinChatService", () => {
chatId: chat.chatId,
clientMessageId: "first",
body: "Evidence",
intent: "evidence",
intent: "answer",
});
assert.deepStrictEqual(posted.author, {
_tag: "agent",
Expand All @@ -177,13 +186,13 @@ describe("KinChatService", () => {
chatId: chat.chatId,
clientMessageId: "first",
body: "Evidence",
intent: "answer",
intent: "evidence",
}),
),
{ reason: "not_allowed" },
);
assert.strictEqual(posted.authorRole, "member");
assert.strictEqual(posted.seq, 2);
assert.strictEqual(posted.seq, 3);
const resumed = decodeThreadId("new-thread");
yield* repo.registerAgentThread({
orgId: agent.orgId,
Expand Down Expand Up @@ -213,7 +222,7 @@ describe("KinChatService", () => {
])
assert.include(yield* Effect.flip(operation), { reason: "invalid_state" });
assert.deepStrictEqual(
(yield* service.history(person, { chatId: chat.chatId, beforeSeq: 3, limit: 1 }))
(yield* service.history(person, { chatId: chat.chatId, beforeSeq: 4, limit: 1 }))
.messages,
[posted],
);
Expand Down Expand Up @@ -245,7 +254,7 @@ describe("KinChatService", () => {
.pipe(Effect.flip),
{ reason: "not_allowed" },
);
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`;
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`;
assert.include(
yield* service
.upsertWidget(agent, {
Expand All @@ -263,7 +272,7 @@ describe("KinChatService", () => {

it.effect("hides foreign org ids on every method and checks active membership and roles", () =>
Effect.gen(function* () {
const { repo, service, person, agent, chat } = yield* seed;
const { repo, service, person, agent, chat } = yield* seed();
const widget = yield* service.createTaskCard({
orgId: person.orgId,
chatId: chat.chatId,
Expand Down Expand Up @@ -427,7 +436,7 @@ describe("KinChatService", () => {

it.effect("creates trusted cards idempotently and enforces ownership and server fields", () =>
Effect.gen(function* () {
const { repo, service, person, agent, chat } = yield* seed;
const { repo, service, person, agent, chat } = yield* seed();
for (const caller of [agent, person])
assert.include(
yield* service
Expand Down Expand Up @@ -460,7 +469,7 @@ describe("KinChatService", () => {
);
assert.strictEqual(
(yield* repo.history({ ...chat, beforeSeq: 99, limit: 100 })).messages.length,
1,
2,
);
const anchor = Option.getOrThrow(yield* repo.getMessage(widget));
assert.include(anchor.author, { _tag: "agent", agentId: agent.agentId });
Expand All @@ -487,7 +496,7 @@ describe("KinChatService", () => {
yield* identity.registerAgentThread({ ...person, agentId: otherId, threadId: otherThread });
const sql = yield* SqlClient.SqlClient;
yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) VALUES (${otherId}, ${person.orgId}, 'Other', 0, '{}', '[]', ${chat.chatId})`;
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`;
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`;
const otherRun = yield* startWakeupRun(otherThread, "other-wakeup");
yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, run_id, model, started_at, status, event_ids) VALUES ('other-wakeup', ${person.orgId}, ${otherId}, ${otherThread}, ${otherRun.id}, 'test', 0, 'running', '[]')`;
const other = yield* identity.resolveAgent({
Expand Down Expand Up @@ -517,7 +526,7 @@ describe("KinChatService", () => {
{ reason: "not_allowed" },
);
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'other-wakeup'`;
yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE wakeup_id = 'service-wakeup'`;
yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`;
const updated = yield* service.upsertWidget(agent, {
chatId: chat.chatId,
widgetId: widget.widgetId,
Expand Down Expand Up @@ -599,7 +608,7 @@ describe("KinChatService", () => {
.pipe(Effect.flip),
{ reason: "widget_changed" },
);
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`;
yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`;
const serverThread = ThreadId.make("server-only");
yield* startWakeupRun(serverThread, "server-only");
assert.strictEqual(
Expand All @@ -613,7 +622,7 @@ describe("KinChatService", () => {
"publishes question waiting and reply resolution, rolls back atomically, and keeps read state monotonic",
() =>
Effect.gen(function* () {
const { repo, service, person, agent, chat } = yield* seed;
const { repo, service, person, agent, chat } = yield* seed(true);
const hub = yield* Hub.KinChatHub;
const events = yield* Stream.toQueue(yield* hub.subscribeForViewer(person), {
capacity: "unbounded",
Expand Down Expand Up @@ -776,7 +785,7 @@ describe("KinChatService", () => {
);
it.effect("filters every hub event against current viewer membership at delivery", () =>
Effect.gen(function* () {
const { repo, service, person, agent, chat } = yield* seed;
const { repo, service, person, agent, chat } = yield* seed(true);
const hub = yield* Hub.KinChatHub;
const viewer = yield* hub.subscribeForViewer(person);
const other = yield* repo.createChat({
Expand All @@ -802,7 +811,7 @@ describe("KinChatService", () => {
chatId: other.chatId,
body: "Private",
clientMessageId: "private",
intent: "answer",
intent: "evidence",
});
const widget = yield* service.createTaskCard({
orgId: person.orgId,
Expand Down Expand Up @@ -900,7 +909,7 @@ describe("KinChatService", () => {
"requires an owner to remove members and publishes cancelled waiting only after commit",
() =>
Effect.gen(function* () {
const { repo, service, person, chat } = yield* seed;
const { repo, service, person, chat } = yield* seed();
const hub = yield* Hub.KinChatHub;
const sql = yield* SqlClient.SqlClient;
const other = { ...person, personId: KinPersonId.make("other-person") };
Expand Down
38 changes: 33 additions & 5 deletions apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as Floor from "../floor/KinFloor.ts";
import { ServerEnvironment } from "../../environment/ServerEnvironment.ts";
import { OrchestratorV2 } from "../../orchestration-v2/Orchestrator.ts";
import * as TaskCard from "../widgets/taskCard.ts";
Expand Down Expand Up @@ -55,7 +56,10 @@ type Viewers = ReadonlyArray<PersonIdentity>;
type Caller = Identity | Viewers;
type PersonCaller = PersonIdentity | Viewers;
type ServiceError = Repository.RepositoryError;
type SendInput = KinMessagesSendInput & { readonly intent?: KinAgentIntent };
type SendInput = KinMessagesSendInput & {
readonly intent?: KinAgentIntent;
readonly floorGrant?: string | undefined;
};
type WidgetUpsertInput = {
readonly chatId: KinChatId;
readonly widgetId?: KinWidgetId | undefined;
Expand Down Expand Up @@ -190,6 +194,7 @@ const requireRecord = Effect.fn("KinChatService.requireRecord")(function* <A, E,
});

const make = Effect.gen(function* () {
const floor = yield* Floor.KinFloor;
const cards = yield* TaskCard.TaskCardIndex;
const repo = yield* Repository.KinChatRepository;
const hub = yield* Hub.KinChatHub;
Expand Down Expand Up @@ -335,6 +340,7 @@ const make = Effect.gen(function* () {
readonly widgetId: KinWidgetId | null;
readonly kind: "text" | "widget_action";
readonly publish?: boolean;
readonly floorRunId?: string | null;
readonly clientId: { readonly kind: "send" | "act"; readonly id: string } | null;
},
) {
Expand All @@ -351,14 +357,17 @@ const make = Effect.gen(function* () {
mentions: input.mentions,
replyTo: input.replyTo,
widgetId: input.widgetId,
floorRunId: null,
floorRunId: input.floorRunId ?? null,
status: "posted",
sentBy: null,
clientMessageId: input.clientId,
createdAt: yield* now,
editedAt: null,
});
if (message.messageId !== messageId || input.publish === false) return message;
if (message.messageId !== messageId) return message;
if (message.author._tag === "human")
yield* floor.open(message, yield* requireRecord(repo.getChat(member)));
if (input.publish === false) return message;
yield* hub.publish({ type: "message.posted", orgId: identity.orgId, message });
if (message.author._tag === "agent" && message.intent === "question") {
const chat = yield* requireRecord(repo.getChat(member));
Expand Down Expand Up @@ -747,15 +756,31 @@ const make = Effect.gen(function* () {
input.intent === undefined
? null
: yield* decodeIntent(input.intent).pipe(Effect.mapError(() => invalidState));
return yield* post(identity, member, {
const existing = yield* repo.findClientMessage({
orgId: identity.orgId,
chatId: request.chatId,
memberId: member.memberId,
kind: "send",
clientId: request.clientMessageId,
});
const chat = yield* requireRecord(repo.getChat(member));
const authorization =
identity._tag === "agent" && Option.isNone(existing)
? yield* floor.authorize(identity, chat, intent ?? "answer", input.floorGrant)
: { runId: null };
const message = yield* post(identity, member, {
...request,
kind: "text",
intent,
floorRunId: authorization.runId,
mentions: request.mentions ?? [],
replyTo: request.replyTo ?? null,
widgetId: null,
clientId: { kind: "send", id: request.clientMessageId },
});
if (Option.isNone(existing) && identity._tag === "agent" && authorization.runId === null)
yield* floor.recordNotice(identity, message);
return message;
}, transaction),
read: Effect.fn("KinChatService.read")(function* (identity, input) {
const request = yield* decodeRead(input).pipe(Effect.mapError(() => invalidState));
Expand Down Expand Up @@ -1130,4 +1155,7 @@ const make = Effect.gen(function* () {
});
});

export const layer = Layer.effect(KinChatService, make).pipe(Layer.provideMerge(TaskCard.layer));
export const layer = Layer.effect(KinChatService, make).pipe(
Layer.provideMerge(TaskCard.layer),
Layer.provide(Floor.layer),
);
70 changes: 70 additions & 0 deletions apps/server/src/kin/chat/WakeupAuthority.testkit.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import {
CommandId,
KinOrgId,
KinEventId,
KinWakeupId,
type KinEvent,
type KinMessage,
type KinAgentId,
MessageId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as TestClock from "effect/testing/TestClock";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as KinEventQueue from "../lead/KinEventQueue.ts";
import * as SqlClient from "effect/sql/SqlClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts";
Expand Down Expand Up @@ -72,3 +83,62 @@ export const startWakeupRun = Effect.fn("test.startWakeupRun")(function* (
});
return (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
});

export const startAgentWakeup = Effect.fn("test.startAgentWakeup")(function* (input: {
readonly orgId: KinOrgId;
readonly agentId: KinAgentId;
readonly threadId: ThreadId;
readonly message?: KinMessage;
}) {
const sql = yield* SqlClient.SqlClient;
const queue = yield* KinEventQueue.KinEventQueue;
const orchestrator = yield* Orchestrator.OrchestratorV2;
const previous = yield* sql<{
wakeup_id: string;
run_id: string | null;
}>`SELECT wakeup_id, run_id FROM kin_wakeups
WHERE org_id = ${input.orgId} AND status = 'running' ORDER BY wakeup_id`;
for (const wakeup of previous) {
yield* queue.finish({
orgId: input.orgId,
wakeupId: KinWakeupId.make(wakeup.wakeup_id),
status: "completed",
});
const projection = yield* orchestrator.getThreadProjection(input.threadId);
const run = projection.runs.find((run) => run.id === wakeup.run_id);
if (run !== undefined)
yield* orchestrator.dispatch({
type: "run.interrupt",
commandId: CommandId.make(`interrupt:${wakeup.wakeup_id}`),
threadId: input.threadId,
runId: run.id,
});
}
const wakeupId = KinWakeupId.make(SecureRandom.uuidV4Unsafe());
const base = {
orgId: input.orgId,
agentId: input.agentId,
eventId: KinEventId.make(`event:${wakeupId}`),
receivedAt: yield* DateTime.now,
dedupeKey: null,
};
const event: KinEvent =
input.message === undefined
? { ...base, _tag: "routine", provenance: { _tag: "system" }, routine: "morning_brief" }
: {
...base,
_tag: "chat.message",
provenance: input.message.author,
chatId: input.message.chatId,
messageId: input.message.messageId,
};
yield* queue.enqueue(event);
yield* TestClock.adjust(input.message === undefined ? 20_000 : 2_000);
yield* Effect.scoped(
queue.claim({ orgId: input.orgId, agentId: input.agentId, wakeupId, model: "test" }),
);
const run = yield* startWakeupRun(input.threadId, wakeupId);
yield* sql`UPDATE kin_wakeups SET thread_id = ${input.threadId}, run_id = ${run.id}
WHERE org_id = ${input.orgId} AND wakeup_id = ${wakeupId}`;
return wakeupId;
}, Effect.provide(KinEventQueue.layer));
Loading