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
6 changes: 3 additions & 3 deletions apps/mobile/src/features/chats/components/KinPresenceLine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ export function useKinPresenceNow(active: boolean): number {
export type KinStopState = "idle" | "stopping" | "failed";

/**
* What the lead is doing, in one line above the composer: pulsing dots while it has only seen
* or is starting, else its avatar and a gently breathing line while it works. The row keeps its
* What the lead is doing, in one line above the composer: pulsing dots while it is queued or
* starting, else its avatar and a gently breathing line while it works. The row keeps its
* height when empty, so a reply landing never shifts the feed.
*/
export function KinPresenceLine(props: {
Expand All @@ -75,7 +75,7 @@ export function KinPresenceLine(props: {
if (announcement !== null) AccessibilityInfo.announceForAccessibility(announcement);
}, [announcement]);
const reduceMotion = useReduceMotionEnabled();
// Motion only while a run is live and seen; Reduce Motion leaves the row still.
// Motion only while a run is live and on screen; Reduce Motion leaves the row still.
const animate = line !== null && props.visible && !reduceMotion;

const { onStop } = props;
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/kin/chat/KinChatService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1429,8 +1429,8 @@ describe("KinChatService", () => {
const working = Effect.map(Queue.take(updates), (event) =>
event._tag === "chat" ? event.chat.working : event._tag,
);
// "seen" leaves the row as it was, so the list sends nothing for it.
yield* presence.set(person.orgId, chat.chatId, { ...line, state: "seen" });
// "paused" leaves the row as it was, so the list sends nothing for it.
yield* presence.set(person.orgId, chat.chatId, { ...line, state: "paused" });
yield* presence.set(person.orgId, chat.chatId, { ...line, state: "thinking" });
assert.strictEqual(yield* working, true);
yield* presence.clear(person.orgId, chat.chatId, agentId);
Expand Down
77 changes: 41 additions & 36 deletions apps/server/src/kin/lead/ChatWake.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,13 @@ describe("ChatWake", () => {
results.map((result) => result.duplicate),
[false, true, false, false],
);
// The owner sees `seen` as soon as the message is queued, before any wake-up claims it.
// The working line shows as soon as the message is queued, before any wake-up claims it.
const presence = yield* Presence.KinPresence;
assert.deepStrictEqual(
presence
.snapshot(KinOrgId.make("a"), KinChatId.make("chat-a"))
.presence.map((line) => [line.agentId, line.state, line.wakeupId]),
[["lead-a", "seen", null]],
.presence.map((line) => [line.agentId, line.state, line.label, line.wakeupId]),
[["lead-a", "starting", "Reading memory", null]],
);
const stored = yield* storedEvents();
assert.deepStrictEqual(
Expand Down Expand Up @@ -259,41 +259,46 @@ describe("ChatWake", () => {
}).pipe(Effect.provide(services)),
);

it.effect("shows `seen` for a waking reaction and drops it once the reaction is withdrawn", () =>
Effect.gen(function* () {
yield* seed("a");
yield* storeMessage(message("a", "lead-latest", { seq: 1, agent: true }));
const { settle } = yield* start();
const hub = yield* Hub.KinChatHub;
const presence = yield* Presence.KinPresence;
const lines = () =>
presence
.snapshot(KinOrgId.make("a"), KinChatId.make("chat-a"))
.presence.map((line) => line.state);
const reaction = (removedAt: string | null) =>
hub.publish({
type: "reaction.updated",
orgId: KinOrgId.make("a"),
chatId: KinChatId.make("chat-a"),
reaction: {
it.effect(
"shows Queued for a waking reaction behind a running wake-up, gone once withdrawn",
() =>
Effect.gen(function* () {
yield* seed("a");
yield* storeMessage(message("a", "lead-latest", { seq: 1, agent: true }));
const { settle } = yield* start();
const hub = yield* Hub.KinChatHub;
const presence = yield* Presence.KinPresence;
const lines = () =>
presence
.snapshot(KinOrgId.make("a"), KinChatId.make("chat-a"))
.presence.map((line) => [line.state, line.label]);
const sql = yield* SqlClient.SqlClient;
yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, event_ids)
VALUES ('running', 'a', 'lead-a', 'fixture', 0, 'running', '[]')`;
const reaction = (removedAt: string | null) =>
hub.publish({
type: "reaction.updated",
orgId: KinOrgId.make("a"),
chatId: KinChatId.make("chat-a"),
messageId: KinMessageId.make("lead-latest"),
memberId: KinMemberId.make("owner-member-a"),
emoji: "👎",
createdAt,
removedAt,
},
woke: removedAt === null,
by: message("a", "m1").author,
});
yield* reaction(null);
yield* settle;
assert.deepStrictEqual(lines(), ["seen"]);
yield* reaction(createdAt);
yield* settle;
assert.deepStrictEqual(lines(), []);
}).pipe(Effect.provide(services)),
reaction: {
orgId: KinOrgId.make("a"),
chatId: KinChatId.make("chat-a"),
messageId: KinMessageId.make("lead-latest"),
memberId: KinMemberId.make("owner-member-a"),
emoji: "👎",
createdAt,
removedAt,
},
woke: removedAt === null,
by: message("a", "m1").author,
});
yield* reaction(null);
yield* settle;
assert.deepStrictEqual(lines(), [["starting", "Queued"]]);
yield* reaction(createdAt);
yield* settle;
assert.deepStrictEqual(lines(), []);
}).pipe(Effect.provide(services)),
);

it.effect("never wakes a lead for its own posts or after retirement, live or on catch-up", () =>
Expand Down
35 changes: 17 additions & 18 deletions apps/server/src/kin/lead/ChatWake.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
KinAgentId,
type KinChatId,
KinEventId,
KinMessageId,
KinOrgId,
Expand All @@ -23,7 +24,7 @@ import { toPersistenceSqlError } from "../../persistence/Errors.ts";
import { forkParked } from "../../serverActivation.ts";
import { KinChatHub, type KinChatHubEvent } from "../chat/KinChatHub.ts";
import { KinChatRepository } from "../chat/KinChatRepository.ts";
import { KinPresence, syncSeen } from "../reply/KinPresence.ts";
import { KinPresence, queueLabel, syncQueued } from "../reply/KinPresence.ts";
import { KinEventQueue } from "./KinEventQueue.ts";

const decodeTap = Schema.decodeUnknownEffect(
Expand All @@ -46,6 +47,17 @@ const make = Effect.gen(function* () {
const repo = yield* KinChatRepository;
const queue = yield* KinEventQueue;
const presence = yield* Effect.serviceOption(KinPresence);
// The working line shows the moment a message is accepted, before any wake-up claims it.
const showQueued = Effect.fn("KinChatWake.showQueued")(
function* (orgId: KinOrgId, chatId: KinChatId, agentId: KinAgentId) {
if (Option.isNone(presence)) return;
const label = yield* queueLabel(orgId, agentId).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
);
yield* presence.value.queued(orgId, chatId, agentId, label, yield* Clock.currentTimeMillis);
},
Effect.catchCause((cause) => Effect.logWarning("Kin queue line failed", { cause })),
);

const wake = Effect.fn("KinChatWake.wake")(
function* (message: KinMessage) {
Expand Down Expand Up @@ -111,21 +123,14 @@ const make = Effect.gen(function* () {
),
}),
);
// The first thing the sender sees, well before a wake-up claims the message.
if (queued && Option.isSome(presence))
yield* presence.value.seen(
message.orgId,
message.chatId,
agentId,
yield* Clock.currentTimeMillis,
);
if (queued) yield* showQueued(message.orgId, message.chatId, agentId);
}
},
Effect.catchCause((cause) => Effect.logError("Kin chat wake-up failed", { cause })),
);

// A waking reaction (the chat service decides) becomes `chat.reaction`; withdrawing it before
// a wake-up claims it cancels the event and its `seen`. Other reactions are feedback only.
// a wake-up claims it cancels the event and its working line. Other reactions are feedback only.
const react = Effect.fn("KinChatWake.react")(
function* (event: Extract<KinChatHubEvent, { type: "reaction.updated" }>) {
const { reaction } = event;
Expand All @@ -138,7 +143,7 @@ const make = Effect.gen(function* () {
);
if (Option.isSome(presence))
for (const row of expired)
yield* syncSeen(presence.value, reaction.orgId, KinAgentId.make(row.agentId)).pipe(
yield* syncQueued(presence.value, reaction.orgId, KinAgentId.make(row.agentId)).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
);
return;
Expand Down Expand Up @@ -176,13 +181,7 @@ const make = Effect.gen(function* () {
),
}),
);
if (queued && Option.isSome(presence))
yield* presence.value.seen(
reaction.orgId,
reaction.chatId,
agentId,
yield* Clock.currentTimeMillis,
);
if (queued) yield* showQueued(reaction.orgId, reaction.chatId, agentId);
},
Effect.catchCause((cause) => Effect.logError("Kin reaction wake-up failed", { cause })),
);
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/kin/lead/KinStop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { PersistenceSqlError, toPersistenceSqlError } from "../../persistence/Er
import * as Hub from "../chat/KinChatHub.ts";
import type { PersonIdentity } from "../chat/KinIdentity.ts";
import * as Chat from "../chat/KinChatRepository.ts";
import { KinPresence, syncSeen } from "../reply/KinPresence.ts";
import { KinPresence, syncQueued } from "../reply/KinPresence.ts";
import type * as Routines from "../triggers/routines.ts";
import * as Queue from "./KinEventQueue.ts";
import { isOrgOwner, isOrgPaused, STOP_REASON } from "./orgState.ts";
Expand Down Expand Up @@ -334,11 +334,11 @@ const make = Effect.gen(function* () {
);
if (resumed !== undefined) {
yield* publish(input.orgId, resumed);
// Messages the pause expired no longer wait, so their `seen` goes too.
// Messages the pause expired no longer wait, so their working line goes too.
if (Option.isSome(presence))
for (const lead of yield* sql<{ agentId: string }>`SELECT agent_id AS "agentId"
FROM kin_leads WHERE org_id = ${input.orgId} ORDER BY agent_id`)
yield* syncSeen(presence.value, input.orgId, KinAgentId.make(lead.agentId)).pipe(
yield* syncQueued(presence.value, input.orgId, KinAgentId.make(lead.agentId)).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
);
if (attached !== undefined) yield* attached.resume(input.orgId);
Expand Down
110 changes: 3 additions & 107 deletions apps/server/src/kin/lead/LeadPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,6 @@ const event = (messageId: string) =>
dedupeKey: null,
provenance: { _tag: "system" },
});
// Sized like a lived-in memory: rules of about 4k characters and an index at its 200-line cap.
const fullRules =
"- Ask the owner before spending money, contacting people or merging code.\n".repeat(55);
const fullIndex = [
"As of 2026-11-08T00:00:00.000Z",
...Array.from(
{ length: 199 },
(_, i) =>
`- commitments/item-${i}.md: follow up with the design partner on onboarding, due Friday`,
),
].join("\n");
// The repository only takes a lead's message inside its running wake-up; these are history.
const insertLeadMessage = Effect.fn("test.insertLeadMessage")(function* (id: string, body: string) {
const sql = yield* SqlClient.SqlClient;
Expand Down Expand Up @@ -119,11 +108,9 @@ const memory = Layer.succeed(
purgeInFlight: () => Effect.die("Unused"),
historyGeneration: () => Effect.die("Unused"),
readPromptSnapshot: (org, head) =>
org === orgId && head === "head-full"
? Effect.succeed({ rules: fullRules, index: fullIndex })
: org !== orgId || !["head-one", "head-two"].includes(head)
? Effect.fail(new Memory.MemoryError({ orgId: org, operation: "promptSnapshot" }))
: Effect.succeed({ rules: `Invented rules ${head}`, index: `Invented index ${head}` }),
org !== orgId || !["head-one", "head-two"].includes(head)
? Effect.fail(new Memory.MemoryError({ orgId: org, operation: "promptSnapshot" }))
: Effect.succeed({ rules: `Invented rules ${head}`, index: `Invented index ${head}` }),
ensureCheckouts: () => Effect.die("Unused"),
prepareWakeup: () => Effect.die("Unused"),
readIndex: () => Effect.die("Unused"),
Expand Down Expand Up @@ -714,100 +701,9 @@ it.effect(
const recent = built.split("# Recent chat (data, oldest first)\n\n")[1]?.split("# Events")[0];
expect(recent).toMatch(/"from":"owner".*Did the release go out\?.*Also check the docs\./);
expect(recent).not.toContain("Current question");
// A warm session saw everything up to its last seq, and its own words, so only the rest goes.
yield* insertLeadMessage("mine", "It went out at noon.");
const warm = yield* prompt.build({
...input,
events: [event("now")],
lane: { chatId, mode: "reply" },
since: { index: "Invented index head-one", chatSeq: 1 },
});
expect(warm).not.toContain("# Standing rules");
expect(warm).not.toContain("# Memory index");
expect(warm).not.toContain("# Group rules");
expect(warm).toContain("Standing rules and the memory index are unchanged");
const since = warm.split("# Chat since your last wake-up (data, oldest first)\n\n")[1];
expect(since?.split("# Events")[0]).toMatch(/Also check the docs\./);
expect(since).not.toMatch(/Did the release go out|It went out at noon/);
expect(since?.split("# Events")[1]).toContain("Current question");
const moved = yield* prompt.build({
...input,
memoryHead: "head-two",
events: [event("now")],
since: { index: "Invented index head-one", chatSeq: 3 },
});
expect(moved).not.toContain("Invented rules");
expect(moved).toContain(
'{"removed":["Invented index head-one"],"added":["Invented index head-two"]}',
);
}).pipe(Effect.provide(layer)),
);

it.effect("a warm continuation is a fraction of a cold wake-up's message", () =>
Effect.gen(function* () {
const repo = yield* seed;
yield* repo.insertAgent({
orgId,
agentId,
displayName: "Fixture lead",
role: "lead",
ownerPersonId: personId,
createdAt: timestamp,
});
for (const [id, principal, role] of [
[memberId, { _tag: "person", personId }, "owner"],
[KinMemberId.make("lead-member"), { _tag: "agent", agentId }, "member"],
] as const)
yield* repo.addMember({
orgId,
chatId,
memberId: id,
principal,
role,
joinedAt: timestamp,
leftAt: null,
mutedUntil: null,
});
for (let i = 1; i <= 21; i++) {
const body = `Message ${i}: ${"the launch plan needs one more pass on pricing and the onboarding copy. ".repeat(4)}`;
if (i % 2 === 0) yield* insertLeadMessage(`m${i}`, body);
else
yield* repo.insertMessage({
orgId,
chatId,
messageId: KinMessageId.make(`m${i}`),
author: { _tag: "human", personId, memberId },
kind: "text",
body,
intent: null,
mentions: [],
replyTo: null,
widgetId: null,
floorRunId: null,
status: "posted",
sentBy: null,
createdAt: timestamp,
editedAt: null,
clientMessageId: null,
});
}
const prompt = yield* KinLeadPrompt;
const wake = { ...input, memoryHead: "head-full", events: [event("m21")] };
const lane = { chatId, mode: "reply" } as const;
const cold = yield* prompt.build({ ...wake, lane });
const warm = yield* prompt.build({ ...wake, lane, since: { index: fullIndex, chatSeq: 20 } });
const wrote = yield* prompt.build({
...wake,
lane,
since: { index: fullIndex.replace(/\n[^\n]*$/, "\n- claims/old.md: retired"), chatSeq: 20 },
});
// About four characters a token: cold is about 7.6k tokens of message, warm about 300.
expect(cold.length).toBeGreaterThan(25_000);
expect(warm.length).toBeLessThan(1_500);
expect(wrote.length).toBeLessThan(1_800);
}).pipe(Effect.provide(layer)),
);

it.effect(
"carries the owner's feedback reactions since the last finished wake-up, and a 👎 asks what was wrong",
() =>
Expand Down
Loading