diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index a8ef448a23bc..d0c2209bf5fd 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -149,6 +149,7 @@ jobs: packages/contracts/src/threadMetadataMcp.test.ts \ apps/web/src/components/threadActionMenu.logic.test.ts \ apps/web/src/components/sidebar/threadListFilter.logic.test.ts \ + packages/client-runtime/src/state/threadAttribution.test.ts \ apps/server/src/orchestration-v2/ThreadLaunchService.test.ts \ apps/server/src/orchestration-v2/SubagentProjection.test.ts \ packages/shared/src/threadPlacement.test.ts \ diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 351505c4c666..3d0288f1bbf6 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -76,10 +76,18 @@ export function resolveSidebarRowAccessibility(input: { readonly title: string; readonly statusLabel: string | null; readonly projectDisplayName: string | null; + readonly attributionLabel?: string | null; readonly isActive: boolean; }): { readonly label: string; readonly current: "page" | undefined } { return { - label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "), + label: [ + input.title, + input.statusLabel, + input.projectDisplayName, + input.attributionLabel ? `from ${input.attributionLabel}` : null, + ] + .filter(Boolean) + .join(", "), current: input.isActive ? "page" : undefined, }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 4bd3b3fb86e0..ab7a874106bc 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,5 +1,9 @@ import { SidebarThreadFilterMenu } from "./sidebar/SidebarThreadFilterMenu"; import { matchesThreadListFilter, threadListFilterOf } from "./sidebar/threadListFilter.logic"; +import { + resolveThreadAttributions, + threadAttributionKey, +} from "@t3tools/client-runtime/state/thread-attribution"; import { threadRoutingUpdateFromMenuAction } from "./threadActionMenu.logic"; import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; @@ -333,6 +337,7 @@ const sidebarProviderEntriesAtom = Atom.make((get) => { const EMPTY_PROVIDER_ENTRIES: ReadonlyMap = new Map(); const EMPTY_THREADS: readonly EnvironmentThreadShell[] = []; +const NO_MACHINE_OWNERS = {}; const SETTLED_TAIL_INITIAL_COUNT = 10; const SETTLED_TAIL_PAGE_COUNT = 25; @@ -1104,11 +1109,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const threads = useQuietThreadShells(); const promotingDraftThreadKeys = usePromotingDraftThreadKeys(); const threadListFilter = useClientSettings(threadListFilterOf); - // Search always looks across every inbox and environment. + const founderByEnvironmentId = useClientSettings((settings) => settings.founderByEnvironmentId); + const threadAttributions = resolveThreadAttributions( + threads, + founderByEnvironmentId ?? NO_MACHINE_OWNERS, + ); + const attributionOf = (thread: Pick) => + threadAttributions.get(threadAttributionKey(thread)) ?? "unknown"; + // Search always looks across every inbox, sender and environment. const inboxThreads = threadSearchQuery.trim().length > 0 ? threads - : threads.filter((thread) => matchesThreadListFilter(thread, threadListFilter)); + : threads.filter((thread) => + matchesThreadListFilter(thread, threadListFilter, attributionOf(thread)), + ); const listedThreads = promotingDraftThreadKeys.length === 0 ? inboxThreads @@ -2993,6 +3007,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve hasProjects={projectGroups.length > 0} threadFilter={ filterSidebarV2VisibleThreads( threads, @@ -3465,6 +3480,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } currentEnvironmentId={primaryEnvironmentId} + attribution={attributionOf(thread)} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } diff --git a/apps/web/src/components/settings/NewThreadInboxSettings.tsx b/apps/web/src/components/settings/NewThreadInboxSettings.tsx index 7068e694def4..06c16ea9b5a0 100644 --- a/apps/web/src/components/settings/NewThreadInboxSettings.tsx +++ b/apps/web/src/components/settings/NewThreadInboxSettings.tsx @@ -1,4 +1,11 @@ -import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; +import type { EnvironmentId, Founder } from "@t3tools/contracts"; + +import { + getClientSettings, + updateClientSettings, + useClientSettings, +} from "../../hooks/useSettings"; +import { useEnvironmentIdentities } from "../../state/environments"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { SettingsRow } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -34,3 +41,56 @@ export function NewThreadInboxRow() { /> ); } + +const UNSET = "unset"; + +/** Which founder each machine belongs to, for threads older than inbox attribution. */ +export function MachineOwnersRow() { + const environments = useEnvironmentIdentities(); + const owners = useClientSettings((settings) => settings.founderByEnvironmentId) ?? {}; + const setOwner = (environmentId: EnvironmentId, founder: Founder | null) => { + // Read at change time, so a second quick edit or another tab's edit is not overwritten. + const next = { ...getClientSettings().founderByEnvironmentId }; + if (founder === null) delete next[environmentId]; + else next[environmentId] = founder; + void updateClientSettings({ founderByEnvironmentId: next }); + }; + return ( + +
+ {environments.map(({ environmentId, label }) => { + const owner = owners[environmentId]; + return ( +
+ {label} +
+ +
+
+ ); + })} +
+
+ ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index edadc0c84a17..4456ee906f0d 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -64,7 +64,7 @@ import { scopedIdleCompaction } from "./scopedSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; import { ThreadTitleInstructionsSettings } from "./ThreadTitleInstructionsSettings"; import { SnoozePresetsRow } from "./SnoozePresetsSettings"; -import { NewThreadInboxRow } from "./NewThreadInboxSettings"; +import { MachineOwnersRow, NewThreadInboxRow } from "./NewThreadInboxSettings"; import { useDesktopUpdateState } from "../../state/desktopUpdate"; import { managedTelemetryOffMessage, usePrimaryManagedPolicy } from "../../state/managedPolicy"; import { @@ -1844,6 +1844,7 @@ export function ThreadsSettingsPanel() { {!isProjectScope ? ( + ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index bb1d67cd9f19..01c86ed15480 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -826,6 +826,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/threads", searchTerms: ["inbox owner founder kameron jeff attribute filed"], }, + { + id: "machine-owners", + title: "Machine owners", + to: "/settings/threads", + searchTerms: ["environment founder kameron jeff attribution from sender badge"], + }, { id: "add-project-starts-in", title: "Add project starts in", diff --git a/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx b/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx index 466eb7bb93bc..09d9379753de 100644 --- a/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx @@ -4,6 +4,11 @@ import { type Founder, type InboxChoice, } from "@t3tools/contracts"; +import { + THREAD_ATTRIBUTION_LABELS, + THREAD_ATTRIBUTIONS, +} from "@t3tools/client-runtime/state/thread-attribution"; +import type { ThreadAttribution } from "@t3tools/contracts/settings"; import { SlidersHorizontalIcon } from "lucide-react"; import type { ReactNode } from "react"; @@ -38,15 +43,17 @@ const INBOX_LABELS: Record = { shared: "Shared", }; -type CountedThreads = Parameters[0]; +type CountedThread = Parameters[0][number]; const LAST_OPTION_NOTE = ", the last one shown, so it stays checked"; /** Chooses which inboxes and environments the thread list shows. Search still finds every thread. */ -export function SidebarThreadFilterMenu({ +export function SidebarThreadFilterMenu({ countedThreads, + attributionOf, }: { /** Called only while the menu is open. */ - countedThreads: () => CountedThreads; + countedThreads: () => ReadonlyArray; + attributionOf: (thread: T) => ThreadAttribution; }) { const filter = useClientSettings(threadListFilterOf); const owner = useClientSettings((settings) => settings.founderInboxOwner); @@ -61,11 +68,16 @@ export function SidebarThreadFilterMenu({ changed.environments ? `${hiddenCount} environment${hiddenCount === 1 ? "" : "s"} hidden` : null, + changed.from + ? `from ${THREAD_ATTRIBUTIONS.filter((from) => !filter.hiddenAttributions.includes(from)) + .map((from) => THREAD_ATTRIBUTION_LABELS[from]) + .join(", ")}` + : null, ].filter((part) => part !== null); const label = summary.length === 0 - ? "Filter threads by inbox and environment" - : `Filter threads by inbox and environment (${summary.join("; ")})`; + ? "Filter threads by inbox, sender and environment" + : `Filter threads by inbox, sender and environment (${summary.join("; ")})`; return ( }> @@ -80,6 +92,7 @@ export function SidebarThreadFilterMenu({ ({ countedThreads, + attributionOf, filter, owner, environments, isChanged, }: { - countedThreads: () => CountedThreads; + countedThreads: () => ReadonlyArray; + attributionOf: (thread: T) => ThreadAttribution; filter: ThreadListFilter; owner: Founder | undefined; environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>; isChanged: boolean; }) { const connectedEnvironmentIds = useConnectedEnvironmentIds(); - const counts = threadListFilterCounts(countedThreads(), filter); + const counts = threadListFilterCounts(countedThreads(), filter, attributionOf); + const shownAttributions = THREAD_ATTRIBUTIONS.filter( + (from) => !filter.hiddenAttributions.includes(from), + ); const inboxOrder = inboxMenuOrder(owner); const environmentIds = environments.map((environment) => environment.environmentId); const shownEnvironmentIds = environmentIds.filter( @@ -136,6 +154,33 @@ function SidebarThreadFilterOptions({ ); })} + + + From + {THREAD_ATTRIBUTIONS.map((from) => { + const checked = shownAttributions.includes(from); + const isLast = checked && shownAttributions.length === 1; + const count = counts.from.get(from) ?? 0; + return ( + { + const shown = toggleFilterOption(shownAttributions, from, THREAD_ATTRIBUTIONS); + void updateClientSettings({ + sidebarHiddenThreadAttributions: THREAD_ATTRIBUTIONS.filter( + (candidate) => !shown.includes(candidate), + ), + }); + }} + > + + + ); + })} + {environments.length > 1 ? ( <> @@ -189,6 +234,7 @@ function SidebarThreadFilterOptions({ void updateClientSettings({ founderInboxFilter: effectiveInboxFilter({ founderInboxOwner: owner }), sidebarHiddenEnvironmentIds: [], + sidebarHiddenThreadAttributions: [], }) } > diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index d901418db85a..12f79eb6a843 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -36,11 +36,13 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; -import type { TimestampFormat } from "@t3tools/contracts/settings"; +import type { ThreadAttribution, TimestampFormat } from "@t3tools/contracts/settings"; +import { THREAD_ATTRIBUTION_LABELS } from "@t3tools/client-runtime/state/thread-attribution"; import { AlarmClockIcon, AlarmClockOffIcon, ArrowRightLeftIcon, + BotIcon, CheckIcon, CircleAlertIcon, CircleCheckIcon, @@ -442,6 +444,31 @@ type SortableThreadRowBag = Pick< "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging" >; +const ATTRIBUTION_INITIALS: Record = { + kameron: "K", + "kameron-agents": "K", + jeff: "J", + "jeff-agents": "J", + unknown: "?", +}; + +/** Who the thread came from; the row's accessible name carries the full label. */ +function ThreadAttributionBadge({ attribution }: { attribution: ThreadAttribution }) { + return ( + + {ATTRIBUTION_INITIALS[attribution]} + {attribution.endsWith("-agents") ? : null} + + ); +} + export const draftSurfaceClassName = "bg-warning/4 hover:bg-warning/8"; export const draftPenClassName = "size-3 shrink-0 text-warning-foreground"; @@ -574,6 +601,7 @@ type SidebarThreadRowProps = { readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; currentEnvironmentId: string | null; + attribution: ThreadAttribution; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; scratchMachineLabel: string | null; @@ -1037,6 +1065,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP title: thread.title, statusLabel: topStatus?.label ?? null, projectDisplayName: props.projectDisplayName, + attributionLabel: + props.attribution === "unknown" ? null : THREAD_ATTRIBUTION_LABELS[props.attribution], isActive: props.isActive, }); @@ -1158,6 +1188,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) ) : null; + const attributionBadge = ; const remoteMachineIcon = isRemote && !showsScratchMachine ? ( @@ -1205,6 +1236,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > + {attributionBadge} {remoteMachineIcon} + {attributionBadge} {remoteMachineIcon} { expect(matchesThreadListFilter(thread(laptop, kameron), hidingCrown)).toBe(true); }); - it("counts each section within the other section's selection", () => { + it("counts each section within the other sections' selection", () => { const threads = [ - thread(laptop, kameron), - thread(laptop, bot), - thread(crown, jeff), - thread(crown, kameron), + { ...thread(laptop, kameron), from: "kameron" as const }, + { ...thread(laptop, bot), from: "kameron-agents" as const }, + { ...thread(crown, jeff), from: "jeff" as const }, + { ...thread(crown, kameron), from: "kameron" as const }, + { ...thread(laptop, kameron), from: "unknown" as const }, ]; - const counts = threadListFilterCounts(threads, { - inboxes: ["kameron"], - hiddenEnvironmentIds: [crown], - }); + const counts = threadListFilterCounts( + threads, + { inboxes: ["kameron"], hiddenEnvironmentIds: [crown], hiddenAttributions: ["unknown"] }, + (candidate) => candidate.from, + ); expect(Object.fromEntries(counts.inboxes)).toEqual({ kameron: 1, agents: 1 }); expect(Object.fromEntries(counts.environments)).toEqual({ laptop: 1, crown: 1 }); + expect(Object.fromEntries(counts.from)).toEqual({ kameron: 1, unknown: 1 }); + expect( + matchesThreadListFilter( + threads[4]!, + threadListFilterOf({ sidebarHiddenThreadAttributions: ["unknown"] }), + "unknown", + ), + ).toBe(false); + // Notifications pass no attribution, so the From section does not silence them. + expect( + matchesThreadListFilter( + threads[4]!, + threadListFilterOf({ sidebarHiddenThreadAttributions: ["unknown"] }), + ), + ).toBe(true); }); it("reports only sections that differ from this device's default", () => { @@ -62,6 +79,7 @@ describe("thread list filter", () => { expect(changedThreadListFilters(unchanged, "jeff", environments)).toEqual({ inboxes: false, environments: false, + from: false, }); const reordered = { ...unchanged, inboxes: ["agents", "jeff"] as const }; expect(changedThreadListFilters(reordered, "jeff", environments).inboxes).toBe(false); @@ -74,7 +92,7 @@ describe("thread list filter", () => { "jeff", environments, ), - ).toEqual({ inboxes: false, environments: true }); + ).toEqual({ inboxes: false, environments: true, from: false }); }); it("toggles in menu order and never unchecks the last option", () => { diff --git a/apps/web/src/components/sidebar/threadListFilter.logic.ts b/apps/web/src/components/sidebar/threadListFilter.logic.ts index 94840afb100a..5699d5b92fd0 100644 --- a/apps/web/src/components/sidebar/threadListFilter.logic.ts +++ b/apps/web/src/components/sidebar/threadListFilter.logic.ts @@ -7,11 +7,12 @@ import { type EnvironmentId, type ThreadInbox, } from "@t3tools/contracts"; -import type { ClientSettings } from "@t3tools/contracts/settings"; +import type { ClientSettings, ThreadAttribution } from "@t3tools/contracts/settings"; export interface ThreadListFilter { readonly inboxes: ReadonlyArray; readonly hiddenEnvironmentIds: ReadonlyArray; + readonly hiddenAttributions: ReadonlyArray; } interface FilterableThread { @@ -25,11 +26,15 @@ interface FilterableThread { export const threadListFilterOf = ( settings: Pick< ClientSettings, - "founderInboxFilter" | "founderInboxOwner" | "sidebarHiddenEnvironmentIds" + | "founderInboxFilter" + | "founderInboxOwner" + | "sidebarHiddenEnvironmentIds" + | "sidebarHiddenThreadAttributions" >, ): ThreadListFilter => ({ inboxes: effectiveInboxFilter(settings), hiddenEnvironmentIds: settings.sidebarHiddenEnvironmentIds ?? [], + hiddenAttributions: settings.sidebarHiddenThreadAttributions ?? [], }); const matchesInboxes = (thread: FilterableThread, inboxes: ReadonlyArray) => @@ -39,8 +44,14 @@ const matchesInboxes = (thread: FilterableThread, inboxes: ReadonlyArray +/** Without an attribution (notifications), the From section does not apply. */ +export const matchesThreadListFilter = ( + thread: FilterableThread, + filter: ThreadListFilter, + attribution?: ThreadAttribution, +) => !filter.hiddenEnvironmentIds.includes(thread.environmentId) && + (attribution === undefined || !filter.hiddenAttributions.includes(attribution)) && matchesInboxes(thread, filter.inboxes); /** The chosen founder's inbox first, then Agents, so the common pair sits together. */ @@ -77,34 +88,43 @@ export function changedThreadListFilters( filter: ThreadListFilter, owner: Founder | undefined, environmentIds: ReadonlyArray, -): { readonly inboxes: boolean; readonly environments: boolean } { +): { readonly inboxes: boolean; readonly environments: boolean; readonly from: boolean } { return { inboxes: !sameMembers(filter.inboxes, effectiveInboxFilter({ founderInboxOwner: owner })), environments: filter.hiddenEnvironmentIds.some((id) => environmentIds.includes(id)), + from: filter.hiddenAttributions.length > 0, }; } +const increment = (counts: Map, key: K) => + counts.set(key, (counts.get(key) ?? 0) + 1); + /** - * Faceted counts: each inbox counts threads in the shown environments, and each environment - * counts threads in the chosen inboxes, so a count is what checking that option would add. + * Faceted counts: each section counts threads that pass the other two sections, so a count + * is what checking that option would add. */ -export function threadListFilterCounts( - threads: ReadonlyArray, +export function threadListFilterCounts( + threads: ReadonlyArray, filter: ThreadListFilter, + attributionOf: (thread: T) => ThreadAttribution, ) { const inboxes = new Map(); const environments = new Map(); + const from = new Map(); for (const thread of threads) { - if (!filter.hiddenEnvironmentIds.includes(thread.environmentId)) { + const attribution = attributionOf(thread); + const environmentShown = !filter.hiddenEnvironmentIds.includes(thread.environmentId); + const fromShown = !filter.hiddenAttributions.includes(attribution); + const inboxShown = matchesInboxes(thread, filter.inboxes); + if (environmentShown && fromShown) { for (const choice of InboxChoice.literals) { - if (matchesInboxes(thread, [choice])) inboxes.set(choice, (inboxes.get(choice) ?? 0) + 1); + if (matchesInboxes(thread, [choice])) increment(inboxes, choice); } } - if (matchesInboxes(thread, filter.inboxes)) { - environments.set(thread.environmentId, (environments.get(thread.environmentId) ?? 0) + 1); - } + if (inboxShown && fromShown) increment(environments, thread.environmentId); + if (inboxShown && environmentShown) increment(from, attribution); } - return { inboxes, environments }; + return { inboxes, environments, from }; } /** Toggles one option, keeping at least one checked so the list never empties by accident. */ diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d303b27c879f..8aa773bb8d07 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -339,6 +339,10 @@ "types": "./src/state/threads.ts", "default": "./src/state/threads.ts" }, + "./state/thread-attribution": { + "types": "./src/state/threadAttribution.ts", + "default": "./src/state/threadAttribution.ts" + }, "./state/thread-activity-announcement": { "types": "./src/state/threadActivityAnnouncement.ts", "default": "./src/state/threadActivityAnnouncement.ts" diff --git a/packages/client-runtime/src/state/threadAttribution.test.ts b/packages/client-runtime/src/state/threadAttribution.test.ts new file mode 100644 index 000000000000..d4753ebeb90b --- /dev/null +++ b/packages/client-runtime/src/state/threadAttribution.test.ts @@ -0,0 +1,87 @@ +import { EnvironmentId, makeThreadInbox, ThreadId, type ThreadInbox } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { resolveThreadAttributions, type AttributableThread } from "./threadAttribution.ts"; + +const asus = EnvironmentId.make("asus"); +const air = EnvironmentId.make("air"); +const kameron = { kind: "human", id: "kameron" } as const; +const jeff = { kind: "human", id: "jeff" } as const; +const bot = { kind: "agent", id: "lead" } as const; +const thread = ( + id: string, + inbox: ThreadInbox | null, + options: { environmentId?: EnvironmentId; parent?: string; createdBy?: string } = {}, +): AttributableThread => ({ + environmentId: options.environmentId ?? asus, + id: ThreadId.make(id), + lineage: { parentThreadId: options.parent ? ThreadId.make(options.parent) : null }, + source: { inbox, createdBy: options.createdBy }, +}); +const attributions = ( + threads: ReadonlyArray, + owners: Readonly> = {}, +) => + Object.fromEntries( + [...resolveThreadAttributions(threads, owners)].map(([key, value]) => [ + key.split(":")[1], + value, + ]), + ); + +describe("thread attribution", () => { + it("names the founder, or the founder whose agents did the work", () => { + expect( + attributions([ + thread("k", makeThreadInbox({ actor: kameron })), + thread("j", makeThreadInbox({ actor: jeff })), + // An agent asked by Jeff, even when the work was filed to Kameron. + thread( + "asked", + makeThreadInbox({ actor: bot, requestedBy: jeff, routing: { owner: "kameron" } }), + ), + thread("owned", makeThreadInbox({ actor: bot, routing: { owner: "kameron" } })), + ]), + ).toEqual({ k: "kameron", j: "jeff", asked: "jeff-agents", owned: "kameron-agents" }); + }); + + it("takes an unowned agent thread's founder from its parent chain", () => { + const parent = makeThreadInbox({ actor: jeff }); + expect( + attributions([ + // Listed before its parent, so resolution cannot depend on order. + thread("grandchild", makeThreadInbox({ actor: bot }), { parent: "child" }), + thread("child", makeThreadInbox({ actor: bot }), { parent: "root" }), + thread("root", parent), + ]), + ).toEqual({ grandchild: "jeff-agents", child: "jeff-agents", root: "jeff" }); + }); + + it("falls back to the machine's owner for history, and never guesses", () => { + const owners = { [air]: "jeff" } as const; + expect( + attributions( + [ + thread("old-human", null, { environmentId: air }), + thread("old-agent", null, { environmentId: air, createdBy: "agent" }), + thread("unmapped", null), + // Routed agent work with no founder anywhere is Unknown, even on a mapped machine. + thread("unowned-agent", makeThreadInbox({ actor: bot }), { environmentId: air }), + thread("orphan", makeThreadInbox({ actor: bot }), { environmentId: air, parent: "gone" }), + // A lineage cycle still resolves. + thread("a", makeThreadInbox({ actor: bot }), { parent: "b" }), + thread("b", makeThreadInbox({ actor: bot }), { parent: "a" }), + ], + owners, + ), + ).toEqual({ + "old-human": "jeff", + "old-agent": "jeff-agents", + unmapped: "unknown", + "unowned-agent": "unknown", + orphan: "unknown", + a: "unknown", + b: "unknown", + }); + }); +}); diff --git a/packages/client-runtime/src/state/threadAttribution.ts b/packages/client-runtime/src/state/threadAttribution.ts new file mode 100644 index 000000000000..8cf8740e4126 --- /dev/null +++ b/packages/client-runtime/src/state/threadAttribution.ts @@ -0,0 +1,87 @@ +import type { EnvironmentId, Founder, ThreadId, ThreadInbox } from "@t3tools/contracts"; +import { ThreadAttribution } from "@t3tools/contracts/settings"; + +export const THREAD_ATTRIBUTIONS = ThreadAttribution.literals; + +export const THREAD_ATTRIBUTION_LABELS: Record = { + kameron: "Kameron", + "kameron-agents": "Kameron's agents", + jeff: "Jeff", + "jeff-agents": "Jeff's agents", + unknown: "Unknown", +}; + +export interface AttributableThread { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + readonly lineage: { readonly parentThreadId: ThreadId | null }; + readonly source: { + readonly inbox?: ThreadInbox | null | undefined; + readonly createdBy?: string | undefined; + }; +} + +/** Machine owners, chosen in Settings; nothing is assumed for an unmapped machine. */ +type FounderByEnvironmentId = Readonly>>; + +export const threadAttributionKey = (thread: { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; +}) => `${thread.environmentId}:${thread.id}`; + +const attributionOf = (founder: Founder, byAgent: boolean): ThreadAttribution => + byAgent ? `${founder}-agents` : founder; + +const founderOfAttribution = (attribution: ThreadAttribution): Founder | null => + attribution === "unknown" ? null : attribution.startsWith("jeff") ? "jeff" : "kameron"; + +const humanFounder = (actor: ThreadInbox["origin"] | undefined): Founder | null => + actor?.kind === "human" ? actor.id : null; + +/** + * Resolves every thread's attribution, keyed by `threadAttributionKey`. A human origin or + * requester is that founder; agent work takes its requester's or owner's founder, else its + * parent's; only history without inbox fields falls back to the machine's owner. + */ +export function resolveThreadAttributions( + threads: ReadonlyArray, + founderByEnvironmentId: FounderByEnvironmentId, +): ReadonlyMap { + const byKey = new Map(threads.map((thread) => [threadAttributionKey(thread), thread])); + const resolved = new Map(); + const resolving = new Set(); + const resolve = (key: string, thread: AttributableThread): ThreadAttribution => { + const known = resolved.get(key); + if (known !== undefined) return known; + // A lineage cycle resolves the repeated thread without its parent. + resolving.add(key); + const inbox = thread.source.inbox; + const byAgent = inbox?.origin?.kind === "agent" || thread.source.createdBy === "agent"; + const parentKey = + thread.lineage.parentThreadId === null + ? null + : `${thread.environmentId}:${thread.lineage.parentThreadId}`; + const parent = + parentKey === null || resolving.has(parentKey) ? undefined : byKey.get(parentKey); + const founder = + humanFounder(inbox?.origin) ?? + humanFounder(inbox?.requestedBy) ?? + (inbox?.origin?.kind === "agent" + ? (inbox.owner ?? + (parent && parentKey ? founderOfAttribution(resolve(parentKey, parent)) : null)) + : null) ?? + // Only history from before inbox routing falls back to the machine: a shared machine + // runs both founders' agents, so crediting routed work to its owner would be a guess. + (inbox ? null : founderByEnvironmentId[thread.environmentId]) ?? + null; + const attribution = + founder === null + ? "unknown" + : attributionOf(founder, byAgent && humanFounder(inbox?.origin) === null); + resolving.delete(key); + resolved.set(key, attribution); + return attribution; + }; + for (const [key, thread] of byKey) resolve(key, thread); + return resolved; +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index d91ab131da19..5e6917eb2819 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -403,11 +403,23 @@ export const VoiceTranscriptionDestination = Schema.Union([ ]); export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type; +/** Who a thread came from, for the sidebar's From filter and row badges. */ +export const ThreadAttribution = Schema.Literals([ + "kameron", + "kameron-agents", + "jeff", + "jeff-agents", + "unknown", +]); +export type ThreadAttribution = typeof ThreadAttribution.Type; + export const ClientSettingsSchema = Schema.Struct({ // Absent until chosen; whole-snapshot saves must not record a default as a choice. founderInboxOwner: Schema.optionalKey(Founder), founderInboxFilter: Schema.optionalKey(Schema.Array(InboxChoice)), sidebarHiddenEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)), + sidebarHiddenThreadAttributions: Schema.optionalKey(Schema.Array(ThreadAttribution)), + founderByEnvironmentId: Schema.optionalKey(Schema.Record(EnvironmentId, Founder)), notificationMode: NotificationMode.pipe( Schema.withDecodingDefault(Effect.succeed("off" as const)), ), @@ -2057,6 +2069,8 @@ export const ClientSettingsPatch = Schema.Struct({ founderInboxOwner: Schema.optionalKey(Founder), founderInboxFilter: Schema.optionalKey(Schema.Array(InboxChoice)), sidebarHiddenEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)), + sidebarHiddenThreadAttributions: Schema.optionalKey(Schema.Array(ThreadAttribution)), + founderByEnvironmentId: Schema.optionalKey(Schema.Record(EnvironmentId, Founder)), notificationMode: Schema.optionalKey(NotificationMode), inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean), diffColorScheme: Schema.optionalKey(DiffColorScheme),