Skip to content
Closed
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
55 changes: 50 additions & 5 deletions apps/mobile/src/features/chats/KinChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
EnvironmentId,
KinChatId,
type KinChatHistoryInput,
type KinChatActivity,
type KinChatHistoryResult,
type KinMessage,
} from "@t3tools/contracts";
Expand All @@ -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";
Expand Down Expand Up @@ -51,6 +52,7 @@ import {
kinDraftKey,
} from "./components/KinComposer";
import { KinFoldLine } from "./components/KinFoldLine";
import { KinActivityRow, kinActivityLabel } from "./components/KinActivityRow";
import {
KinDayLine,
KinMessageBubble,
Expand All @@ -61,6 +63,7 @@ import {
buildKinFeedRows,
initialKinPaging,
kinActivePaging,
kinActivityWorking,
kinChatScreenState,
kinChatStatusLine,
kinEarlierPage,
Expand All @@ -69,6 +72,7 @@ import {
kinMarkReadRearms,
kinRowSeq,
kinSeqToMarkRead,
kinShownActivity,
kinUnseenCount,
latestKinSeq,
mergeKinFeed,
Expand Down Expand Up @@ -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 (
<View collapsable={false} className="flex-1 bg-screen">
<AppBar title={props.title} subtitle={subtitle} onBack={() => navigation.goBack()} />
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<KinChatRow> =
pending.length === 0
pending.length === 0 && activity === null
? feedRows
: [
...feedRows,
Expand All @@ -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<string | null>(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;
Expand Down Expand Up @@ -603,7 +644,9 @@ function KinChatFeed(props: {
const markSeen = ({ viewableItems }: OnViewableItemsChangedInfo<KinChatRow>) => {
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 });
};
Expand Down Expand Up @@ -661,6 +704,8 @@ function KinChatFeed(props: {
);
case "day":
return <KinDayLine row={item} />;
case "activity":
return <KinActivityRow activity={item.activity} agentName={item.agentName} />;
}
};

Expand Down
62 changes: 62 additions & 0 deletions apps/mobile/src/features/chats/components/KinActivityRow.tsx
Original file line number Diff line number Diff line change
@@ -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<string | null>(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 (
<View
accessible
accessibilityLabel={kinActivityLabel(activity, props.agentName, stillKey === phaseKey)}
className="items-start gap-1 px-4 pb-1.5"
>
<Text textRole="caption" className="px-1 pt-2 font-t3-medium text-foreground-muted">
{props.agentName}
</Text>
<View className="max-w-[85%] flex-row items-center gap-2 px-1">
{busy && !reduceMotion ? <AppActivityIndicator size="small" /> : null}
<Text textRole="body" className="shrink text-foreground-muted">
{copy}
</Text>
</View>
</View>
);
}
91 changes: 90 additions & 1 deletion apps/mobile/src/features/chats/state/kinChatFeed.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -16,6 +22,8 @@ import {
initialKinPaging,
KIN_HISTORY_PAGE_SIZE,
kinActivePaging,
kinActivityCopy,
KIN_STILL_WORKING_MS,
kinChatScreenState,
kinChatStatusLine,
kinDayLabel,
Expand All @@ -29,6 +37,8 @@ import {
kinMarkReadRearms,
kinRowSeq,
kinSeqToMarkRead,
kinShownActivity,
kinStillWorkingIn,
kinUnseenCount,
mergeKinFeed,
type KinFeedRow,
Expand Down Expand Up @@ -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<KinChatActivity> = {}) =>
({ 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();
});
});
Loading