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
9 changes: 6 additions & 3 deletions apps/mobile/src/features/usage/UsageKinCacheLine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
kinCacheDayLine,
kinCacheLabel,
} from "@t3tools/client-runtime/kin/kinCacheDaily";
import { useMessages } from "gt-react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/reactivity";
Expand Down Expand Up @@ -51,6 +52,7 @@ function KinCacheLines(props: {
readonly environmentId: EnvironmentId;
readonly label: string | null;
}) {
const messages = useMessages();
const result = useAtomValue(
kinClient.cacheDays({ environmentId: props.environmentId, input: {} }),
);
Expand All @@ -62,9 +64,10 @@ function KinCacheLines(props: {
<Text className="text-sm leading-5 font-medium text-foreground">{props.label}</Text>
)}
{days !== null ? (
[kinCacheDayLine("today", days.day), kinCacheDayLine("yesterday", days.before)].map(
(line) => <DayLine key={line.label} label={line.label} body={line.body} />,
)
[
kinCacheDayLine("today", days.day, messages),
kinCacheDayLine("yesterday", days.before, messages),
].map((line) => <DayLine key={line.label} label={line.label} body={line.body} />)
) : failed ? (
<View className="flex-row flex-wrap items-center gap-3">
<Text className={LINE}>{KIN_CACHE_DAILY_COPY.failed}</Text>
Expand Down
127 changes: 126 additions & 1 deletion apps/server/src/kin/chat/KinChatService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
EnvironmentId,
KinAgentId,
KinChatId,
KinPendingAction,
KinKeyThumbprint,
KinMemberId,
type KinChatListEvent,
Expand Down Expand Up @@ -75,7 +76,12 @@ import { ServerSettingsService } from "../../serverSettings.ts";
import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts";
import type { McpInvocationScope } from "../../mcp/McpInvocationContext.ts";
import { KinKeyNotices } from "../approvals/ExecutionNotices.ts";
import { keyNoticeBody, keyNoticesLayer } from "./executionNotices.ts";
import {
keyNoticeBody,
keyNoticesLayer,
layer as executionNoticesLayer,
} from "./executionNotices.ts";
import { KinExecutionNotices } from "../approvals/ExecutionNotices.ts";
import * as Hub from "./KinChatHub.ts";
import * as RefreshHub from "./KinRefreshHub.ts";
import * as Repository from "./KinChatRepository.ts";
Expand All @@ -102,6 +108,7 @@ const decodeKinMemberId = Schema.decodeSync(KinMemberId);
const decodeThreadId = Schema.decodeSync(ThreadId);
const decodeTask = Schema.decodeUnknownEffect(KinTaskCardState);
const decodeSend = Schema.decodeUnknownEffect(KinMessagesSendInput);
const decodePendingAction = Schema.decodeSync(KinPendingAction);
const database = authorityLayer;
const repositories = Layer.provideMerge(Repository.layer, database);
const dependencies = Layer.provideMerge(Layer.merge(Hub.layer, RefreshHub.layer), repositories);
Expand Down Expand Up @@ -321,6 +328,124 @@ const seed = Effect.fn("test.seed")(function* (
return { repo, service, identity, person, agent, chat };
});

it.effect(
"execution notices keep the owner's result direct and copy only a co-owner chat's own result",
() =>
Effect.gen(function* () {
const { repo, service, identity, person, chat } = yield* seed();
const sql = yield* SqlClient.SqlClient;
const notices = yield* KinExecutionNotices;
const { orgId } = person;
const meera = KinPersonId.make("meera");
yield* sql`INSERT INTO kin_people (org_id, person_id, handle, display_name, created_at, access)
VALUES (${orgId}, ${meera}, 'meera', 'Meera', ${timestamp}, 'co_owner')`;
const other = yield* service.createDirect({ ...person, personId: meera }, { orgId, agentId });
const group = yield* repo.createChat({
orgId,
chatId: KinChatId.make("dispatch"),
kind: "team_group",
title: "Dispatch",
teamId: null,
directKey: null,
lastMessageAt: null,
createdAt: timestamp,
archivedAt: null,
});
yield* repo.addMember({
orgId,
chatId: group.chatId,
memberId: KinMemberId.make("dispatch-rhea"),
principal: { _tag: "person", personId: person.personId },
role: "owner",
joinedAt: timestamp,
leftAt: null,
mutedUntil: null,
});
for (const [name, source, to, expected] of [
["legacy", threadId, undefined, [chat.chatId]],
["owner", ThreadId.make("kin:owner-chat:dispatch"), group.chatId, [chat.chatId]],
["mixed", ThreadId.make("kin:mixed-wake:dispatch"), group.chatId, [chat.chatId]],
["co-owner", ThreadId.make("kin:meera"), other.chatId, [chat.chatId, other.chatId]],
] as const) {
if (to !== undefined)
yield* identity.registerAgentThread({ orgId, agentId, threadId: source, chatId: to });
const action = decodePendingAction({
id: `delete-${name}`,
orgId,
idempotencyKey: "a".repeat(64),
kind: "delete_branch",
target: {
_tag: "branch",
host: "github.com",
repo: "invented/dispatch",
ref: "finished",
},
resolved: { _tag: "branch", headSha: "a".repeat(40) },
targetDigest: "b".repeat(64),
nonce: "invented",
revision: 1,
reason: "Merged",
requestedBy: { agentId, threadId: source },
provenance: {
startedBy: { humanId: name === "co-owner" ? meera : person.personId },
startedByRole: "owner",
chain: [],
ceilingBelowOwner: false,
},
requiredApprovers: [{ role: "owner" }],
state: "succeeded",
createdAt: timestamp,
updatedAt: timestamp,
expiresAt: timestamp,
});
yield* sql`INSERT INTO kin_pending_actions (action_id, org_id, idempotency_key,
kind, target_json, resolved_json, target_digest, nonce, revision, reason,
requested_by_agent_id, requested_by_thread_id, provenance_json, required_approvers_json,
state, created_at, updated_at, expires_at)
VALUES (${action.id}, ${orgId}, ${name}, ${action.kind}, '{}', '{}', 'fixture', 'nonce', 1,
'Merged', ${agentId}, ${source}, '{}', '[]', 'succeeded', 0, 0, 0)`;
yield* sql`INSERT INTO kin_grants (grant_id, org_id, action_id, revision, jti,
approver_human_id, key_thumbprint, compact, iat_s, exp_s, accepted_at)
VALUES (${name}, ${orgId}, ${action.id}, 1, ${name}, ${meera}, 'key', 'fixture', 0, 1, 0)`;
const finished = notices.finished({ action, outcome: "succeeded" });
yield* finished;
yield* finished;
const destinations = yield* sql<{ chat_id: KinChatId }>`SELECT chat_id FROM kin_messages
WHERE org_id = ${orgId} AND message_id IN (${`kin-exec:${action.id}`}, ${`kin-exec-asked:${action.id}`})
ORDER BY message_id DESC`;
assert.sameMembers(
destinations.map(({ chat_id }) => chat_id),
[...expected],
name,
);
}
}).pipe(Effect.provide(Layer.provideMerge(executionNoticesLayer, layer))),
);

it.effect("reopening a former reader's direct chat ends its old thread", () =>
Effect.gen(function* () {
const { repo, service, identity, person } = yield* seed();
const sql = yield* SqlClient.SqlClient;
const { orgId } = person;
const meera = KinPersonId.make("meera");
const viewer = { ...person, personId: meera };
yield* sql`INSERT INTO kin_people (org_id, person_id, handle, display_name, created_at, access)
VALUES (${orgId}, ${meera}, 'meera', 'Meera', ${timestamp}, 'co_owner')`;
const chat = yield* service.createDirect(viewer, { orgId, agentId });
const member = (yield* repo.listMembers(chat)).find((row) => row.principal._tag === "person")!;
yield* repo.leaveChat({ ...member, leftAt: timestamp });
const former = ThreadId.make("kin:meera-former");
yield* identity.registerAgentThread({ orgId, agentId, threadId: former, chatId: chat.chatId });
assert.strictEqual(
(yield* service.createDirect(viewer, { orgId, agentId })).chatId,
chat.chatId,
);
const [thread] = yield* sql<{ ended_at: string | null }>`SELECT ended_at FROM kin_agent_threads
WHERE org_id = ${orgId} AND thread_id = ${former}`;
assert.isString(thread?.ended_at);
}).pipe(Effect.provide(layer)),
);

const progressSettings = Effect.fnUntraced(function* (flipOnRead = false) {
const settings = yield* Ref.make({
...DEFAULT_SERVER_SETTINGS,
Expand Down
21 changes: 20 additions & 1 deletion apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ import { hasTurnChanges } from "../lead/turnChanges.ts";
import * as Repository from "./KinChatRepository.ts";
import type { WriteAudience } from "./KinChatRepository.ts";
import { KinAttachmentStore } from "./KinAttachmentStore.ts";
import type { AgentIdentity, PersonIdentity } from "./KinIdentity.ts";
import { KinIdentity, type AgentIdentity, type PersonIdentity } from "./KinIdentity.ts";
import { finishPersonJoin, onPersonJoined } from "../lead/ChatSharing.ts";
import { roomReadable } from "./memberAccess.ts";
import * as Reactions from "./reactions.ts";
import * as LeadAccess from "../lead/LeadAccess.ts";
Expand Down Expand Up @@ -837,6 +838,7 @@ const make = Effect.gen(function* () {
// Absent where no attachments directory exists; a send with files is then refused.
const attachmentStore = yield* Effect.serviceOption(KinAttachmentStore);
const stop = yield* Effect.serviceOption(KinStop);
const identities = yield* Effect.serviceOption(KinIdentity);
// A deferral card's [Start now] hands its work to the lead's queue in the tap's transaction.
const queue = yield* Effect.serviceOption(KinEventQueue);
/** For a stream event; left out of a chat that was never cleared. */
Expand Down Expand Up @@ -3907,6 +3909,23 @@ const make = Effect.gen(function* () {
leftAt: null,
mutedUntil: null,
});
if (mine.leftAt !== null) {
const join = yield* onPersonJoined({
orgId: chat.orgId,
chatId: chat.chatId,
personId: person.personId,
}).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
Effect.mapError(toPersistenceSqlError("KinChatService.directRejoin")),
);
yield* finishPersonJoin(chat, join, {
repo,
hub,
...(Option.isSome(identities) ? { identity: identities.value } : {}),
...(Option.isSome(stop) ? { stop: stop.value } : {}),
...(Option.isSome(presence) ? { presence: presence.value } : {}),
}).pipe(Effect.provideService(SqlClient.SqlClient, sql));
}
yield* hub.publish({
type: "member.updated",
orgId: chat.orgId,
Expand Down
49 changes: 13 additions & 36 deletions apps/server/src/kin/chat/KinGroups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ import * as SqlClient from "effect/sql/SqlClient";
import * as SqlError from "effect/sql/SqlError";

import { toPersistenceSqlError } from "../../persistence/Errors.ts";
import { freezeMovedCard, onPersonJoined, settleCards, tellStopped } from "../lead/ChatSharing.ts";
import {
finishPersonJoin,
freezeMovedCard,
onPersonJoined,
settleCards,
} from "../lead/ChatSharing.ts";
import { KinStop } from "../lead/KinStop.ts";
import * as Reach from "../lead/Reach.ts";
import { ownerLevel } from "../people/KinAccess.ts";
Expand Down Expand Up @@ -313,41 +318,13 @@ const make = Effect.gen(function* () {
SqlError: (cause) => Effect.fail(toPersistenceSqlError("KinGroups.freezeCard")(cause)),
}),
);
if (shared.expired.length > 0 && Option.isSome(presence)) {
const line = presence.value;
yield* sql.afterCommit(
Effect.forEach(
new Set(shared.expired.map((row) => row.agentId)),
(id) =>
syncQueued(line, chat.orgId, KinAgentId.make(id)).pipe(
Effect.provideService(SqlClient.SqlClient, sql),
),
{ discard: true },
),
);
}
if (shared.stopped.length > 0)
yield* sql.afterCommit(
withChat(tellStopped({ ...chat, lines: shared.stopped })).pipe(
Effect.ignore({ log: "Warn", message: "KinGroups.tellStopped" }),
),
);
if (shared.threads.length > 0)
yield* sql.afterCommit(
Effect.forEach(
shared.threads,
(threadId) =>
identity.endAgentThread({ orgId: chat.orgId, threadId }).pipe(Effect.ignore),
{ discard: true },
),
);
if (shared.turns.length === 0 || Option.isNone(stop)) return;
yield* sql.afterCommit(
stop.value.abortTurns(
chat.orgId,
shared.turns.map((turn) => KinWakeupId.make(turn.wakeupId)),
),
);
yield* finishPersonJoin(chat, shared, {
identity,
repo,
hub,
...(Option.isSome(stop) ? { stop: stop.value } : {}),
...(Option.isSome(presence) ? { presence: presence.value } : {}),
}).pipe(Effect.provideService(SqlClient.SqlClient, sql));
});

/** Tells everyone still in the chat that who is in it, its name or its lead changed. */
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/kin/chat/executionNotices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
type KinExecutionOutcome,
type KinKeyChange,
} from "../approvals/ExecutionNotices.ts";
import { isScopedOwnerWakeThread } from "../lead/sessionAudience.ts";
import { CHIEF_OF_STAFF_DOMAIN } from "../lead/orgLeads.ts";
import { textLocale, type TextClock } from "../work/companyProfile.ts";
import { ownerZone } from "../work/recordRows.ts";
Expand Down Expand Up @@ -85,14 +86,16 @@ export const layer = Layer.effect(
* the request came from when that is a co-owner's own, so whoever asked hears the result.
*/
const post = Effect.fnUntraced(function* (action: KinPendingAction, body: string) {
const source = action.requestedBy.threadId;
const ownerSource = isScopedOwnerWakeThread(source);
const [lead] = yield* sql<{
readonly chatId: string;
readonly askedIn: string | null;
readonly approver: string | null;
}>`
SELECT l.owner_chat_id AS "chatId",
(SELECT t.chat_id FROM kin_agent_threads t WHERE t.org_id = l.org_id
AND t.thread_id = ${action.requestedBy.threadId}) AS "askedIn",
AND t.agent_id = l.agent_id AND t.thread_id = ${source} AND NOT ${ownerSource}) AS "askedIn",
(SELECT p.display_name FROM kin_grants g
JOIN kin_people p ON p.org_id = g.org_id AND p.person_id = g.approver_human_id
JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id
Expand Down
9 changes: 3 additions & 6 deletions apps/server/src/kin/chat/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import * as VisualHosts from "./KinVisualHosts.ts";
import * as Records from "../work/KinRecords.ts";
import { KinIdentity, KinIdentityConfig } from "./KinIdentity.ts";

const identities = KinIdentity.layer.pipe(Layer.provide(KinIdentityConfig.layer));
const stop = Stop.layer.pipe(Layer.provide(Presence.layer), Layer.provideMerge(Queue.layer));

const service = Layer.mergeAll(
Expand All @@ -33,12 +34,8 @@ const service = Layer.mergeAll(
VisualHosts.layer,
).pipe(Layer.provideMerge(stop)),
// A join stops the turns it aborts (`KinGroups.shareWith`) through the stop switch's fan-out.
Groups.layer.pipe(
Layer.provide(Presence.layer),
Layer.provide(stop),
Layer.provideMerge(KinIdentity.layer.pipe(Layer.provide(KinIdentityConfig.layer))),
),
);
Groups.layer.pipe(Layer.provide(Presence.layer), Layer.provide(stop)),
).pipe(Layer.provideMerge(identities));

const storage = Layer.merge(Hub.layer, RefreshHub.layer).pipe(
Layer.provideMerge(Repository.layer),
Expand Down
13 changes: 10 additions & 3 deletions apps/server/src/kin/chat/sharing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,22 @@ const notOwnerSql = (org: string, chat: string, person: string) =>

/**
* In the transaction that makes a member active: a person besides the owner reads from the next
* seq on, and their chat is shared from then, once and for good (`shared_at`). Everything before
* seq on (unless restoring the same reader's history), and the chat is shared once and for good.
* Everything before
* `shared_from_seq` was written for the owner alone. Returns whether this join shared the chat.
*/
export const recordJoin = Effect.fn("KinChatSharing.recordJoin")(function* (
sql: SqlClient.SqlClient,
input: { readonly orgId: string; readonly chatId: string; readonly memberId: string },
input: {
readonly orgId: string;
readonly chatId: string;
readonly memberId: string;
readonly preserveHistory?: true;
},
) {
const now = yield* Clock.currentTimeMillis;
yield* sql`UPDATE kin_chat_members AS m SET joined_seq = CASE
if (input.preserveHistory !== true)
yield* sql`UPDATE kin_chat_members AS m SET joined_seq = CASE
WHEN m.principal_kind = 'person' AND ${sql.literal(notOwnerSql("m.org_id", "m.chat_id", "m.person_id"))}
THEN (SELECT c.last_seq + 1 FROM kin_chats c WHERE c.org_id = m.org_id AND c.chat_id = m.chat_id)
ELSE 0 END
Expand Down
Loading
Loading