diff --git a/apps/mobile/src/features/chats/KinChatScreen.tsx b/apps/mobile/src/features/chats/KinChatScreen.tsx index cb0ad49c09369..ab28cb39fcfc3 100644 --- a/apps/mobile/src/features/chats/KinChatScreen.tsx +++ b/apps/mobile/src/features/chats/KinChatScreen.tsx @@ -14,6 +14,7 @@ import { EnvironmentId, KinChatId, type KinChatHistoryInput, + type KinChatActivity, type KinChatHistoryResult, type KinMessage, } from "@t3tools/contracts"; @@ -23,7 +24,7 @@ import * as Schema from "effect/Schema"; import { Atom, type AsyncResult } from "effect/reactivity"; import { KeyboardAwareLegendList, useKeyboardChatComposerInset } from "@legendapp/list/keyboard"; import { useEffect, useRef, useState, type ComponentPropsWithRef } from "react"; -import { AppState, Platform, View, type ViewInstance } from "react-native"; +import { AccessibilityInfo, AppState, Platform, View, type ViewInstance } from "react-native"; import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller"; import Animated from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -51,6 +52,7 @@ import { kinDraftKey, } from "./components/KinComposer"; import { KinFoldLine } from "./components/KinFoldLine"; +import { KinActivityRow, kinActivityLabel } from "./components/KinActivityRow"; import { KinDayLine, KinMessageBubble, @@ -61,6 +63,7 @@ import { buildKinFeedRows, initialKinPaging, kinActivePaging, + kinActivityWorking, kinChatScreenState, kinChatStatusLine, kinEarlierPage, @@ -69,6 +72,7 @@ import { kinMarkReadRearms, kinRowSeq, kinSeqToMarkRead, + kinShownActivity, kinUnseenCount, latestKinSeq, mergeKinFeed, @@ -276,7 +280,15 @@ function KinChatPage(props: { const navigation = useNavigation(); const topInset = useContentTopInset(); const { state } = props; - const subtitle = state._tag === "ready" ? kinChatStatusLine(state.chat.value.widgets) : null; + const shownActivity = + state._tag === "ready" + ? kinShownActivity(state.chat.value.activity, state.chat.value.messages) + : null; + const subtitle = + state._tag === "ready" + ? (kinChatStatusLine(state.chat.value.widgets) ?? + (shownActivity !== null && kinActivityWorking(shownActivity) ? "Working…" : null)) + : null; return ( navigation.goBack()} /> @@ -414,7 +426,13 @@ const SEEN_ROW_CONFIGS = [ type KinChatRow = | KinFeedRow - | { readonly type: "pending"; readonly key: string; readonly entry: KinOutboxEntry }; + | { readonly type: "pending"; readonly key: string; readonly entry: KinOutboxEntry } + | { + readonly type: "activity"; + readonly key: string; + readonly activity: KinChatActivity; + readonly agentName: string; + }; function KinChatFeed(props: { readonly orgId: string; @@ -510,8 +528,14 @@ function KinChatFeed(props: { const { messages } = mergeKinFeed(streamed, { ...emptyKinChat, messages: acked }); const widgets = new Map(streamed.widgets.map((widget) => [widget.widgetId, widget])); const feedRows = buildKinFeedRows(messages, props.viewer, expandedRuns, new Date(dayStartMs)); + const activity = kinShownActivity(live.activity, messages); + const activityAgent = + activity === null + ? "" + : (props.viewer.agentNames.get(activity.agentId) ?? props.agentName ?? "Your lead"); + // Last in the data, so the feed follows it to the end like a new message. const rows: ReadonlyArray = - pending.length === 0 + pending.length === 0 && activity === null ? feedRows : [ ...feedRows, @@ -520,7 +544,24 @@ function KinChatFeed(props: { key: `pending:${entry.clientMessageId}`, entry, })), + ...(activity === null + ? [] + : [{ type: "activity" as const, key: "activity", activity, agentName: activityAgent }]), ]; + // Working phases read as one status; a change of meaning (waiting, failed, too late) speaks again. + const announceKey = + activity === null + ? null + : `${activity.agentId}:${kinActivityWorking(activity) ? "working" : activity.phase}`; + const announced = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells VoiceOver and TalkBack once per status, not on each phase or timer + useEffect(() => { + const previous = announced.current; + announced.current = announceKey; + if (announceKey === null || activity === null || previous === announceKey) return; + AccessibilityInfo.announceForAccessibility(kinActivityLabel(activity, activityAgent)); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- the key is the announcement's identity + }, [announceKey]); const followsEnd = kinFollowsEnd(follow); const unseen = followsEnd ? 0 : kinUnseenCount(messages, follow.seenSeq, props.viewer.personId); const loading = paging.request !== null; @@ -603,7 +644,9 @@ function KinChatFeed(props: { const markSeen = ({ viewableItems }: OnViewableItemsChangedInfo) => { const seq = Math.max( 0, - ...viewableItems.map((token) => (token.item.type === "pending" ? 0 : kinRowSeq(token.item))), + ...viewableItems.map((token) => + token.item.type === "pending" || token.item.type === "activity" ? 0 : kinRowSeq(token.item), + ), ); if (seq > 0) transition({ type: "seen", seq }); }; @@ -661,6 +704,8 @@ function KinChatFeed(props: { ); case "day": return ; + case "activity": + return ; } }; diff --git a/apps/mobile/src/features/chats/components/KinActivityRow.tsx b/apps/mobile/src/features/chats/components/KinActivityRow.tsx new file mode 100644 index 0000000000000..79db3c709f824 --- /dev/null +++ b/apps/mobile/src/features/chats/components/KinActivityRow.tsx @@ -0,0 +1,62 @@ +import type { KinChatActivity } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; +import { View } from "react-native"; + +import { AppActivityIndicator } from "../../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../../components/ui/AppText"; +import { useReduceMotionEnabled } from "../../../lib/appState"; +import { kinActivityCopy, kinActivityWorking, kinStillWorkingIn } from "../state/kinChatFeed"; + +const timeFormat = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }); +const formatTime = (epochMs: number) => timeFormat.format(new Date(epochMs)); + +/** The row's spoken text, also announced by the feed. */ +export const kinActivityLabel = ( + activity: KinChatActivity, + agentName: string, + stillWorking = false, +) => `${agentName}: ${kinActivityCopy({ activity, agentName, stillWorking, formatTime })}`; + +/** The lead's status at the feed's end, in its bubble position. The feed announces it. */ +export function KinActivityRow(props: { + readonly activity: KinChatActivity; + readonly agentName: string; +}) { + const { activity } = props; + const reduceMotion = useReduceMotionEnabled(); + const phaseKey = `${activity.agentId}:${activity.phase}:${activity.since}`; + const [stillKey, setStillKey] = useState(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- one timer per phase marks it long-running; no interval or animation + useEffect(() => { + const wait = kinStillWorkingIn(activity, Date.now()); + if (wait === null) return; + const timer = setTimeout(() => setStillKey(phaseKey), wait); + return () => clearTimeout(timer); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- the key names the phase the timer belongs to + }, [phaseKey]); + const copy = kinActivityCopy({ + activity, + agentName: props.agentName, + stillWorking: stillKey === phaseKey, + formatTime, + }); + const busy = activity.phase === "queued" || kinActivityWorking(activity); + + return ( + + + {props.agentName} + + + {busy && !reduceMotion ? : null} + + {copy} + + + + ); +} diff --git a/apps/mobile/src/features/chats/state/kinChatFeed.test.ts b/apps/mobile/src/features/chats/state/kinChatFeed.test.ts index 8e4928324e9b4..b5590946cec26 100644 --- a/apps/mobile/src/features/chats/state/kinChatFeed.test.ts +++ b/apps/mobile/src/features/chats/state/kinChatFeed.test.ts @@ -1,4 +1,10 @@ -import type { EnvironmentId, KinMessage, KinWidget } from "@t3tools/contracts"; +import type { + EnvironmentId, + KinAgentId, + KinChatActivity, + KinMessage, + KinWidget, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; @@ -16,6 +22,8 @@ import { initialKinPaging, KIN_HISTORY_PAGE_SIZE, kinActivePaging, + kinActivityCopy, + KIN_STILL_WORKING_MS, kinChatScreenState, kinChatStatusLine, kinDayLabel, @@ -29,6 +37,8 @@ import { kinMarkReadRearms, kinRowSeq, kinSeqToMarkRead, + kinShownActivity, + kinStillWorkingIn, kinUnseenCount, mergeKinFeed, type KinFeedRow, @@ -634,3 +644,82 @@ describe("kinChatStatusLine", () => { ).toBe("Working on 2 tasks"); }); }); + +describe("lead activity", () => { + const since = Date.parse("2026-11-08T09:00:00.000Z"); + const activity = (phase: KinChatActivity["phase"], extra: Partial = {}) => + ({ agentId: KIN_FIXTURE_AGENT as KinAgentId, phase, since, ...extra }) as KinChatActivity; + const copy = (value: KinChatActivity, stillWorking = false) => + kinActivityCopy({ + activity: value, + agentName: "Tech lead", + stillWorking, + formatTime: () => "9:00", + }); + + it("says what the lead is doing, from the owner's side", () => { + expect( + ( + [ + "queued", + "budget", + "paused", + "started", + "notes_read", + "notes_write", + "delegating", + "approval", + "scheduling", + "failed", + "reply_late", + ] as const + ).map((phase) => copy(activity(phase))), + ).toEqual([ + "Waiting for Tech lead…", + "Paused: Tech lead's budget for today is used up.", + "Kin is paused. Messages wait until you resume it.", + "Tech lead is reading your message…", + "Checking its notes…", + "Saving to its notes…", + "Handing work to a worker…", + "Preparing something for you to approve…", + "Scheduling a follow-up…", + "Tech lead couldn't finish. Send your message again to retry.", + "Tech lead's reply came too late to post. Send your message again.", + ]); + expect(copy(activity("budget", { resumesAt: since + 1 }))).toBe( + "Paused: Tech lead's budget for today is used up. It resumes at 9:00.", + ); + expect(copy(activity("notes_read"), true)).toBe("Checking its notes… Still working."); + expect(copy(activity("failed"), true)).toBe( + "Tech lead couldn't finish. Send your message again to retry.", + ); + }); + + it("marks only a working phase long-running, once, after 45 seconds", () => { + expect(kinStillWorkingIn(activity("started"), since + 10_000)).toBe( + KIN_STILL_WORKING_MS - 10_000, + ); + expect(kinStillWorkingIn(activity("started"), since + 60_000)).toBe(0); + expect(kinStillWorkingIn(activity("queued"), since)).toBeNull(); + expect(kinStillWorkingIn(activity("failed"), since)).toBeNull(); + }); + + it("hides when the reply lands, and a failure once someone writes again", () => { + const reply = agentMessage(10, { createdAt: "2026-11-08T09:00:30.000Z" }); + const earlier = agentMessage(9, { createdAt: "2026-11-08T08:59:00.000Z" }); + const owner = { + ...all.find((m) => m.author._tag === "human")!, + seq: 11, + createdAt: "2026-11-08T09:01:00.000Z", + }; + expect(kinShownActivity(null, [])).toBeNull(); + expect(kinShownActivity(activity("idle"), [])).toBeNull(); + expect(kinShownActivity(activity("started"), [earlier])?.phase).toBe("started"); + expect(kinShownActivity(activity("notes_read"), [earlier, reply])).toBeNull(); + expect(kinShownActivity(activity("queued"), [reply])?.phase).toBe("queued"); + expect(kinShownActivity(activity("failed"), [reply])?.phase).toBe("failed"); + expect(kinShownActivity(activity("failed"), [reply, owner])).toBeNull(); + expect(kinShownActivity(activity("reply_late"), [reply, owner])).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/chats/state/kinChatFeed.ts b/apps/mobile/src/features/chats/state/kinChatFeed.ts index fc52090391e35..17dcbf8a70217 100644 --- a/apps/mobile/src/features/chats/state/kinChatFeed.ts +++ b/apps/mobile/src/features/chats/state/kinChatFeed.ts @@ -2,6 +2,8 @@ import { EnvironmentAuthorizationError, KinTaskCardState, type EnvironmentId, + type KinChatActivity, + type KinChatActivityPhase, type KinChatHistoryInput, type KinChatId, type KinMessage, @@ -517,6 +519,88 @@ export function kinChatStatusLine(widgets: ReadonlyArray): string | n return working === 1 ? "Working on 1 task" : `Working on ${working} tasks`; } +// Lead activity + +/** Phases of a running wake-up; queued, paused and the end states are not "working". */ +const WORKING_PHASES: ReadonlySet = new Set([ + "started", + "notes_read", + "notes_write", + "delegating", + "approval", + "scheduling", +]); +export const KIN_STILL_WORKING_MS = 45_000; + +export const kinActivityWorking = (activity: KinChatActivity) => WORKING_PHASES.has(activity.phase); + +/** + * The activity the feed's end shows, or null. A working phase hides once the lead has posted + * since it began: the reply landed, and its next tool call brings the row back. A failure or a + * late reply hides once someone writes again. + */ +export function kinShownActivity( + activity: KinChatActivity | null | undefined, + messages: ReadonlyArray, +): KinChatActivity | null { + if (!activity || activity.phase === "idle") return null; + const working = kinActivityWorking(activity); + if (!working && activity.phase !== "failed" && activity.phase !== "reply_late") return activity; + const latest = messages.findLast((message) => + working + ? message.author._tag === "agent" && message.author.agentId === activity.agentId + : message.author._tag === "human", + ); + return latest !== undefined && Date.parse(latest.createdAt) >= activity.since ? null : activity; +} + +/** Milliseconds until a working phase reads "Still working", or null when it never will. */ +export function kinStillWorkingIn(activity: KinChatActivity, nowMs: number): number | null { + if (!kinActivityWorking(activity)) return null; + return Math.max(0, activity.since + KIN_STILL_WORKING_MS - nowMs); +} + +/** What the lead is doing, from the owner's side. */ +export function kinActivityCopy(input: { + readonly activity: KinChatActivity; + readonly agentName: string; + readonly stillWorking: boolean; + readonly formatTime: (epochMs: number) => string; +}): string { + const { activity, agentName: name } = input; + const text = (() => { + switch (activity.phase) { + case "queued": + return `Waiting for ${name}…`; + case "budget": + return activity.resumesAt === undefined + ? `Paused: ${name}'s budget for today is used up.` + : `Paused: ${name}'s budget for today is used up. It resumes at ${input.formatTime(activity.resumesAt)}.`; + case "paused": + return "Kin is paused. Messages wait until you resume it."; + case "started": + return `${name} is reading your message…`; + case "notes_read": + return "Checking its notes…"; + case "notes_write": + return "Saving to its notes…"; + case "delegating": + return "Handing work to a worker…"; + case "approval": + return "Preparing something for you to approve…"; + case "scheduling": + return "Scheduling a follow-up…"; + case "failed": + return `${name} couldn't finish. Send your message again to retry.`; + case "reply_late": + return `${name}'s reply came too late to post. Send your message again.`; + case "idle": + return ""; + } + })(); + return input.stillWorking && kinActivityWorking(activity) ? `${text} Still working.` : text; +} + /** The viewer and agent names from the host's `kin.orgs.list` answer. */ export function kinFeedViewer(orgs: KinOrgsListResult | null, orgId: string | null): KinFeedViewer { if (orgs === null) return { personId: null, agentNames: new Map() }; diff --git a/apps/mobile/src/features/chats/state/kinInboxModel.test.ts b/apps/mobile/src/features/chats/state/kinInboxModel.test.ts index bcc33271863cd..31d909702897d 100644 --- a/apps/mobile/src/features/chats/state/kinInboxModel.test.ts +++ b/apps/mobile/src/features/chats/state/kinInboxModel.test.ts @@ -1,4 +1,5 @@ import type { + KinAgentId, KinChatId, KinChatMember, KinChatSummary, @@ -307,6 +308,26 @@ describe("kin chat feed", () => { expect(applyKinChatEvent(state, { _tag: "member", member: member(at(4)) }).left).toBe(true); }); + it("holds the lead's activity from the stream and its snapshots, and clears it on idle", () => { + const working = { agentId: "lead" as KinAgentId, phase: "started", since: 1 } as const; + let state = applyKinChatEvent(emptyKinChat, { _tag: "activity", ...working }); + expect(state.activity).toEqual(working); + // A repeat changes nothing; an older host's backlog, without the field, keeps it. + expect(applyKinChatEvent(state, { _tag: "activity", ...working })).toBe(state); + expect(applyKinChatEvent(state, backlog([], 0))).toBe(state); + state = applyKinChatEvent(state, { _tag: "activity", ...working, phase: "notes_read" }); + expect(state.activity?.phase).toBe("notes_read"); + // A reconnect's snapshot says the wake-up ended while away. + expect(applyKinChatEvent(state, { ...backlog([], 0), activity: null }).activity).toBeNull(); + expect( + applyKinChatEvent(state, { _tag: "reset", lastSeq: 9, activity: working }).activity, + ).toEqual(working); + expect( + applyKinChatEvent(state, { _tag: "activity", ...working, phase: "idle", since: 2 }).activity, + ).toBeNull(); + expect(trimKinChatForCache(state).activity).toBeNull(); + }); + it("moves read marks forward only", () => { let state = applyKinChatEvent(emptyKinChat, { _tag: "read", memberId: "me" as never, seq: 5 }); state = applyKinChatEvent(state, { _tag: "read", memberId: "me" as never, seq: 3 }); diff --git a/apps/mobile/src/features/chats/state/kinInboxModel.ts b/apps/mobile/src/features/chats/state/kinInboxModel.ts index 45c4e6721731e..0338c2e7d20b9 100644 --- a/apps/mobile/src/features/chats/state/kinInboxModel.ts +++ b/apps/mobile/src/features/chats/state/kinInboxModel.ts @@ -1,4 +1,5 @@ import { + KinChatActivity, KinChatSummary, KinMessage, KinWaitingItem, @@ -111,6 +112,8 @@ export const KinChatState = Schema.Struct({ /** The last backlog's `lastChangeSeq`; the `afterChangeSeq` that replays edits made offline. */ changeSeq: Schema.Number, reads: Schema.Record(Schema.String, Schema.Number), + /** What the lead's wake-up is doing for this chat; null when nothing. Never cached. */ + activity: Schema.optional(Schema.NullOr(KinChatActivity)), /** The server reported a gap of more than 200; reload the latest page with history. */ needsHistoryReload: Schema.Boolean, /** The viewer left; the stream has ended. Never cached. */ @@ -217,15 +220,18 @@ export function applyKinChatEvent(state: KinChatState, event: KinChatStreamEvent const contiguousSeq = advanceContiguous(messages, filled); // Only a fully applied backlog moves it; live events keep this snapshot cursor. const changeSeq = event.lastChangeSeq ?? state.changeSeq; + // Older hosts send no activity; keep what the chat holds. + const activity = event.activity === undefined ? state.activity : event.activity; if ( messages === state.messages && widgets === state.widgets && contiguousSeq === state.contiguousSeq && - changeSeq === state.changeSeq + changeSeq === state.changeSeq && + sameActivity(activity, state.activity) ) { return state; } - return { ...state, messages, widgets, contiguousSeq, changeSeq }; + return { ...state, messages, widgets, contiguousSeq, changeSeq, activity }; } case "reset": return { @@ -235,7 +241,13 @@ export function applyKinChatEvent(state: KinChatState, event: KinChatStreamEvent contiguousSeq: event.lastSeq, changeSeq: event.lastChangeSeq ?? 0, needsHistoryReload: true, + activity: event.activity === undefined ? state.activity : event.activity, }; + case "activity": { + const { _tag, ...held } = event; + const activity = held.phase === "idle" ? null : held; + return sameActivity(activity, state.activity) ? state : { ...state, activity }; + } case "message": { const messages = mergeMessages(state.messages, [event.message], streamFloor(state)); if (messages === state.messages) return state; @@ -259,6 +271,19 @@ export function applyKinChatEvent(state: KinChatState, event: KinChatStreamEvent } } +function sameActivity( + a: KinChatActivity | null | undefined, + b: KinChatActivity | null | undefined, +): boolean { + if (!a || !b) return (a ?? null) === (b ?? null); + return ( + a.agentId === b.agentId && + a.phase === b.phase && + a.since === b.since && + a.resumesAt === b.resumesAt + ); +} + /** A message from outside the stream, such as a send reply. It never advances `contiguousSeq`. */ export function addKinChatMessage(state: KinChatState, message: KinMessage): KinChatState { return { ...state, messages: mergeMessages(state.messages, [message]) }; @@ -282,6 +307,8 @@ export function trimKinChatForCache(state: KinChatState): KinChatState { ...state, messages, widgets: state.widgets.filter((widget) => kept.has(widget.messageId)), + // A cached "working" would be stale by the next open; the stream's backlog brings it back. + activity: null, left: false, closed: null, }; diff --git a/apps/server/src/kin/approvals/mcp.ts b/apps/server/src/kin/approvals/mcp.ts index 0f1c9583dbb0f..dfe4731671008 100644 --- a/apps/server/src/kin/approvals/mcp.ts +++ b/apps/server/src/kin/approvals/mcp.ts @@ -12,6 +12,7 @@ import { McpInvocationContext } from "../../mcp/McpInvocationContext.ts"; import * as McpToolAccess from "../../mcp/McpToolAccess.ts"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; +import { announceToolPhase } from "../mcp/toolPhase.ts"; import * as RequestAction from "./RequestAction.ts"; // Reads `KinIdentity`, which the Kin MCP endpoint provides per call: `KinServer` reaches the judge. @@ -70,6 +71,7 @@ const handlers = McpToolAccess.toLayer( isKinChatError(error) && error.reason === "not_allowed" ? notALead : unavailable, ), ); + yield* announceToolPhase("approval"); return yield* requests.request(agent, input); }), ), diff --git a/apps/server/src/kin/chat/KinChatHub.test.ts b/apps/server/src/kin/chat/KinChatHub.test.ts index 7e5da46a31024..5f4a3bc30ba13 100644 --- a/apps/server/src/kin/chat/KinChatHub.test.ts +++ b/apps/server/src/kin/chat/KinChatHub.test.ts @@ -1,5 +1,5 @@ import { assert, it } from "@effect/vitest"; -import { KinChatId, KinMemberId, KinOrgId, KinPersonId } from "@t3tools/contracts"; +import { KinAgentId, KinChatId, KinMemberId, KinOrgId, KinPersonId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; @@ -74,5 +74,28 @@ it.effect("delivers only committed viewer events and isolates organizations", () event, { ...event, seq: 2 }, ]); + + // Activity reaches only the chat's members, and only when its phase changes. + const agentId = KinAgentId.make("lead"); + const unjoined = KinChatId.make("unjoined"); + const activity = (phase: "started" | "notes_read" | "idle") => ({ + type: "activity.updated" as const, + orgId, + chatId, + activity: { agentId, phase, since: 0 }, + }); + yield* hub.setActivity({ orgId, agentId, chatIds: [chatId, unjoined], phase: "started" }); + yield* hub.setActivity({ orgId, agentId, chatIds: [chatId], phase: "started" }); + yield* hub.setWorkingPhase(orgId, KinAgentId.make("other"), "notes_read"); + yield* hub.setWorkingPhase(orgId, agentId, "notes_read"); + yield* hub.setActivity({ orgId, agentId, chatIds: [chatId], phase: "idle" }); + yield* hub.setActivity({ orgId, agentId, chatIds: [chatId], phase: "idle" }); + assert.deepStrictEqual(yield* Stream.runCollect(first.pipe(Stream.take(3))), [ + activity("started"), + activity("notes_read"), + activity("idle"), + ]); + assert.isNull(yield* hub.activity(orgId, chatId)); + assert.strictEqual((yield* hub.activity(orgId, unjoined))?.phase, "notes_read"); }).pipe(Effect.provide(layer)), ); diff --git a/apps/server/src/kin/chat/KinChatHub.ts b/apps/server/src/kin/chat/KinChatHub.ts index af75435a4f85d..170350c63e294 100644 --- a/apps/server/src/kin/chat/KinChatHub.ts +++ b/apps/server/src/kin/chat/KinChatHub.ts @@ -1,5 +1,8 @@ import type { + KinAgentId, KinChat, + KinChatActivity, + KinChatActivityPhase, KinChatId, KinMemberId, KinChatMember, @@ -8,6 +11,7 @@ import type { KinWaitingItem, KinWidget, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -26,6 +30,11 @@ type ChatEvent = | { readonly type: "widget.updated"; readonly widget: KinWidget } | { readonly type: "waiting.updated"; readonly item: KinWaitingItem } | { readonly type: "member.removed"; readonly member: KinChatMember } + | { + readonly type: "activity.updated"; + readonly chatId: KinChatId; + readonly activity: KinChatActivity; + } | { readonly type: "read.updated"; readonly chatId: KinChatId; @@ -34,6 +43,23 @@ type ChatEvent = }; export type KinChatHubEvent = ChatEvent & { readonly orgId: KinOrgId }; +/** Phases a running wake-up reports; MCP tool calls move only these. */ +export const WORKING_PHASES: ReadonlySet = new Set([ + "started", + "notes_read", + "notes_write", + "delegating", + "approval", + "scheduling", +]); +export interface ActivityInput { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly chatIds: Iterable; + readonly phase: KinChatActivityPhase; + readonly resumesAt?: number | undefined; +} + export class KinChatHub extends Context.Service< KinChatHub, { @@ -45,6 +71,19 @@ export class KinChatHub extends Context.Service< never, Scope.Scope >; + /** The chat's current activity, held in memory: a restart ends every wake-up. */ + readonly activity: ( + orgId: KinOrgId, + chatId: KinChatId, + ) => Effect.Effect; + /** Sets each chat's activity, publishing only a changed phase. `idle` clears it. */ + readonly setActivity: (input: ActivityInput) => Effect.Effect; + /** Moves every chat the agent is working on to `phase`; others keep theirs. */ + readonly setWorkingPhase: ( + orgId: KinOrgId, + agentId: KinAgentId, + phase: KinChatActivityPhase, + ) => Effect.Effect; /** Every organization's committed events, unfiltered. Server consumers only, never a client. */ readonly subscribeAll: Effect.Effect, never, Scope.Scope>; } @@ -69,15 +108,58 @@ const make = Effect.gen(function* () { } return yield* PubSub.subscribe(hub); }); + const deliver = Effect.fnUntraced(function* (event: KinChatHubEvent) { + const hub = hubs.get(event.orgId); + if (hub !== undefined) yield* PubSub.publish(hub, event); + if (all !== undefined) yield* PubSub.publish(all, event); + }); + const activities = new Map< + string, + { readonly orgId: KinOrgId; readonly chatId: KinChatId; readonly activity: KinChatActivity } + >(); + const activityKey = (orgId: KinOrgId, chatId: KinChatId) => `${orgId}:${chatId}`; + const setActivity = Effect.fn("KinChatHub.setActivity")(function* (input: ActivityInput) { + const since = yield* Clock.currentTimeMillis; + for (const chatId of new Set(input.chatIds)) { + const key = activityKey(input.orgId, chatId); + const held = activities.get(key)?.activity; + const unchanged = + input.phase === "idle" + ? held === undefined + : held?.phase === input.phase && + held.agentId === input.agentId && + held.resumesAt === input.resumesAt; + if (unchanged) continue; + const activity: KinChatActivity = { + agentId: input.agentId, + phase: input.phase, + since, + ...(input.resumesAt === undefined ? {} : { resumesAt: input.resumesAt }), + }; + if (input.phase === "idle") activities.delete(key); + else activities.set(key, { orgId: input.orgId, chatId, activity }); + // Activity is memory-only, so it publishes at once rather than after a commit. + yield* deliver({ type: "activity.updated", orgId: input.orgId, chatId, activity }); + } + }); return KinChatHub.of({ publish: Effect.fn("KinChatHub.publish")(function (event) { - return sql.afterCommit( - Effect.gen(function* () { - const hub = hubs.get(event.orgId); - if (hub !== undefined) yield* PubSub.publish(hub, event); - if (all !== undefined) yield* PubSub.publish(all, event); - }), - ); + return sql.afterCommit(deliver(event)); + }), + activity: Effect.fn("KinChatHub.activity")(function* (orgId, chatId) { + return activities.get(activityKey(orgId, chatId))?.activity ?? null; + }), + setActivity, + setWorkingPhase: Effect.fn("KinChatHub.setWorkingPhase")(function* (orgId, agentId, phase) { + const chatIds = [...activities.values()] + .filter( + (held) => + held.orgId === orgId && + held.activity.agentId === agentId && + WORKING_PHASES.has(held.activity.phase), + ) + .map((held) => held.chatId); + if (chatIds.length > 0) yield* setActivity({ orgId, agentId, chatIds, phase }); }), subscribeAll: Effect.gen(function* () { const created = yield* PubSub.unbounded(); diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index e6f17e13525f9..6d55962e760c4 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -588,14 +588,23 @@ const make = Effect.gen(function* () { afterSeq: input.afterSeq ?? 0, afterChangeSeq: input.afterChangeSeq, }); + // Read after subscribing, so a change in between arrives live; repeats are idempotent. + const activity = () => hub.activity(identity.orgId, input.chatId); + const current = yield* activity(); const backlog: KinChatStreamEvent = resumed.reset - ? { _tag: "reset", lastSeq: resumed.lastSeq, lastChangeSeq: resumed.lastChangeSeq } + ? { + _tag: "reset", + lastSeq: resumed.lastSeq, + lastChangeSeq: resumed.lastChangeSeq, + activity: current, + } : { _tag: "backlog", lastSeq: resumed.lastSeq, lastChangeSeq: resumed.lastChangeSeq, messages: resumed.messages, widgets: resumed.widgets, + activity: current, }; const messageChanges = new Map(); const revisions = new Map( @@ -611,7 +620,13 @@ const make = Effect.gen(function* () { }); cursor = { lastSeq: next.lastSeq, lastChangeSeq: next.lastChangeSeq }; delivered = 0; - if (next.reset) return { _tag: "reset", ...cursor } satisfies KinChatStreamEvent; + const activityNow = yield* activity(); + if (next.reset) + return { + _tag: "reset", + ...cursor, + activity: activityNow, + } satisfies KinChatStreamEvent; // The client already holds rows and widgets at the versions this stream delivered. const messages = next.messages.filter( (m) => (m.changeSeq ?? m.seq) !== messageChanges.get(m.messageId), @@ -621,7 +636,13 @@ const make = Effect.gen(function* () { ); for (const m of messages) messageChanges.set(m.messageId, m.changeSeq ?? m.seq); for (const w of widgets) revisions.set(w.widgetId, w.revision); - return { _tag: "backlog", ...cursor, messages, widgets } satisfies KinChatStreamEvent; + return { + _tag: "backlog", + ...cursor, + messages, + widgets, + activity: activityNow, + } satisfies KinChatStreamEvent; }); return Stream.concat( Stream.succeed(backlog), @@ -658,6 +679,10 @@ const make = Effect.gen(function* () { return event.member.chatId === input.chatId ? Option.some({ _tag: "member", member: event.member }) : Option.none(); + case "activity.updated": + return event.chatId === input.chatId + ? Option.some({ _tag: "activity", ...event.activity }) + : Option.none(); case "read.updated": return event.chatId === input.chatId ? Option.some({ @@ -716,6 +741,8 @@ const make = Effect.gen(function* () { initial.waiting.map((item) => [item.waitingId, JSON.stringify(item)]), ); const live = Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe( + // Activity changes no summary; skip the re-read. + Stream.filter(({ event }) => event.type !== "activity.updated"), Stream.mapEffect(({ viewer, event }) => Effect.gen(function* (): Effect.fn.Return { if (event.type === "waiting.updated") diff --git a/apps/server/src/kin/chat/rpcHandlers.test.ts b/apps/server/src/kin/chat/rpcHandlers.test.ts index b495ef921b23b..3a1c42590d357 100644 --- a/apps/server/src/kin/chat/rpcHandlers.test.ts +++ b/apps/server/src/kin/chat/rpcHandlers.test.ts @@ -406,8 +406,15 @@ it.effect("resets large backlogs and bounds a resume to the current snapshot", ( Option.getOrThrow( yield* Stream.runHead(chat.subscribe(person, { chatId: direct.chatId, afterSeq: 0 })), ), - { _tag: "reset", lastSeq: 201, lastChangeSeq: 201 }, + { _tag: "reset", lastSeq: 201, lastChangeSeq: 201, activity: null }, ); + // A phone that reconnects mid-wake-up sees the current phase in its backlog. + yield* Context.get(context, Hub.KinChatHub).setActivity({ + orgId: person.orgId, + agentId: KinAgentId.make("lead"), + chatIds: [direct.chatId], + phase: "started", + }); const resume = Option.getOrThrow( yield* Stream.runHead(chat.subscribe(person, { chatId: direct.chatId, afterSeq: 1 })), ); @@ -416,6 +423,7 @@ it.effect("resets large backlogs and bounds a resume to the current snapshot", ( assert.strictEqual(resume.messages.length, 200); assert.strictEqual(resume.messages[0]?.seq, 2); assert.strictEqual(resume.lastSeq, 201); + assert.strictEqual(resume.activity?.phase, "started"); } const sql = yield* SqlClient.SqlClient; yield* sql`UPDATE kin_messages SET body = 'Offline edit' WHERE org_id = ${person.orgId} AND chat_id = ${direct.chatId}`; @@ -429,7 +437,12 @@ it.effect("resets large backlogs and bounds a resume to the current snapshot", ( }), ), ), - { _tag: "reset", lastSeq: 201, lastChangeSeq: 402 }, + { + _tag: "reset", + lastSeq: 201, + lastChangeSeq: 402, + activity: { agentId: KinAgentId.make("lead"), phase: "started", since: 0 }, + }, ); // A client keeps its change cursor frozen while live, so the stream must refresh it. const events = yield* Stream.toQueue( diff --git a/apps/server/src/kin/floor/KinFloor.ts b/apps/server/src/kin/floor/KinFloor.ts index c090398cd7d5d..2364047d6d3bd 100644 --- a/apps/server/src/kin/floor/KinFloor.ts +++ b/apps/server/src/kin/floor/KinFloor.ts @@ -61,6 +61,13 @@ const notGranted = new KinChatError({ reason: "floor_not_granted", message: "The floor is not granted.", }); +const replyWindowClosed = new KinChatError({ + reason: "floor_not_granted", + message: "The reply window closed before this post.", +}); +/** The agent held a grant for the latest run but it expired unused. */ +export const isReplyWindowClosed = (error: KinChatError) => + error.reason === replyWindowClosed.reason && error.message === replyWindowClosed.message; type Scope = { readonly orgId: KinOrgId; readonly chatId: KinChatId }; type Authorization = { readonly runId: string | null }; export class KinFloor extends Context.Service< @@ -254,7 +261,12 @@ const make = Effect.gen(function* () { AND (${token ?? null} IS NULL OR token = ${token ?? null}) ORDER BY expires_at, token LIMIT 1`; const grant = grants[0]; - if (grant === undefined) return yield* notGranted; + if (grant === undefined) { + const expired = yield* sql`SELECT 1 FROM kin_floor_grants + WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${identity.agentId} + AND run_id = ${run.run_id} AND consumed_at IS NULL AND expires_at <= ${now} LIMIT 1`; + return yield* expired.length > 0 ? replyWindowClosed : notGranted; + } const consumed = yield* sql`UPDATE kin_floor_grants SET consumed_at = ${now} WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${identity.agentId} AND run_id = ${run.run_id} AND token = ${grant.token} AND consumed_at IS NULL AND expires_at > ${now} diff --git a/apps/server/src/kin/lead/ChatWake.ts b/apps/server/src/kin/lead/ChatWake.ts index 3a0b15ce460f9..2ac4fc14df096 100644 --- a/apps/server/src/kin/lead/ChatWake.ts +++ b/apps/server/src/kin/lead/ChatWake.ts @@ -22,6 +22,7 @@ import { forkParked } from "../../serverActivation.ts"; import { KinChatHub } from "../chat/KinChatHub.ts"; import { KinChatRepository } from "../chat/KinChatRepository.ts"; import { KinEventQueue } from "./KinEventQueue.ts"; +import * as ChatActivity from "./chatActivity.ts"; const decodeTap = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ actionId: TrimmedNonEmptyString })), @@ -89,14 +90,23 @@ const make = Effect.gen(function* () { const event: KinEvent = Option.isSome(actionId) ? { ...base, _tag: "widget.action", actionId: actionId.value } : { ...base, _tag: "chat.message" }; - yield* queue.enqueue(event).pipe( + const queued = yield* queue.enqueue(event).pipe( + Effect.asSome, Effect.catchTags({ - KinEventQueueRetiredAgent: () => Effect.void, - KinEventQueueUnknownAgent: () => Effect.void, + KinEventQueueRetiredAgent: () => Effect.succeedNone, + KinEventQueueUnknownAgent: () => Effect.succeedNone, KinEventQueueConflict: (error) => - Effect.logWarning("Kin chat wake-up conflicts with a stored event", error), + Effect.logWarning("Kin chat wake-up conflicts with a stored event", error).pipe( + Effect.as(Option.none()), + ), }), ); + if (Option.isSome(queued) && !queued.value.duplicate) + yield* ChatActivity.enqueued(hub, { + orgId: message.orgId, + agentId, + chatId: message.chatId, + }); } }, Effect.catchCause((cause) => Effect.logError("Kin chat wake-up failed", { cause })), diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 99c860ee274cb..0aa87ba61bd98 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -14,6 +14,7 @@ import { KinWakeupId, KinEvent, KinAgentId, + KinChatId, KinPersonId, ThreadId, RunId, @@ -58,6 +59,10 @@ import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; import * as EffectWorker from "../../orchestration-v2/EffectWorker.ts"; import { provideDeterministicTestRuntime } from "../../orchestration-v2/testkit/DeterministicRuntime.ts"; import { harness, seed, orgId, agentId, event } from "./WakeupRunner.testkit.ts"; +import * as ChatActivity from "./chatActivity.ts"; +import { announceToolPhase } from "../mcp/toolPhase.ts"; +import { McpInvocationContext } from "../../mcp/McpInvocationContext.ts"; +import * as Stream from "effect/Stream"; const decodeEvent = Schema.decodeSync(KinEvent); const decodeUsage = Schema.decodeEffect( @@ -73,8 +78,7 @@ const decodeUsage = Schema.decodeEffect( ), ), ); -const resolveAgent = Effect.fn("test.resolveAgent")(function* (threadId: ThreadId) { - const identity = yield* KinIdentity.KinIdentity; +const scopeFor = Effect.fn("test.scopeFor")(function* (threadId: ThreadId) { const sessions = yield* McpSessionRegistry.McpSessionRegistry; const issued = yield* sessions.issue({ threadId, @@ -83,7 +87,34 @@ const resolveAgent = Effect.fn("test.resolveAgent")(function* (threadId: ThreadI const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); const scope = yield* sessions.resolve(token); assert.isDefined(scope); - return yield* identity.resolveAgent(scope!); + return scope!; +}); +const resolveAgent = Effect.fn("test.resolveAgent")(function* (threadId: ThreadId) { + return yield* (yield* KinIdentity.KinIdentity).resolveAgent(yield* scopeFor(threadId)); +}); +const chatId = KinChatId.make("owner-chat"); +const chatEvent = (id: string) => + decodeEvent({ + _tag: "chat.message", + orgId, + agentId, + eventId: id, + receivedAt: "1970-01-01T00:00:00.000Z", + dedupeKey: id, + provenance: { _tag: "system" }, + chatId, + messageId: `message-${id}`, + }); +/** The phases the hub publishes for the owner's chat, in order. */ +const chatPhases = Effect.fn("test.chatPhases")(function* (count: number) { + const events = yield* (yield* ChatHub.KinChatHub).subscribeAll; + return yield* events.pipe( + Stream.filter((item) => item.type === "activity.updated" && item.chatId === chatId), + Stream.map((item) => (item.type === "activity.updated" ? item.activity.phase : "idle")), + Stream.take(count), + Stream.runCollect, + Effect.forkChild, + ); }); const run = Effect.fn("test.run")(function* () { const runner = yield* WakeupRunner.WakeupRunner; @@ -181,6 +212,80 @@ describe("WakeupRunner", () => { }).pipe(Effect.provide(harness({ writer }))); }).pipe(provideDeterministicTestRuntime), ); + it.effect("reports a chat's activity from queued through a tool call to idle", () => + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const hold = yield* Deferred.make(); + yield* Effect.gen(function* () { + yield* seed; + const hub = yield* ChatHub.KinChatHub; + const sql = yield* SqlClient.SqlClient; + const phases = yield* chatPhases(4); + yield* (yield* KinEventQueue.KinEventQueue).enqueue(chatEvent("hello")); + yield* ChatActivity.enqueued(hub, { orgId, agentId, chatId }); + const fiber = yield* run(); + yield* Deferred.await(entered); + const [wakeup] = yield* sql<{ threadId: ThreadId }>` + SELECT thread_id AS "threadId" FROM kin_wakeups WHERE org_id = ${orgId}`; + const toolCall = announceToolPhase("notes_read").pipe( + Effect.provideService(McpInvocationContext, yield* scopeFor(wakeup!.threadId)), + Effect.provideService(ChatHub.KinChatHub, hub), + Effect.provideService(KinIdentity.KinIdentity, yield* KinIdentity.KinIdentity), + ); + // A repeated phase publishes nothing. + yield* toolCall; + yield* toolCall; + yield* Deferred.succeed(hold, undefined); + yield* Fiber.join(fiber); + assert.deepStrictEqual(yield* Fiber.join(phases), [ + "queued", + "started", + "notes_read", + "idle", + ]); + assert.isNull(yield* hub.activity(orgId, chatId)); + }).pipe(Effect.scoped, Effect.provide(harness({ entered, hold }))); + }).pipe(provideDeterministicTestRuntime), + ); + it.effect("shows a failed chat wake-up until the owner writes again", () => + Effect.gen(function* () { + yield* seed; + const hub = yield* ChatHub.KinChatHub; + const queue = yield* KinEventQueue.KinEventQueue; + const phases = yield* chatPhases(3); + yield* queue.enqueue(chatEvent("fails")); + yield* Fiber.join(yield* run()); + assert.strictEqual((yield* hub.activity(orgId, chatId))?.phase, "failed"); + yield* queue.enqueue(chatEvent("again")); + yield* ChatActivity.enqueued(hub, { orgId, agentId, chatId }); + assert.deepStrictEqual(yield* Fiber.join(phases), ["started", "failed", "queued"]); + }).pipe( + Effect.scoped, + Effect.provide(harness({ failed: true })), + provideDeterministicTestRuntime, + ), + ); + it.effect("reports a budget-deferred chat event with its reset time", () => + Effect.gen(function* () { + yield* seed; + const hub = yield* ChatHub.KinChatHub; + const sql = yield* SqlClient.SqlClient; + yield* (yield* Budget.KinBudget).set( + [{ _tag: "person", orgId, personId: KinPersonId.make("owner") }], + { orgId, limits: { leadUnits: 0, workerUnits: 0 } }, + ); + const phases = yield* chatPhases(1); + yield* (yield* KinEventQueue.KinEventQueue).enqueue(chatEvent("over-budget")); + yield* Fiber.join(yield* run()); + const [row] = yield* sql<{ notBefore: number }>` + SELECT not_before AS "notBefore" FROM kin_events WHERE org_id = ${orgId}`; + assert.deepStrictEqual(yield* Fiber.join(phases), ["budget"]); + assert.include(yield* hub.activity(orgId, chatId), { + phase: "budget", + resumesAt: row!.notBefore, + }); + }).pipe(Effect.scoped, Effect.provide(harness()), provideDeterministicTestRuntime), + ); it.effect("uses the cheap model for exhausted P0 even when a routine is in the batch", () => Effect.gen(function* () { yield* seed; diff --git a/apps/server/src/kin/lead/WakeupRunner.testkit.ts b/apps/server/src/kin/lead/WakeupRunner.testkit.ts index f78815a1275ee..19c6a9ee30e76 100644 --- a/apps/server/src/kin/lead/WakeupRunner.testkit.ts +++ b/apps/server/src/kin/lead/WakeupRunner.testkit.ts @@ -426,25 +426,13 @@ function parts(options: HarnessOptions) { const launch = ThreadLaunch.layer.pipe( Layer.provide(Layer.mergeAll(external, management, receipts, IdAllocator.layer)), ); + // One hub instance, so a test reads the activity the runner publishes. + const hub = Hub.layer.pipe(Layer.provideMerge(KinChatRepository.layer)); const kin = Layer.mergeAll( KinEventQueue.layer, - KinStop.layer.pipe( - Layer.provide( - Layer.mergeAll( - KinEventQueue.layer, - Hub.layer.pipe(Layer.provideMerge(KinChatRepository.layer)), - ), - ), - ), - Budget.layer.pipe( - Layer.provide( - Layer.mergeAll( - MemoryCache.layer, - KinEventQueue.layer, - Hub.layer.pipe(Layer.provideMerge(KinChatRepository.layer)), - ), - ), - ), + hub, + KinStop.layer.pipe(Layer.provide(Layer.mergeAll(KinEventQueue.layer, hub))), + Budget.layer.pipe(Layer.provide(Layer.mergeAll(MemoryCache.layer, KinEventQueue.layer, hub))), KinLeadRegistry.layer, KinIdentity.KinIdentity.layer.pipe( Layer.provide(KinChatRepository.layer), diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index d3315cbbec6b2..984a2b04a9934 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -1,6 +1,7 @@ import { CommandId, KinAgentId, + KinChatId, KinLead, KinOrgId, KinWakeupId, @@ -34,6 +35,8 @@ import * as Memory from "../memory/Memory.ts"; import * as Routines from "../triggers/routines.ts"; import * as OwnerCheck from "../triggers/ownerCheck.ts"; import * as KinEventQueue from "./KinEventQueue.ts"; +import { KinChatHub } from "../chat/KinChatHub.ts"; +import * as ChatActivity from "./chatActivity.ts"; import * as KinBudget from "./KinBudget.ts"; import * as KinLeadRegistry from "./KinLeadRegistry.ts"; import { KinLeadPrompt } from "./LeadPrompt.ts"; @@ -88,6 +91,9 @@ const RunningRow = Schema.Struct({ startedAt: Schema.Number, }); const decodeLead = Schema.decodeUnknownEffect(LeadRow); +// A run the stop switch interrupted is "stopped": its events wait for the resume, not a retry. +const endedInFailure = (status: string | undefined) => + status === "failed" || status === "timed_out"; const decodeRunning = Schema.decodeUnknownEffect(RunningRow); const ulid = Effect.gen(function* () { const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; @@ -114,6 +120,7 @@ const make = Effect.gen(function* () { const prompt = yield* KinLeadPrompt; const identity = yield* KinIdentity.KinIdentity; const registry = yield* KinLeadRegistry.KinLeadRegistry; + const hub = yield* KinChatHub; const projects = yield* ProjectService.ProjectService; const launch = yield* ThreadLaunchService.ThreadLaunchService; const threads = yield* ThreadManagementService.ThreadManagementService; @@ -259,6 +266,7 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`kin-settle:${row.wakeupId}`), byOwnAgent: true, }); + return stopped ? "stopped" : status; }, (effect, row) => effect.pipe( @@ -269,6 +277,25 @@ const make = Effect.gen(function* () { ), ), ); + // Settles the chats' activity when the scope closes; queue state has settled by then. + const trackChats = Effect.fn("WakeupRunner.trackChats")(function* ( + orgId: KinOrgId, + agentId: KinAgentId, + chatIds: ReadonlyArray, + failed: () => boolean, + ) { + yield* Effect.acquireRelease(Effect.void, (_, exit) => + ChatActivity.settle(hub, { + orgId, + agentId, + chatIds, + failed: (Exit.isFailure(exit) && !Exit.hasInterrupts(exit)) || failed(), + }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.catchCause((cause) => Effect.logWarning("Kin chat activity settle failed", cause)), + ), + ); + }); const clearMissingThread = Effect.fn("WakeupRunner.clearMissingThread")(function* ( row: typeof RunningRow.Type, ) { @@ -356,6 +383,9 @@ const make = Effect.gen(function* () { ), ); row = { ...row, startedAt: yield* Clock.currentTimeMillis }; + let failed = false; + const claimedChats = ChatActivity.chatIdsOf(events); + yield* trackChats(orgId, agentId, claimedChats, () => failed); yield* Effect.gen(function* () { if (yield* paused(orgId)) { yield* queue.release({ @@ -372,6 +402,7 @@ const make = Effect.gen(function* () { return yield* retire(current); } let cheapOnly = false; + let deferredUntil: number | undefined; for (const priority of new Set(events.map((item) => item.priority))) { const admission = yield* budget.admit(orgId, priority); cheapOnly ||= admission.cheapOnly; @@ -390,8 +421,19 @@ const make = Effect.gen(function* () { budgetDeferred: true, }); events = events.filter((event) => !deferred.has(event.eventId)); + deferredUntil = Math.max(deferredUntil ?? 0, admission.nextReset); } } + if (deferredUntil !== undefined) { + const running = new Set(ChatActivity.chatIdsOf(events)); + yield* hub.setActivity({ + orgId, + agentId, + chatIds: claimedChats.filter((chatId) => !running.has(chatId)), + phase: "budget", + resumesAt: deferredUntil, + }); + } const routines = yield* Effect.serviceOption(Routines.KinRoutines); if (Option.isSome(routines)) events = yield* Effect.filter(events, (event) => @@ -403,6 +445,12 @@ const make = Effect.gen(function* () { yield* queue.finish({ orgId, wakeupId, status: "completed" }); return; } + yield* hub.setActivity({ + orgId, + agentId, + chatIds: ChatActivity.chatIdsOf(events), + phase: "started", + }); const budgetContext = yield* budget.promptContext(orgId); const pinned = yield* memory.prepareWakeup(orgId, wakeupId).pipe( Effect.tapError((error) => @@ -549,7 +597,7 @@ const make = Effect.gen(function* () { runId: run.id, commandId: CommandId.make(`kin-stop-launch:${wakeupId}`), }); - yield* wait(row, project.id); + failed = endedInFailure(yield* wait(row, project.id)); }).pipe( Effect.onExit((exit) => Exit.isFailure(exit) @@ -642,11 +690,26 @@ const make = Effect.gen(function* () { threadId: projection.thread.id, }); yield* registry.register(projection.thread.id, { ...row, level: record.level }); - yield* wait(row, projection.thread.projectId).pipe( - Effect.onExit((exit) => - Exit.isFailure(exit) - ? cleanup(row, Exit.hasInterrupts(exit)).pipe(Effect.ignore) - : Effect.void, + const chats = yield* sql<{ chatId: string }>` + SELECT DISTINCT json_extract(json, '$.chatId') AS "chatId" FROM kin_events + WHERE org_id = ${row.orgId} AND wakeup_id = ${row.wakeupId} + AND json_extract(json, '$.chatId') IS NOT NULL`; + let failed = false; + const chatIds = chats.map((chat) => KinChatId.make(chat.chatId)); + yield* trackChats(row.orgId, row.agentId, chatIds, () => failed); + yield* hub.setActivity({ + orgId: row.orgId, + agentId: row.agentId, + chatIds, + phase: "started", + }); + failed = endedInFailure( + yield* wait(row, projection.thread.projectId).pipe( + Effect.onExit((exit) => + Exit.isFailure(exit) + ? cleanup(row, Exit.hasInterrupts(exit)).pipe(Effect.ignore) + : Effect.void, + ), ), ); }), diff --git a/apps/server/src/kin/lead/chatActivity.ts b/apps/server/src/kin/lead/chatActivity.ts new file mode 100644 index 0000000000000..a1c5aa775a9cc --- /dev/null +++ b/apps/server/src/kin/lead/chatActivity.ts @@ -0,0 +1,74 @@ +import type { KinAgentId, KinChatId, KinEvent, KinOrgId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { WORKING_PHASES, type KinChatHub } from "../chat/KinChatHub.ts"; +import { isOrgPaused } from "./orgState.ts"; + +/** The chats a batch of events answers: owner messages and widget taps. */ +export const chatIdsOf = (events: ReadonlyArray): ReadonlyArray => [ + ...new Set( + events.flatMap((event) => + event._tag === "chat.message" || event._tag === "widget.action" ? [event.chatId] : [], + ), + ), +]; + +/** Why a chat's queued event has not started, or undefined when none is queued. */ +const waitingPhase = Effect.fn("KinChatActivity.waitingPhase")(function* ( + orgId: KinOrgId, + agentId: KinAgentId, + chatId: KinChatId, +) { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ deferred: number; notBefore: number | null }>` + SELECT budget_deferred AS deferred, not_before AS "notBefore" FROM kin_events + WHERE org_id = ${orgId} AND agent_id = ${agentId} AND state = 'queued' + AND json_extract(json, '$.chatId') = ${chatId} + ORDER BY budget_deferred DESC, not_before DESC LIMIT 1`; + if (row === undefined) return undefined; + if (yield* isOrgPaused(orgId)) return { phase: "paused" as const }; + return row.deferred === 1 + ? { phase: "budget" as const, resumesAt: row.notBefore ?? undefined } + : { phase: "queued" as const }; +}); + +/** + * A wake-up ended: show its failure until the next wake-up or owner message, else what still + * waits, else nothing. A late-reply notice stays. + */ +export const settle = Effect.fn("KinChatActivity.settle")(function* ( + hub: KinChatHub["Service"], + input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly chatIds: ReadonlyArray; + readonly failed: boolean; + }, +) { + for (const chatId of input.chatIds) { + const held = yield* hub.activity(input.orgId, chatId); + if (held?.phase === "reply_late" && held.agentId === input.agentId) continue; + const next = input.failed + ? { phase: "failed" as const } + : ((yield* waitingPhase(input.orgId, input.agentId, chatId)) ?? { phase: "idle" as const }); + yield* hub.setActivity({ + orgId: input.orgId, + agentId: input.agentId, + chatIds: [chatId], + ...next, + }); + } +}); + +/** A new owner message: say why it waits, unless a wake-up is already working on the chat. */ +export const enqueued = Effect.fn("KinChatActivity.enqueued")(function* ( + hub: KinChatHub["Service"], + input: { readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly chatId: KinChatId }, +) { + const held = yield* hub.activity(input.orgId, input.chatId); + if (held !== null && held.agentId === input.agentId && WORKING_PHASES.has(held.phase)) return; + const waiting = yield* waitingPhase(input.orgId, input.agentId, input.chatId); + if (waiting !== undefined) + yield* hub.setActivity({ ...input, chatIds: [input.chatId], ...waiting }); +}); diff --git a/apps/server/src/kin/lead/layer.test.ts b/apps/server/src/kin/lead/layer.test.ts index 5159d52704215..f6e4fd7d58c85 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -23,7 +23,11 @@ import { event, harness, seed, orgId } from "./WakeupRunner.testkit.ts"; const external = Layer.mergeAll( Layer.mock(ChatService.KinChatService)({}), - Layer.mock(ChatHub.KinChatHub)({ subscribeAll: Effect.succeed(Stream.never) }), + Layer.mock(ChatHub.KinChatHub)({ + subscribeAll: Effect.succeed(Stream.never), + activity: () => Effect.succeed(null), + setActivity: () => Effect.void, + }), ServerConfig.layerTest(process.cwd(), { prefix: "kin-lead-layer-" }), Layer.mock(VcsProcess.VcsProcess)({}), ).pipe(Layer.provideMerge(NodeServices.layer)); diff --git a/apps/server/src/kin/lead/mcp/handlers.ts b/apps/server/src/kin/lead/mcp/handlers.ts index 01db062e9f817..c22185e7dffd3 100644 --- a/apps/server/src/kin/lead/mcp/handlers.ts +++ b/apps/server/src/kin/lead/mcp/handlers.ts @@ -4,16 +4,19 @@ import * as McpToolAccess from "../../../mcp/McpToolAccess.ts"; import { LeadMemory } from "../LeadMemory.ts"; import { KinWorkers } from "../Workers.ts"; import { KinLeadToolkit } from "./tools.ts"; +import { announceToolPhase } from "../../mcp/toolPhase.ts"; // Kin's service checks the persisted lead and wake-up, rather than T3 thread-control grants. export const handlers = McpToolAccess.toLayer(KinLeadToolkit, { kin_delegate: McpToolAccess.actsAsCaller( Effect.fn("KinLeadToolkit.delegate")(function* (input) { + yield* announceToolPhase("delegating"); return yield* (yield* KinWorkers).delegate(yield* McpInvocationContext, input); }), ), kin_follow_up: McpToolAccess.actsAsCaller( Effect.fn("KinLeadToolkit.followUp")(function* (input) { + yield* announceToolPhase("delegating"); return yield* (yield* KinWorkers).followUp(yield* McpInvocationContext, input); }), ), @@ -24,26 +27,31 @@ export const handlers = McpToolAccess.toLayer(KinLeadToolkit, { ), memory_search: McpToolAccess.reads( Effect.fn("KinLeadToolkit.search")(function* (input) { + yield* announceToolPhase("notes_read"); return yield* (yield* LeadMemory).search(yield* McpInvocationContext, input); }), ), memory_read: McpToolAccess.reads( Effect.fn("KinLeadToolkit.read")(function* (input) { + yield* announceToolPhase("notes_read"); return yield* (yield* LeadMemory).read(yield* McpInvocationContext, input); }), ), memory_write: McpToolAccess.actsAsCaller( Effect.fn("KinLeadToolkit.write")(function* (input) { + yield* announceToolPhase("notes_write"); return yield* (yield* LeadMemory).write(yield* McpInvocationContext, input); }), ), kin_defer: McpToolAccess.actsAsCaller( Effect.fn("KinLeadToolkit.defer")(function* (input) { + yield* announceToolPhase("scheduling"); return yield* (yield* LeadMemory).defer(yield* McpInvocationContext, input); }), ), kin_journal: McpToolAccess.actsAsCaller( Effect.fn("KinLeadToolkit.journal")(function* (input) { + yield* announceToolPhase("notes_write"); return yield* (yield* LeadMemory).journal(yield* McpInvocationContext, input); }), ), diff --git a/apps/server/src/kin/mcp/KinChatToolkit.test.ts b/apps/server/src/kin/mcp/KinChatToolkit.test.ts index e21c98659268b..af2fca26fcbf2 100644 --- a/apps/server/src/kin/mcp/KinChatToolkit.test.ts +++ b/apps/server/src/kin/mcp/KinChatToolkit.test.ts @@ -3,6 +3,7 @@ import { authorityLayer, startAgentWakeup } from "../chat/WakeupAuthority.testki import * as SecureRandom from "effect/crypto/SecureRandom"; import * as TestClock from "effect/testing/TestClock"; import { FLOOR_GRANT_TTL_MS } from "../floor/FloorManager.ts"; +import { isReplyWindowClosed } from "../floor/KinFloor.ts"; import * as FileSystem from "effect/FileSystem"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -11,6 +12,7 @@ import { AuthStandardClientScopes, EnvironmentId, KinAgentId, + KinChatError, KinMessageId, KinMemberId, KinOrgId, @@ -26,6 +28,7 @@ import * as Result from "effect/Result"; import * as Option from "effect/Option"; import * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; +import * as Schema from "effect/Schema"; import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts"; import { liveThreadShell } from "../../mcp/McpToolAccess.testkit.ts"; import * as McpSessions from "../../mcp/McpSessionRegistry.ts"; @@ -738,6 +741,7 @@ const sendFloor = Effect.fn("test.sendFloor")(function* (input: FloorPost) { clientMessageId: input.clientMessageId ?? SecureRandom.uuidV4Unsafe(), }).pipe(Effect.result); }); +const isKinChatError = Schema.is(KinChatError); const failureOf = (result: Result.Result) => Result.getOrThrow(Result.flip(result)); it.effect( @@ -894,9 +898,14 @@ it.effect( floorGrant: grant.token, } as const; yield* TestClock.adjust(FLOOR_GRANT_TTL_MS); - assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + const late = failureOf(yield* sendFloor(post)); + assert.include(late, { reason: "floor_not_granted" }); + // The phone says the reply came too late only for a lapsed grant, not a newer run's. + assert.isTrue(isKinChatError(late) && isReplyWindowClosed(late)); yield* human("human-2"); - assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + const superseded = failureOf(yield* sendFloor(post)); + assert.include(superseded, { reason: "floor_not_granted" }); + assert.isFalse(isKinChatError(superseded) && isReplyWindowClosed(superseded)); const [fresh] = yield* sql<{ token: string; run_id: string; diff --git a/apps/server/src/kin/mcp/KinChatToolkit.ts b/apps/server/src/kin/mcp/KinChatToolkit.ts index 883f0eb36da5f..fb2158dee1b22 100644 --- a/apps/server/src/kin/mcp/KinChatToolkit.ts +++ b/apps/server/src/kin/mcp/KinChatToolkit.ts @@ -26,6 +26,8 @@ import { KinServer } from "../KinServer.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { KinChatService } from "../chat/KinChatService.ts"; import { KinLevelGate } from "../lead/LevelGate.ts"; +import { isReplyWindowClosed } from "../floor/KinFloor.ts"; +import { announceReplyLate } from "./toolPhase.ts"; export const enabled = () => { const fiber = Fiber.getCurrent(); @@ -136,7 +138,12 @@ export const handlers = McpToolAccess.toLayer(KinChatToolkit, { return yield* post(agent, { ...input, clientMessageId: input.clientMessageId ?? SecureRandom.uuidV4Unsafe(), - }).pipe(Effect.mapError(failure)); + }).pipe( + Effect.mapError(failure), + Effect.tapError((error) => + isReplyWindowClosed(error) ? announceReplyLate(input.chatId) : Effect.void, + ), + ); }), ), kin_chat_read: McpToolAccess.reads( diff --git a/apps/server/src/kin/mcp/layer.ts b/apps/server/src/kin/mcp/layer.ts index 44552f443d9f2..f85fbd7ac78f7 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -14,6 +14,7 @@ import * as KinLead from "../lead/layer.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import { KinServer } from "../KinServer.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; +import { KinChatHub } from "../chat/KinChatHub.ts"; import { KinShadowSummary } from "../lead/KinLevels.ts"; import { KinChatToolkit, handlers } from "./KinChatToolkit.ts"; import * as KinApprovalsMcp from "../approvals/mcp.ts"; @@ -61,6 +62,8 @@ const auth = HttpRouter.middleware<{ provides: McpInvocationContext | KinServer Effect.provideService(KinIdentity, identity), // request_action refreshes the owner's shadow summary without importing the chat service. Effect.provideService(KinShadowSummary, Context.get(kin.services.value, KinShadowSummary)), + // Tool calls report the lead's phase to the chats its wake-up answers. + Effect.provideService(KinChatHub, Context.get(kin.services.value, KinChatHub)), ); }) satisfies Auth; }), diff --git a/apps/server/src/kin/mcp/toolPhase.ts b/apps/server/src/kin/mcp/toolPhase.ts new file mode 100644 index 0000000000000..50348c0ed58a7 --- /dev/null +++ b/apps/server/src/kin/mcp/toolPhase.ts @@ -0,0 +1,46 @@ +import type { KinChatActivityPhase, KinChatId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { McpInvocationContext } from "../../mcp/McpInvocationContext.ts"; +import { KinChatHub } from "../chat/KinChatHub.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; + +// The /kin/mcp middleware provides both to every tool call; other callers get no status. +const callerHub = Effect.gen(function* () { + const hub = yield* Effect.serviceOption(KinChatHub); + const identity = yield* Effect.serviceOption(KinIdentity); + if (Option.isNone(hub) || Option.isNone(identity)) return Option.none(); + const agent = yield* identity.value.resolveAgent(yield* McpInvocationContext); + return Option.some({ hub: hub.value, agent }); +}); + +/** Shows the owner what the calling lead is doing in the chats its wake-up answers. */ +export const announceToolPhase = Effect.fn("KinToolPhase.announce")( + function* (phase: KinChatActivityPhase) { + const caller = yield* callerHub; + if (Option.isSome(caller)) + yield* caller.value.hub.setWorkingPhase( + caller.value.agent.orgId, + caller.value.agent.agentId, + phase, + ); + }, + // Status is best effort; it never fails the tool call. + (effect) => Effect.ignore(effect), +); + +/** The lead's reply missed its window; the chat says so until the owner writes again. */ +export const announceReplyLate = Effect.fn("KinToolPhase.replyLate")( + function* (chatId: KinChatId) { + const caller = yield* callerHub; + if (Option.isSome(caller)) + yield* caller.value.hub.setActivity({ + orgId: caller.value.agent.orgId, + agentId: caller.value.agent.agentId, + chatIds: [chatId], + phase: "reply_late", + }); + }, + (effect) => Effect.ignore(effect), +); diff --git a/docs/kin/specs/chat.md b/docs/kin/specs/chat.md index 3f823977d08bf..0ee4251a2c8d8 100644 --- a/docs/kin/specs/chat.md +++ b/docs/kin/specs/chat.md @@ -338,11 +338,14 @@ export const KinChatStreamEvent = Schema.Union([ widgets: Schema.Array(KinWidget), lastSeq: NonNegativeInt, lastChangeSeq: Schema.optional(NonNegativeInt), + activity: Schema.optional(Schema.NullOr(KinChatActivity)), // current lead activity }), Schema.TaggedStruct("reset", { lastSeq: NonNegativeInt, lastChangeSeq: Schema.optional(NonNegativeInt), + activity: Schema.optional(Schema.NullOr(KinChatActivity)), }), // gap too big: refetch with history + Schema.TaggedStruct("activity", KinChatActivity.fields), // { agentId, phase, since, resumesAt? } Schema.TaggedStruct("message", { message: KinMessage }), // new or changed (edit, delete, send of a suggestion) Schema.TaggedStruct("widget", { widget: KinWidget }), Schema.TaggedStruct("member", { member: KinChatMember }), @@ -352,6 +355,7 @@ export const KinChatStreamEvent = Schema.Union([ - **Resume:** `kin.chat.subscribe` subscribes to the hub first, then reads one SQLite snapshot. `seq` remains the message's immutable ordering key. K010 adds a per-chat integer `change_seq`: message inserts/updates and widget writes advance it transactionally; widget writes mark their parent message changed. The indexed backlog selects the union of new messages (`seq > afterSeq`) and changed messages (`change_seq > afterChangeSeq`), once per message, with current associated widgets and normal viewer filtering. More than 200 affected visible messages sends `reset` instead. Both `backlog` and `reset` include `lastSeq` and `lastChangeSeq` from that snapshot. The migration marks all existing messages changed beyond `lastSeq`, so a client offline across the upgrade cannot miss an earlier edit. - **Client resume contract:** upsert messages by `messageId` (do not discard an older `seq`) and widgets by `widgetId`/`revision`. Persist `backlog.lastChangeSeq` only after applying the whole backlog; send it as optional `afterChangeSeq` with the last message `afterSeq` on reconnect. Keep this snapshot cursor unchanged while receiving live events: their delivery order need not match commit order, so taking the maximum live `changeSeq` could skip another committed event. Because inserts also advance `change_seq`, a frozen cursor would grow the replay until a long live session reset on reconnect; every 100 live messages the stream re-reads from its last cursor and sends another `backlog` that carries the fresh cursors and only the rows and widgets the stream has not already delivered. Apply it like any backlog. Replaying already-held rows across reconnects is intentional and idempotent. `reset` invalidates the entire cached chat, not just the latest page; refetch with history and resume from the reset cursors. Clients omitting `afterChangeSeq` get only new messages (`seq > afterSeq`), the pre-K010 behaviour, and can miss offline edits. Clients must treat a backlog as upserts, not append-only. Live message events carry optional `changeSeq`; the server drops buffered changes already represented by the snapshot and repeated versions. These optional fields preserve older payload decoding. `clientMessageId` is an optional unprefixed send id, present only for the message's author in send replies, history, backlogs, live events and chat summaries; owning the chat does not reveal another author's id. +- **Lead activity:** `KinChatHub` holds each chat's current `KinChatActivity` in memory (a restart ends every wake-up) and publishes only a changed phase. ChatWake sets `queued`, `paused` or `budget` from the queue row; the wake-up runner sets `started`, then `failed` or what still waits, else `idle`, when its scope closes; the lead's Kin MCP tools set their working phase when a call starts; a post refused because the grant lapsed unused sets `reply_late`. Provider-native tools are invisible to Kin, so the last phase stands. Snapshots carry the current activity; the chat-list stream ignores it. - **List resume:** `kin.chats.subscribe` has no `afterSeq`: message sequences are per chat, not an org-wide event cursor. It subscribes first, buffers while reading one fresh chat/waiting snapshot, then emits changed summaries and personal waiting rows, dropping state already in that snapshot. Reconnection replaces the list with a new snapshot. A durable list-event cursor needs a separate journal and is not CHAT-6. - **Removal:** a removed member receives their own resolved waiting rows even after membership ends. Their chat stream emits a final typed `member` event with non-null `leftAt`, then ends. The chat-list stream stays open; an event whose summary or waiting read fails is dropped and logged at debug level, not allowed to terminate the subscription. - **Agent discovery:** `kin.orgs.list` includes each org's `agents: [{ agentId, displayName, retired }]`, filtered by org and ordered by display name then agent id. Use a non-retired agent id with `createDirect`. diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 938bb7f9d50e2..20bf8e0fe8714 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -222,6 +222,7 @@ Every screen handles the same seven states. Each state's copy is fixed below. - **Composer (`KinComposer`).** It wraps `ComposerEditor` with `draftKey = kin:${environmentId}:${orgId}:${chatId}`, plus a send `Button`. The placeholder is "Message Tech lead". There are no model, attachment or slash controls in phase 1. - **Sending.** Send creates a `clientMessageId` (`lib/uuid.ts`) and shows the bubble at once as "Sending". When the stream carries a message with that `clientMessageId` (returned only to its author), the pending bubble gives way to it, even if the send reply was lost, so the author sees one bubble. Offline sends wait in a Kin outbox (`features/chats/state/kinOutbox.ts`, persisted, keyed by `clientMessageId`) and go out on reconnect. The server dedupes by `clientMessageId`, so anything short of a typed refusal (no connection, Kin `unavailable`, no reply within 30 s, a reply that fails to decode) waits and resends under the same id. A refusal (`KinChatError` other than `unavailable`, or `EnvironmentAuthorizationError`) can't succeed on resend: the bubble shows "Not sent: " with Edit, which moves the body back to the draft and drops the entry. - **Outbox keying.** The outbox is keyed by environment and chat, not by person. That holds while an org has one person per device. Once orgs have more than one person, key entries by person too, so one person's unsent messages never go out under another's session. +- **Lead status.** While the lead's wake-up covers the chat, the feed ends with a quiet row in the lead's position, from the stream's `activity` phase: "Waiting for Tech lead…", "Tech lead is reading your message…", "Checking its notes…", a failure or a budget pause. A working phase adds "Still working." after 45 s (one timer) and hides once the lead posts after it began; a failure hides once someone writes again. The header reads "Working…" when no task status applies. The spinner is the platform indicator, dropped under reduced motion; each status is announced once. The row is never cached. - New messages arrive on the stream, live or in a reconnect backlog. While the reader is at the end, the list follows; otherwise a "New messages" pill counts others' messages past the latest one the reader has had on screen. **Waiting on you (`KinWaitingScreen`, new).** A list of the same native cards the chat shows, each with its buttons. Each card links to its message in the chat: "Open in chat" scrolls to it. diff --git a/packages/contracts/src/kinChat.test.ts b/packages/contracts/src/kinChat.test.ts index 5f1346d26bb11..83f4ec340b49a 100644 --- a/packages/contracts/src/kinChat.test.ts +++ b/packages/contracts/src/kinChat.test.ts @@ -123,6 +123,7 @@ type SchemaName = { [K in keyof typeof Kin]: (typeof Kin)[K] extends Schema.Top ? K : never; }[keyof typeof Kin]; +const activity = { agentId: "agent-1", phase: "notes_read", since: 1 }; const samples = { KinText: ["", "Hello\nworld", " Markdown "], KinTrimmedText: ["Kin", "Owner name"], @@ -170,8 +171,13 @@ const samples = { { _tag: "chat", chat: summary }, { _tag: "waiting", item: waiting }, ], + KinChatActivityPhase: ["queued", "started", "failed", "idle"], + KinChatActivity: [activity, { ...activity, phase: "budget", resumesAt: 9 }], KinChatStreamEvent: [ { _tag: "backlog", messages: [message], widgets: [widget], lastSeq: 1 }, + { _tag: "backlog", messages: [], widgets: [], lastSeq: 1, activity: null }, + { _tag: "reset", lastSeq: 1, activity }, + { _tag: "activity", ...activity }, { _tag: "reset", lastSeq: 1 }, { _tag: "backlog", messages: [message], widgets: [widget], lastSeq: 1, lastChangeSeq: 2 }, { _tag: "reset", lastSeq: 1, lastChangeSeq: 2 }, diff --git a/packages/contracts/src/kinChat.ts b/packages/contracts/src/kinChat.ts index bc4d828b4f145..0264410520518 100644 --- a/packages/contracts/src/kinChat.ts +++ b/packages/contracts/src/kinChat.ts @@ -257,17 +257,47 @@ export const KinChatListEvent = Schema.Union([ ]); export type KinChatListEvent = typeof KinChatListEvent.Type; +/** What a lead's wake-up is doing for a chat. `idle` clears it. */ +export const KinChatActivityPhase = Schema.Literals([ + "queued", + "budget", + "paused", + "started", + "notes_read", + "notes_write", + "delegating", + "approval", + "scheduling", + "failed", + "reply_late", + "idle", +]); +export type KinChatActivityPhase = typeof KinChatActivityPhase.Type; +export const KinChatActivity = Schema.Struct({ + agentId: KinAgentId, + phase: KinChatActivityPhase, + /** Epoch ms when this phase began. */ + since: NonNegativeInt, + /** Epoch ms when a `budget` phase lifts, when the server knows it. */ + resumesAt: Schema.optional(NonNegativeInt), +}); +export type KinChatActivity = typeof KinChatActivity.Type; + export const KinChatStreamEvent = Schema.Union([ Schema.TaggedStruct("backlog", { messages: Schema.Array(KinMessage), widgets: Schema.Array(KinWidget), lastSeq: NonNegativeInt, lastChangeSeq: Schema.optional(NonNegativeInt), + /** The chat's current activity; null when none. Absent from older servers. */ + activity: Schema.optional(Schema.NullOr(KinChatActivity)), }), Schema.TaggedStruct("reset", { lastSeq: NonNegativeInt, lastChangeSeq: Schema.optional(NonNegativeInt), + activity: Schema.optional(Schema.NullOr(KinChatActivity)), }), + Schema.TaggedStruct("activity", KinChatActivity.fields), Schema.TaggedStruct("message", { message: KinMessage }), Schema.TaggedStruct("widget", { widget: KinWidget }), Schema.TaggedStruct("member", { member: KinChatMember }),