@athenaintel/react 0.21.2 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -0
- package/dist/chat/StatewireApprovalCard.cjs +70 -10
- package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
- package/dist/chat/StatewireApprovalCard.d.ts +12 -1
- package/dist/chat/StatewireApprovalCard.js +73 -13
- package/dist/chat/StatewireApprovalCard.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +22 -1
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.d.ts +41 -0
- package/dist/chat/use-statewire-approval-request.js +24 -3
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs +0 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js +0 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js.map +1 -1
- package/dist/collab/client.cjs +4 -9
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.js +2 -7
- package/dist/collab/client.js.map +1 -1
- package/dist/collab/index.cjs +23 -0
- package/dist/collab/index.cjs.map +1 -1
- package/dist/collab/index.d.ts +17 -2
- package/dist/collab/index.js +24 -1
- package/dist/collab/index.js.map +1 -1
- package/dist/collab/mint.cjs +18 -13
- package/dist/collab/mint.cjs.map +1 -1
- package/dist/collab/mint.d.ts +10 -0
- package/dist/collab/mint.js +18 -13
- package/dist/collab/mint.js.map +1 -1
- package/dist/collab/presence-client.cjs +211 -0
- package/dist/collab/presence-client.cjs.map +1 -0
- package/dist/collab/presence-client.d.ts +60 -0
- package/dist/collab/presence-client.js +194 -0
- package/dist/collab/presence-client.js.map +1 -0
- package/dist/collab/presence-mint.cjs +68 -0
- package/dist/collab/presence-mint.cjs.map +1 -0
- package/dist/collab/presence-mint.d.ts +87 -0
- package/dist/collab/presence-mint.js +68 -0
- package/dist/collab/presence-mint.js.map +1 -0
- package/dist/collab/presence-react.cjs +114 -0
- package/dist/collab/presence-react.cjs.map +1 -0
- package/dist/collab/presence-react.d.ts +47 -0
- package/dist/collab/presence-react.js +114 -0
- package/dist/collab/presence-react.js.map +1 -0
- package/dist/collab/presence-slots.cjs +220 -0
- package/dist/collab/presence-slots.cjs.map +1 -0
- package/dist/collab/presence-slots.d.ts +119 -0
- package/dist/collab/presence-slots.js +220 -0
- package/dist/collab/presence-slots.js.map +1 -0
- package/dist/collab/token-refresh.cjs +13 -0
- package/dist/collab/token-refresh.cjs.map +1 -0
- package/dist/collab/token-refresh.d.ts +20 -0
- package/dist/collab/token-refresh.js +13 -0
- package/dist/collab/token-refresh.js.map +1 -0
- package/dist/packages/agent-runtime/src/interrupts.cjs +40 -1
- package/dist/packages/agent-runtime/src/interrupts.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/interrupts.js +40 -1
- package/dist/packages/agent-runtime/src/interrupts.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings for the workspace presence feed.
|
|
3
|
+
*
|
|
4
|
+
* `useWorkspacePresence(workspaceId)` opens (and owns) a
|
|
5
|
+
* `connectWorkspacePresence` handle, resolving auth from the surrounding
|
|
6
|
+
* `AthenaProvider` (per-viewer bearer when present, API key otherwise), and
|
|
7
|
+
* re-renders on status/roster changes via `useSyncExternalStore`. Each person
|
|
8
|
+
* carries a `state` on the intent ladder, recomputed against a clock that
|
|
9
|
+
* ticks every `tickMs` so `active` decays to `idle` and `away` between
|
|
10
|
+
* awareness events.
|
|
11
|
+
*
|
|
12
|
+
* `useWorkspacePresenceResolver(workspaceId)` returns the batch id→title
|
|
13
|
+
* resolver bound to the same auth. It is deliberately thin: callers own
|
|
14
|
+
* caching (TanStack Query is the expected home for it).
|
|
15
|
+
*/
|
|
16
|
+
import { type WorkspacePresenceStatus } from './presence-client';
|
|
17
|
+
import { type WorkspacePresenceResolveRequest, type WorkspacePresenceResolveResponse } from './presence-mint';
|
|
18
|
+
import { type PresenceAgent, type PresenceHuman, type PresenceState } from './presence-slots';
|
|
19
|
+
/** Default cadence for re-deriving each person's intent state. */
|
|
20
|
+
export declare const PRESENCE_DEFAULT_TICK_MS = 10000;
|
|
21
|
+
export interface PresenceHumanWithState extends PresenceHuman {
|
|
22
|
+
/** Where the person sits on the intent ladder as of the last tick. */
|
|
23
|
+
state: PresenceState;
|
|
24
|
+
}
|
|
25
|
+
export interface UseWorkspacePresenceOptions {
|
|
26
|
+
/** `false` closes the feed without unmounting the caller. Default `true`. */
|
|
27
|
+
enabled?: boolean;
|
|
28
|
+
/** How often `state` is re-derived from `lastIntentAt`. Default 10 s. */
|
|
29
|
+
tickMs?: number;
|
|
30
|
+
}
|
|
31
|
+
export interface UseWorkspacePresenceResult {
|
|
32
|
+
/** `'closed'` while disabled or without a workspace; `'connecting'` until the first mint resolves. */
|
|
33
|
+
status: WorkspacePresenceStatus;
|
|
34
|
+
error: Error | null;
|
|
35
|
+
accessType: 'r' | 'rw' | null;
|
|
36
|
+
humans: PresenceHumanWithState[];
|
|
37
|
+
agents: PresenceAgent[];
|
|
38
|
+
/** Force an early token refresh; resolves immediately when no feed is open. */
|
|
39
|
+
refreshNow: () => Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export declare function useWorkspacePresence(workspaceId: string | null, options?: UseWorkspacePresenceOptions): UseWorkspacePresenceResult;
|
|
42
|
+
export type WorkspacePresenceResolver = (request: WorkspacePresenceResolveRequest, signal?: AbortSignal) => Promise<WorkspacePresenceResolveResponse>;
|
|
43
|
+
/**
|
|
44
|
+
* A stable resolver bound to the provider's auth and the given workspace.
|
|
45
|
+
* Rejects when called without a workspace; no caching — callers own that.
|
|
46
|
+
*/
|
|
47
|
+
export declare function useWorkspacePresenceResolver(workspaceId: string | null): WorkspacePresenceResolver;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { useState, useRef, useEffect, useMemo, useSyncExternalStore, useCallback } from "react";
|
|
2
|
+
import { useAthenaConfig } from "../provider/AthenaContext.js";
|
|
3
|
+
import { connectWorkspacePresence } from "./presence-client.js";
|
|
4
|
+
import { resolveWorkspacePresence } from "./presence-mint.js";
|
|
5
|
+
import { derivePresenceState } from "./presence-slots.js";
|
|
6
|
+
const PRESENCE_DEFAULT_TICK_MS = 1e4;
|
|
7
|
+
const EMPTY_SNAPSHOT = "init||0";
|
|
8
|
+
const NO_HUMANS = [];
|
|
9
|
+
const NO_AGENTS = [];
|
|
10
|
+
function useWorkspacePresence(workspaceId, options) {
|
|
11
|
+
const config = useAthenaConfig();
|
|
12
|
+
const enabled = (options == null ? void 0 : options.enabled) !== false && workspaceId !== null;
|
|
13
|
+
const tickMs = (options == null ? void 0 : options.tickMs) ?? PRESENCE_DEFAULT_TICK_MS;
|
|
14
|
+
const [entry, setEntry] = useState(null);
|
|
15
|
+
const handleRef = useRef(null);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!enabled || workspaceId === null) {
|
|
18
|
+
setEntry(null);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const next = connectWorkspacePresence({
|
|
22
|
+
workspaceId,
|
|
23
|
+
auth: {
|
|
24
|
+
backendUrl: config.backendUrl,
|
|
25
|
+
apiKey: config.apiKey,
|
|
26
|
+
token: config.token
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
handleRef.current = next;
|
|
30
|
+
setEntry({ workspaceId, handle: next });
|
|
31
|
+
return () => {
|
|
32
|
+
handleRef.current = null;
|
|
33
|
+
next.destroy();
|
|
34
|
+
};
|
|
35
|
+
}, [enabled, workspaceId, config.backendUrl, config.apiKey, config.token]);
|
|
36
|
+
const handle = enabled && entry !== null && entry.workspaceId === workspaceId ? entry.handle : null;
|
|
37
|
+
const subscribe = useMemo(() => {
|
|
38
|
+
return (onStoreChange) => {
|
|
39
|
+
if (!handle) return () => {
|
|
40
|
+
};
|
|
41
|
+
return handle.onChange(onStoreChange);
|
|
42
|
+
};
|
|
43
|
+
}, [handle]);
|
|
44
|
+
useSyncExternalStore(
|
|
45
|
+
subscribe,
|
|
46
|
+
() => {
|
|
47
|
+
if (!handle) return EMPTY_SNAPSHOT;
|
|
48
|
+
return `${handle.status}|${handle.accessType ?? ""}|${handle.version}`;
|
|
49
|
+
},
|
|
50
|
+
() => EMPTY_SNAPSHOT
|
|
51
|
+
);
|
|
52
|
+
const [now, setNow] = useState(() => Date.now());
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
if (!enabled) return;
|
|
55
|
+
setNow(Date.now());
|
|
56
|
+
const timer = setInterval(() => {
|
|
57
|
+
setNow(Date.now());
|
|
58
|
+
}, tickMs);
|
|
59
|
+
return () => {
|
|
60
|
+
clearInterval(timer);
|
|
61
|
+
};
|
|
62
|
+
}, [enabled, tickMs]);
|
|
63
|
+
const rosterHumans = (handle == null ? void 0 : handle.humans) ?? NO_HUMANS;
|
|
64
|
+
const humans = useMemo(
|
|
65
|
+
() => rosterHumans.map((human) => ({
|
|
66
|
+
...human,
|
|
67
|
+
state: derivePresenceState({
|
|
68
|
+
lastIntentAt: human.lastIntentAt,
|
|
69
|
+
hidden: human.hidden,
|
|
70
|
+
manualAway: human.manualAway,
|
|
71
|
+
now
|
|
72
|
+
})
|
|
73
|
+
})),
|
|
74
|
+
[rosterHumans, now]
|
|
75
|
+
);
|
|
76
|
+
const refreshNow = useCallback(() => {
|
|
77
|
+
var _a;
|
|
78
|
+
return ((_a = handleRef.current) == null ? void 0 : _a.refreshNow()) ?? Promise.resolve();
|
|
79
|
+
}, []);
|
|
80
|
+
return {
|
|
81
|
+
status: handle ? handle.status : enabled ? "connecting" : "closed",
|
|
82
|
+
error: (handle == null ? void 0 : handle.error) ?? null,
|
|
83
|
+
accessType: (handle == null ? void 0 : handle.accessType) ?? null,
|
|
84
|
+
humans,
|
|
85
|
+
agents: (handle == null ? void 0 : handle.agents) ?? NO_AGENTS,
|
|
86
|
+
refreshNow
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function useWorkspacePresenceResolver(workspaceId) {
|
|
90
|
+
const config = useAthenaConfig();
|
|
91
|
+
const { backendUrl, apiKey, token } = config;
|
|
92
|
+
return useCallback(
|
|
93
|
+
(request, signal) => {
|
|
94
|
+
if (workspaceId === null) {
|
|
95
|
+
return Promise.reject(
|
|
96
|
+
new Error("[AthenaSDK] useWorkspacePresenceResolver: no workspace selected")
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return resolveWorkspacePresence({
|
|
100
|
+
auth: { backendUrl, apiKey, token },
|
|
101
|
+
workspaceId,
|
|
102
|
+
request,
|
|
103
|
+
signal
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
[workspaceId, backendUrl, apiKey, token]
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
export {
|
|
110
|
+
PRESENCE_DEFAULT_TICK_MS,
|
|
111
|
+
useWorkspacePresence,
|
|
112
|
+
useWorkspacePresenceResolver
|
|
113
|
+
};
|
|
114
|
+
//# sourceMappingURL=presence-react.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence-react.js","sources":["../../src/collab/presence-react.ts"],"sourcesContent":["/**\n * React bindings for the workspace presence feed.\n *\n * `useWorkspacePresence(workspaceId)` opens (and owns) a\n * `connectWorkspacePresence` handle, resolving auth from the surrounding\n * `AthenaProvider` (per-viewer bearer when present, API key otherwise), and\n * re-renders on status/roster changes via `useSyncExternalStore`. Each person\n * carries a `state` on the intent ladder, recomputed against a clock that\n * ticks every `tickMs` so `active` decays to `idle` and `away` between\n * awareness events.\n *\n * `useWorkspacePresenceResolver(workspaceId)` returns the batch id→title\n * resolver bound to the same auth. It is deliberately thin: callers own\n * caching (TanStack Query is the expected home for it).\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { useAthenaConfig } from '../provider/AthenaContext';\nimport {\n type WorkspacePresenceHandle,\n type WorkspacePresenceStatus,\n connectWorkspacePresence,\n} from './presence-client';\nimport {\n type WorkspacePresenceResolveRequest,\n type WorkspacePresenceResolveResponse,\n resolveWorkspacePresence,\n} from './presence-mint';\nimport {\n type PresenceAgent,\n type PresenceHuman,\n type PresenceState,\n derivePresenceState,\n} from './presence-slots';\n\n/** Default cadence for re-deriving each person's intent state. */\nexport const PRESENCE_DEFAULT_TICK_MS = 10_000;\n\nexport interface PresenceHumanWithState extends PresenceHuman {\n /** Where the person sits on the intent ladder as of the last tick. */\n state: PresenceState;\n}\n\nexport interface UseWorkspacePresenceOptions {\n /** `false` closes the feed without unmounting the caller. Default `true`. */\n enabled?: boolean;\n /** How often `state` is re-derived from `lastIntentAt`. Default 10 s. */\n tickMs?: number;\n}\n\nexport interface UseWorkspacePresenceResult {\n /** `'closed'` while disabled or without a workspace; `'connecting'` until the first mint resolves. */\n status: WorkspacePresenceStatus;\n error: Error | null;\n accessType: 'r' | 'rw' | null;\n humans: PresenceHumanWithState[];\n agents: PresenceAgent[];\n /** Force an early token refresh; resolves immediately when no feed is open. */\n refreshNow: () => Promise<void>;\n}\n\nconst EMPTY_SNAPSHOT = 'init||0';\nconst NO_HUMANS: PresenceHuman[] = [];\nconst NO_AGENTS: PresenceAgent[] = [];\n\nexport function useWorkspacePresence(\n workspaceId: string | null,\n options?: UseWorkspacePresenceOptions\n): UseWorkspacePresenceResult {\n const config = useAthenaConfig();\n const enabled = options?.enabled !== false && workspaceId !== null;\n const tickMs = options?.tickMs ?? PRESENCE_DEFAULT_TICK_MS;\n const [entry, setEntry] = useState<{\n workspaceId: string;\n handle: WorkspacePresenceHandle;\n } | null>(null);\n const handleRef = useRef<WorkspacePresenceHandle | null>(null);\n\n useEffect(() => {\n if (!enabled || workspaceId === null) {\n setEntry(null);\n return;\n }\n const next = connectWorkspacePresence({\n workspaceId,\n auth: {\n backendUrl: config.backendUrl,\n apiKey: config.apiKey,\n token: config.token,\n },\n });\n handleRef.current = next;\n setEntry({ workspaceId, handle: next });\n return () => {\n handleRef.current = null;\n next.destroy();\n };\n // Recreate when the target or credentials change; the handle re-mints on\n // its own schedule otherwise.\n }, [enabled, workspaceId, config.backendUrl, config.apiKey, config.token]);\n\n // React renders with the new arguments before the effect above runs, so a\n // handle opened for a previous workspace, or before the feed was disabled,\n // still sits in state for that one render. Expose it only while it is the\n // handle this render asked for; otherwise the closed / connecting empty\n // result wins, and a disabled feed never leaks a roster.\n const handle =\n enabled && entry !== null && entry.workspaceId === workspaceId ? entry.handle : null;\n\n const subscribe = useMemo(() => {\n return (onStoreChange: () => void) => {\n if (!handle) return () => {};\n return handle.onChange(onStoreChange);\n };\n }, [handle]);\n\n const snapshot = useSyncExternalStore(\n subscribe,\n () => {\n if (!handle) return EMPTY_SNAPSHOT;\n return `${handle.status}|${handle.accessType ?? ''}|${handle.version}`;\n },\n () => EMPTY_SNAPSHOT\n );\n void snapshot;\n\n // The ladder decays with wall-clock time, not with awareness events; a\n // person who stops typing must drift to idle even when nothing arrives.\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!enabled) return;\n setNow(Date.now());\n const timer = setInterval(() => {\n setNow(Date.now());\n }, tickMs);\n return () => {\n clearInterval(timer);\n };\n }, [enabled, tickMs]);\n\n const rosterHumans = handle?.humans ?? NO_HUMANS;\n const humans = useMemo(\n () =>\n rosterHumans.map((human) => ({\n ...human,\n state: derivePresenceState({\n lastIntentAt: human.lastIntentAt,\n hidden: human.hidden,\n manualAway: human.manualAway,\n now,\n }),\n })),\n [rosterHumans, now]\n );\n\n const refreshNow = useCallback(() => handleRef.current?.refreshNow() ?? Promise.resolve(), []);\n\n return {\n status: handle ? handle.status : enabled ? 'connecting' : 'closed',\n error: handle?.error ?? null,\n accessType: handle?.accessType ?? null,\n humans,\n agents: handle?.agents ?? NO_AGENTS,\n refreshNow,\n };\n}\n\nexport type WorkspacePresenceResolver = (\n request: WorkspacePresenceResolveRequest,\n signal?: AbortSignal\n) => Promise<WorkspacePresenceResolveResponse>;\n\n/**\n * A stable resolver bound to the provider's auth and the given workspace.\n * Rejects when called without a workspace; no caching — callers own that.\n */\nexport function useWorkspacePresenceResolver(\n workspaceId: string | null\n): WorkspacePresenceResolver {\n const config = useAthenaConfig();\n const { backendUrl, apiKey, token } = config;\n return useCallback<WorkspacePresenceResolver>(\n (request, signal) => {\n if (workspaceId === null) {\n return Promise.reject(\n new Error('[AthenaSDK] useWorkspacePresenceResolver: no workspace selected')\n );\n }\n return resolveWorkspacePresence({\n auth: { backendUrl, apiKey, token },\n workspaceId,\n request,\n signal,\n });\n },\n [workspaceId, backendUrl, apiKey, token]\n );\n}\n"],"names":[],"mappings":";;;;;AAoCO,MAAM,2BAA2B;AAyBxC,MAAM,iBAAiB;AACvB,MAAM,YAA6B,CAAA;AACnC,MAAM,YAA6B,CAAA;AAE5B,SAAS,qBACd,aACA,SAC4B;AAC5B,QAAM,SAAS,gBAAA;AACf,QAAM,WAAU,mCAAS,aAAY,SAAS,gBAAgB;AAC9D,QAAM,UAAS,mCAAS,WAAU;AAClC,QAAM,CAAC,OAAO,QAAQ,IAAI,SAGhB,IAAI;AACd,QAAM,YAAY,OAAuC,IAAI;AAE7D,YAAU,MAAM;AACd,QAAI,CAAC,WAAW,gBAAgB,MAAM;AACpC,eAAS,IAAI;AACb;AAAA,IACF;AACA,UAAM,OAAO,yBAAyB;AAAA,MACpC;AAAA,MACA,MAAM;AAAA,QACJ,YAAY,OAAO;AAAA,QACnB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,MAAA;AAAA,IAChB,CACD;AACD,cAAU,UAAU;AACpB,aAAS,EAAE,aAAa,QAAQ,KAAA,CAAM;AACtC,WAAO,MAAM;AACX,gBAAU,UAAU;AACpB,WAAK,QAAA;AAAA,IACP;AAAA,EAGF,GAAG,CAAC,SAAS,aAAa,OAAO,YAAY,OAAO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,iCAAQ,UAAS;AAAA,IACxB,aAAY,iCAAQ,eAAc;AAAA,IAClC;AAAA,IACA,SAAQ,iCAAQ,WAAU;AAAA,IAC1B;AAAA,EAAA;AAEJ;AAWO,SAAS,6BACd,aAC2B;AAC3B,QAAM,SAAS,gBAAA;AACf,QAAM,EAAE,YAAY,QAAQ,MAAA,IAAU;AACtC,SAAO;AAAA,IACL,CAAC,SAAS,WAAW;AACnB,UAAI,gBAAgB,MAAM;AACxB,eAAO,QAAQ;AAAA,UACb,IAAI,MAAM,iEAAiE;AAAA,QAAA;AAAA,MAE/E;AACA,aAAO,yBAAyB;AAAA,QAC9B,MAAM,EAAE,YAAY,QAAQ,MAAA;AAAA,QAC5B;AAAA,QACA;AAAA,QACA;AAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,CAAC,aAAa,YAAY,QAAQ,KAAK;AAAA,EAAA;AAE3C;"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const PRESENCE_CONTEXT_TYPE = {
|
|
4
|
+
ASSET: "asset",
|
|
5
|
+
SESSION: "session",
|
|
6
|
+
/** Server-written only: "somewhere in that project", never which document. */
|
|
7
|
+
PROJECT: "project"
|
|
8
|
+
};
|
|
9
|
+
const MAX_PRESENCE_CONTEXTS_PER_SLOT = 64;
|
|
10
|
+
const MAX_PRESENCE_STRING_CHARS = 512;
|
|
11
|
+
const PRESENCE_ACTIVE_WINDOW_MS = 6e4;
|
|
12
|
+
const PRESENCE_IDLE_WINDOW_MS = 3e5;
|
|
13
|
+
function isRecord(value) {
|
|
14
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
15
|
+
}
|
|
16
|
+
function cleanString(value) {
|
|
17
|
+
if (typeof value !== "string") return null;
|
|
18
|
+
const trimmed = value.trim();
|
|
19
|
+
if (!trimmed) return null;
|
|
20
|
+
return trimmed.slice(0, MAX_PRESENCE_STRING_CHARS);
|
|
21
|
+
}
|
|
22
|
+
function cleanEpochMs(value) {
|
|
23
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
function cleanContextType(value) {
|
|
27
|
+
if (value === PRESENCE_CONTEXT_TYPE.ASSET || value === PRESENCE_CONTEXT_TYPE.SESSION || value === PRESENCE_CONTEXT_TYPE.PROJECT) {
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
function cleanStringList(value) {
|
|
33
|
+
if (!Array.isArray(value)) return [];
|
|
34
|
+
const out = [];
|
|
35
|
+
for (const item of value) {
|
|
36
|
+
const cleaned = cleanString(item);
|
|
37
|
+
if (cleaned === null || out.includes(cleaned)) continue;
|
|
38
|
+
out.push(cleaned);
|
|
39
|
+
if (out.length >= MAX_PRESENCE_CONTEXTS_PER_SLOT) break;
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
function parseContext(raw) {
|
|
44
|
+
if (!isRecord(raw)) return null;
|
|
45
|
+
const type = cleanContextType(raw.type);
|
|
46
|
+
const guid = cleanString(raw.guid);
|
|
47
|
+
if (type === null || guid === null) return null;
|
|
48
|
+
return {
|
|
49
|
+
type,
|
|
50
|
+
guid,
|
|
51
|
+
locationLabel: cleanString(raw.locationLabel),
|
|
52
|
+
projects: cleanStringList(raw.projects),
|
|
53
|
+
coarse: raw.coarse === true,
|
|
54
|
+
lastAnchorChangeAt: cleanEpochMs(raw.lastAnchorChangeAt)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function parseContexts(raw) {
|
|
58
|
+
if (!Array.isArray(raw)) return [];
|
|
59
|
+
const seen = /* @__PURE__ */ new Set();
|
|
60
|
+
const contexts = [];
|
|
61
|
+
for (const item of raw) {
|
|
62
|
+
const parsed = parseContext(item);
|
|
63
|
+
if (parsed === null) continue;
|
|
64
|
+
const key = `${parsed.type}:${parsed.guid}`;
|
|
65
|
+
if (seen.has(key)) continue;
|
|
66
|
+
seen.add(key);
|
|
67
|
+
contexts.push(parsed);
|
|
68
|
+
if (contexts.length >= MAX_PRESENCE_CONTEXTS_PER_SLOT) break;
|
|
69
|
+
}
|
|
70
|
+
return contexts;
|
|
71
|
+
}
|
|
72
|
+
function parseAgentInitiator(raw) {
|
|
73
|
+
if (!isRecord(raw)) return null;
|
|
74
|
+
const initiator = {
|
|
75
|
+
userId: cleanString(raw.userId),
|
|
76
|
+
email: cleanString(raw.email),
|
|
77
|
+
name: cleanString(raw.name)
|
|
78
|
+
};
|
|
79
|
+
if (initiator.userId === null && initiator.email === null && initiator.name === null) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
return initiator;
|
|
83
|
+
}
|
|
84
|
+
function parseSlot(raw) {
|
|
85
|
+
if (!isRecord(raw)) return null;
|
|
86
|
+
const user = raw.user;
|
|
87
|
+
if (!isRecord(user)) return null;
|
|
88
|
+
const email = cleanString(user.email);
|
|
89
|
+
const userId = cleanString(user.userId) ?? email;
|
|
90
|
+
if (userId === null) return null;
|
|
91
|
+
return {
|
|
92
|
+
kind: user.kind === "agent" ? "agent" : "human",
|
|
93
|
+
userId,
|
|
94
|
+
authUserId: cleanString(user.authUserId),
|
|
95
|
+
name: cleanString(user.name) ?? userId,
|
|
96
|
+
email,
|
|
97
|
+
color: cleanString(user.color),
|
|
98
|
+
avatarUrl: cleanString(user.avatarUrl),
|
|
99
|
+
agentInitiator: parseAgentInitiator(user.agentInitiator),
|
|
100
|
+
contexts: parseContexts(raw.activeContexts),
|
|
101
|
+
hidden: raw.hidden === true,
|
|
102
|
+
lastIntentAt: cleanEpochMs(raw.lastIntentAt),
|
|
103
|
+
manualAway: raw.status === "away"
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function mergeContexts(existing, incoming) {
|
|
107
|
+
const index = /* @__PURE__ */ new Map();
|
|
108
|
+
existing.forEach((context, position) => {
|
|
109
|
+
index.set(`${context.type}:${context.guid}`, position);
|
|
110
|
+
});
|
|
111
|
+
for (const context of incoming) {
|
|
112
|
+
const key = `${context.type}:${context.guid}`;
|
|
113
|
+
const position = index.get(key);
|
|
114
|
+
if (position === void 0) {
|
|
115
|
+
existing.push(context);
|
|
116
|
+
index.set(key, existing.length - 1);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const prior = existing[position];
|
|
120
|
+
if (prior && (context.lastAnchorChangeAt ?? 0) > (prior.lastAnchorChangeAt ?? 0)) {
|
|
121
|
+
existing[position] = context;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function maxIntent(a, b) {
|
|
126
|
+
if (a === null) return b;
|
|
127
|
+
if (b === null) return a;
|
|
128
|
+
return Math.max(a, b);
|
|
129
|
+
}
|
|
130
|
+
function toPresenceContext(context) {
|
|
131
|
+
return {
|
|
132
|
+
type: context.type,
|
|
133
|
+
guid: context.guid,
|
|
134
|
+
locationLabel: context.locationLabel,
|
|
135
|
+
projects: context.projects,
|
|
136
|
+
coarse: context.coarse
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function byName(a, b) {
|
|
140
|
+
const names = a.name.localeCompare(b.name);
|
|
141
|
+
return names !== 0 ? names : a.key.localeCompare(b.key);
|
|
142
|
+
}
|
|
143
|
+
function mergePresenceStates(states) {
|
|
144
|
+
const humans = /* @__PURE__ */ new Map();
|
|
145
|
+
const agents = /* @__PURE__ */ new Map();
|
|
146
|
+
for (const raw of states.values()) {
|
|
147
|
+
const slot = parseSlot(raw);
|
|
148
|
+
if (slot === null) continue;
|
|
149
|
+
if (slot.kind === "agent") {
|
|
150
|
+
const existing2 = agents.get(slot.userId);
|
|
151
|
+
if (existing2) {
|
|
152
|
+
existing2.lastIntentAt = maxIntent(existing2.lastIntentAt, slot.lastIntentAt);
|
|
153
|
+
existing2.agentInitiator = existing2.agentInitiator ?? slot.agentInitiator;
|
|
154
|
+
mergeContexts(existing2.contexts, slot.contexts);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
agents.set(slot.userId, {
|
|
158
|
+
key: slot.userId,
|
|
159
|
+
userId: slot.userId,
|
|
160
|
+
name: slot.name,
|
|
161
|
+
agentInitiator: slot.agentInitiator,
|
|
162
|
+
contexts: [...slot.contexts],
|
|
163
|
+
lastIntentAt: slot.lastIntentAt
|
|
164
|
+
});
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const key = slot.authUserId ?? slot.userId;
|
|
168
|
+
const existing = humans.get(key);
|
|
169
|
+
if (existing) {
|
|
170
|
+
existing.connections += 1;
|
|
171
|
+
existing.lastIntentAt = maxIntent(existing.lastIntentAt, slot.lastIntentAt);
|
|
172
|
+
existing.hidden = existing.hidden && slot.hidden;
|
|
173
|
+
existing.manualAway = existing.manualAway || slot.manualAway;
|
|
174
|
+
existing.email = existing.email ?? slot.email;
|
|
175
|
+
existing.avatarUrl = existing.avatarUrl ?? slot.avatarUrl;
|
|
176
|
+
existing.color = existing.color ?? slot.color;
|
|
177
|
+
mergeContexts(existing.contexts, slot.contexts);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
humans.set(key, {
|
|
181
|
+
key,
|
|
182
|
+
authUserId: slot.authUserId,
|
|
183
|
+
userId: slot.userId,
|
|
184
|
+
name: slot.name,
|
|
185
|
+
email: slot.email,
|
|
186
|
+
avatarUrl: slot.avatarUrl,
|
|
187
|
+
color: slot.color,
|
|
188
|
+
contexts: [...slot.contexts],
|
|
189
|
+
lastIntentAt: slot.lastIntentAt,
|
|
190
|
+
hidden: slot.hidden,
|
|
191
|
+
manualAway: slot.manualAway,
|
|
192
|
+
connections: 1
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
humans: [...humans.values()].map((human) => ({ ...human, contexts: human.contexts.map(toPresenceContext) })).sort(byName),
|
|
197
|
+
agents: [...agents.values()].map((agent) => ({ ...agent, contexts: agent.contexts.map(toPresenceContext) })).sort(byName)
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function derivePresenceState({
|
|
201
|
+
lastIntentAt,
|
|
202
|
+
hidden,
|
|
203
|
+
manualAway,
|
|
204
|
+
now
|
|
205
|
+
}) {
|
|
206
|
+
if (manualAway) return "away";
|
|
207
|
+
if (lastIntentAt === null) return "idle";
|
|
208
|
+
const elapsed = Math.max(0, now - lastIntentAt);
|
|
209
|
+
if (elapsed <= PRESENCE_ACTIVE_WINDOW_MS) return hidden ? "idle" : "active";
|
|
210
|
+
if (elapsed <= PRESENCE_IDLE_WINDOW_MS) return "idle";
|
|
211
|
+
return "away";
|
|
212
|
+
}
|
|
213
|
+
exports.MAX_PRESENCE_CONTEXTS_PER_SLOT = MAX_PRESENCE_CONTEXTS_PER_SLOT;
|
|
214
|
+
exports.MAX_PRESENCE_STRING_CHARS = MAX_PRESENCE_STRING_CHARS;
|
|
215
|
+
exports.PRESENCE_ACTIVE_WINDOW_MS = PRESENCE_ACTIVE_WINDOW_MS;
|
|
216
|
+
exports.PRESENCE_CONTEXT_TYPE = PRESENCE_CONTEXT_TYPE;
|
|
217
|
+
exports.PRESENCE_IDLE_WINDOW_MS = PRESENCE_IDLE_WINDOW_MS;
|
|
218
|
+
exports.derivePresenceState = derivePresenceState;
|
|
219
|
+
exports.mergePresenceStates = mergePresenceStates;
|
|
220
|
+
//# sourceMappingURL=presence-slots.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence-slots.cjs","sources":["../../src/collab/presence-slots.ts"],"sourcesContent":["/**\n * Pure decoding of workspace awareness slots into typed presence entries.\n *\n * Every connected Olympus tab (and every agent run, published by the backend)\n * holds one slot in the workspace awareness room. Keryx narrows what each\n * recipient receives (a document the viewer may not open collapses into a\n * coarse `project` context, agents with nothing visible are dropped), so the\n * slots seen here are already scoped to the token holder. This module treats\n * every field as untrusted anyway: a slot is JSON a browser published, and a\n * malformed one must be dropped rather than crash the feed or merge every\n * anonymous tab into one phantom person.\n *\n * The shape mirrors Olympus's `WorkspaceAwarenessSlot`\n * (`olympus/src/store/workspaceAwarenessStore.ts`) and the bounds mirror\n * Agora's observer (`agora/agora/services/presence/awareness_slots.py`).\n * No React, no network — the merge and the intent ladder are testable directly.\n */\n\nexport const PRESENCE_CONTEXT_TYPE = {\n ASSET: 'asset',\n SESSION: 'session',\n /** Server-written only: \"somewhere in that project\", never which document. */\n PROJECT: 'project',\n} as const;\n\nexport type PresenceContextType =\n (typeof PRESENCE_CONTEXT_TYPE)[keyof typeof PRESENCE_CONTEXT_TYPE];\n\n/** Contexts kept per slot; anything past this is publisher junk. */\nexport const MAX_PRESENCE_CONTEXTS_PER_SLOT = 64;\n/** Characters kept per string field. */\nexport const MAX_PRESENCE_STRING_CHARS = 512;\n\n/**\n * Intent ladder thresholds, mirroring `agora/agora/services/presence/types.py`\n * and `olympus/src/sections/presence-monitor/presence-state.ts`. Readers\n * recompute the state from `lastIntentAt` on every tick so it decays smoothly\n * instead of stepping when a snapshot lands.\n */\nexport const PRESENCE_ACTIVE_WINDOW_MS = 60_000;\nexport const PRESENCE_IDLE_WINDOW_MS = 300_000;\n\nexport type PresenceState = 'active' | 'idle' | 'away';\n\nexport interface PresenceContext {\n type: PresenceContextType;\n /** Asset id, session thread id, or project asset id depending on `type`. */\n guid: string;\n /** Human-readable location inside the asset (\"Slide 4\", \"Sheet1!B14\"), when the tab reported one. */\n locationLabel: string | null;\n /** Server-written: projects containing this document that the viewer may also open. */\n projects: string[];\n /** Server-written on `project` contexts: the viewer may not open the underlying document. */\n coarse: boolean;\n}\n\nexport interface PresenceHuman {\n /** Identity the person's tabs merge by: the server-attested id when present, else the self-reported one. */\n key: string;\n /** Agora user id stamped by Keryx from the publishing socket's token; null on unstamped slots. */\n authUserId: string | null;\n /** Self-reported user identifier (the email, for Olympus tabs). */\n userId: string;\n name: string;\n email: string | null;\n avatarUrl: string | null;\n color: string | null;\n /** Union of open contexts across the person's tabs, deduped by type + guid. */\n contexts: PresenceContext[];\n /** Most recent self-reported input across the person's tabs (epoch ms, publisher clock); null when none reported. */\n lastIntentAt: number | null;\n /** True only when every one of the person's tabs reports itself backgrounded. */\n hidden: boolean;\n /** True when any tab carries the manual \"away\" status set in Settings. */\n manualAway: boolean;\n /** Number of awareness slots (tabs) merged into this entry. */\n connections: number;\n}\n\nexport interface PresenceAgent {\n /** The agent slot's own id (`agent:<run>`); runs never collapse by publisher. */\n key: string;\n userId: string;\n name: string;\n /** The person the run works for; what a reader shows as \"Athena for …\". */\n agentInitiator: { userId: string | null; email: string | null; name: string | null } | null;\n contexts: PresenceContext[];\n lastIntentAt: number | null;\n}\n\nexport interface PresenceRoster {\n humans: PresenceHuman[];\n agents: PresenceAgent[];\n}\n\ninterface ParsedContext extends PresenceContext {\n /** Publisher-reported ms of the last anchor change; breaks ties when tabs share a context. */\n lastAnchorChangeAt: number | null;\n}\n\ninterface ParsedSlot {\n kind: 'human' | 'agent';\n userId: string;\n authUserId: string | null;\n name: string;\n email: string | null;\n color: string | null;\n avatarUrl: string | null;\n agentInitiator: PresenceAgent['agentInitiator'];\n contexts: ParsedContext[];\n hidden: boolean;\n lastIntentAt: number | null;\n manualAway: boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Accept a non-empty string, trimmed and truncated. Anything else becomes null. */\nfunction cleanString(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n return trimmed.slice(0, MAX_PRESENCE_STRING_CHARS);\n}\n\n/** Accept a plausible epoch-milliseconds number, else null. */\nfunction cleanEpochMs(value: unknown): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null;\n return value;\n}\n\nfunction cleanContextType(value: unknown): PresenceContextType | null {\n if (\n value === PRESENCE_CONTEXT_TYPE.ASSET ||\n value === PRESENCE_CONTEXT_TYPE.SESSION ||\n value === PRESENCE_CONTEXT_TYPE.PROJECT\n ) {\n return value;\n }\n return null;\n}\n\nfunction cleanStringList(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const out: string[] = [];\n for (const item of value) {\n const cleaned = cleanString(item);\n if (cleaned === null || out.includes(cleaned)) continue;\n out.push(cleaned);\n if (out.length >= MAX_PRESENCE_CONTEXTS_PER_SLOT) break;\n }\n return out;\n}\n\nfunction parseContext(raw: unknown): ParsedContext | null {\n if (!isRecord(raw)) return null;\n const type = cleanContextType(raw.type);\n const guid = cleanString(raw.guid);\n if (type === null || guid === null) return null;\n return {\n type,\n guid,\n locationLabel: cleanString(raw.locationLabel),\n projects: cleanStringList(raw.projects),\n coarse: raw.coarse === true,\n lastAnchorChangeAt: cleanEpochMs(raw.lastAnchorChangeAt),\n };\n}\n\nfunction parseContexts(raw: unknown): ParsedContext[] {\n if (!Array.isArray(raw)) return [];\n const seen = new Set<string>();\n const contexts: ParsedContext[] = [];\n for (const item of raw) {\n const parsed = parseContext(item);\n if (parsed === null) continue;\n const key = `${parsed.type}:${parsed.guid}`;\n if (seen.has(key)) continue;\n seen.add(key);\n contexts.push(parsed);\n if (contexts.length >= MAX_PRESENCE_CONTEXTS_PER_SLOT) break;\n }\n return contexts;\n}\n\nfunction parseAgentInitiator(raw: unknown): PresenceAgent['agentInitiator'] {\n if (!isRecord(raw)) return null;\n const initiator = {\n userId: cleanString(raw.userId),\n email: cleanString(raw.email),\n name: cleanString(raw.name),\n };\n if (initiator.userId === null && initiator.email === null && initiator.name === null) {\n return null;\n }\n return initiator;\n}\n\n/**\n * Validate one slot. Returns null for anything that cannot be attributed to a\n * stable identity: a slot with neither `userId` nor `email` would otherwise\n * merge every anonymous tab in the workspace into one phantom participant.\n * A missing or unrecognised `kind` reads as human — an older client is far\n * likelier than an agent, and mislabelling a person would hide them.\n */\nfunction parseSlot(raw: unknown): ParsedSlot | null {\n if (!isRecord(raw)) return null;\n const user = raw.user;\n if (!isRecord(user)) return null;\n const email = cleanString(user.email);\n const userId = cleanString(user.userId) ?? email;\n if (userId === null) return null;\n return {\n kind: user.kind === 'agent' ? 'agent' : 'human',\n userId,\n authUserId: cleanString(user.authUserId),\n name: cleanString(user.name) ?? userId,\n email,\n color: cleanString(user.color),\n avatarUrl: cleanString(user.avatarUrl),\n agentInitiator: parseAgentInitiator(user.agentInitiator),\n contexts: parseContexts(raw.activeContexts),\n hidden: raw.hidden === true,\n lastIntentAt: cleanEpochMs(raw.lastIntentAt),\n manualAway: raw.status === 'away',\n };\n}\n\n/**\n * Fold one slot's contexts into an already-seen participant's list, keeping\n * the entry with the most recent anchor activity for a duplicate (type, guid).\n */\nfunction mergeContexts(existing: ParsedContext[], incoming: readonly ParsedContext[]): void {\n const index = new Map<string, number>();\n existing.forEach((context, position) => {\n index.set(`${context.type}:${context.guid}`, position);\n });\n for (const context of incoming) {\n const key = `${context.type}:${context.guid}`;\n const position = index.get(key);\n if (position === undefined) {\n existing.push(context);\n index.set(key, existing.length - 1);\n continue;\n }\n const prior = existing[position];\n if (prior && (context.lastAnchorChangeAt ?? 0) > (prior.lastAnchorChangeAt ?? 0)) {\n existing[position] = context;\n }\n }\n}\n\nfunction maxIntent(a: number | null, b: number | null): number | null {\n if (a === null) return b;\n if (b === null) return a;\n return Math.max(a, b);\n}\n\nfunction toPresenceContext(context: ParsedContext): PresenceContext {\n return {\n type: context.type,\n guid: context.guid,\n locationLabel: context.locationLabel,\n projects: context.projects,\n coarse: context.coarse,\n };\n}\n\ninterface HumanAccumulator extends Omit<PresenceHuman, 'contexts'> {\n contexts: ParsedContext[];\n}\n\ninterface AgentAccumulator extends Omit<PresenceAgent, 'contexts'> {\n contexts: ParsedContext[];\n}\n\nfunction byName<T extends { name: string; key: string }>(a: T, b: T): number {\n const names = a.name.localeCompare(b.name);\n return names !== 0 ? names : a.key.localeCompare(b.key);\n}\n\n/**\n * Merge the awareness room's slots into one entry per person and one per\n * agent run.\n *\n * Humans merge by the server-attested `authUserId` when Keryx stamped one\n * (a tab that merely *claims* a colleague's `userId` gets its own row, with its\n * real identity on it) and by the self-reported `userId` only for unstamped\n * slots — the same rule as Agora's observer and Olympus's store. A person is\n * as active as their most active tab, backgrounded only when every tab is,\n * and away whenever any tab carries the manual flag. Agents keep their own\n * slot id: every run is published by the same service identity, so merging\n * by publisher would collapse concurrent runs into one.\n */\nexport function mergePresenceStates(states: ReadonlyMap<number, unknown>): PresenceRoster {\n const humans = new Map<string, HumanAccumulator>();\n const agents = new Map<string, AgentAccumulator>();\n\n for (const raw of states.values()) {\n const slot = parseSlot(raw);\n if (slot === null) continue;\n\n if (slot.kind === 'agent') {\n const existing = agents.get(slot.userId);\n if (existing) {\n existing.lastIntentAt = maxIntent(existing.lastIntentAt, slot.lastIntentAt);\n existing.agentInitiator = existing.agentInitiator ?? slot.agentInitiator;\n mergeContexts(existing.contexts, slot.contexts);\n continue;\n }\n agents.set(slot.userId, {\n key: slot.userId,\n userId: slot.userId,\n name: slot.name,\n agentInitiator: slot.agentInitiator,\n contexts: [...slot.contexts],\n lastIntentAt: slot.lastIntentAt,\n });\n continue;\n }\n\n const key = slot.authUserId ?? slot.userId;\n const existing = humans.get(key);\n if (existing) {\n existing.connections += 1;\n existing.lastIntentAt = maxIntent(existing.lastIntentAt, slot.lastIntentAt);\n existing.hidden = existing.hidden && slot.hidden;\n existing.manualAway = existing.manualAway || slot.manualAway;\n // A person with tabs in two surfaces publishes identity from both;\n // prefer whichever slot actually carried the optional fields.\n existing.email = existing.email ?? slot.email;\n existing.avatarUrl = existing.avatarUrl ?? slot.avatarUrl;\n existing.color = existing.color ?? slot.color;\n mergeContexts(existing.contexts, slot.contexts);\n continue;\n }\n humans.set(key, {\n key,\n authUserId: slot.authUserId,\n userId: slot.userId,\n name: slot.name,\n email: slot.email,\n avatarUrl: slot.avatarUrl,\n color: slot.color,\n contexts: [...slot.contexts],\n lastIntentAt: slot.lastIntentAt,\n hidden: slot.hidden,\n manualAway: slot.manualAway,\n connections: 1,\n });\n }\n\n return {\n humans: [...humans.values()]\n .map((human) => ({ ...human, contexts: human.contexts.map(toPresenceContext) }))\n .sort(byName),\n agents: [...agents.values()]\n .map((agent) => ({ ...agent, contexts: agent.contexts.map(toPresenceContext) }))\n .sort(byName),\n };\n}\n\n/**\n * Where a person sits on the intent ladder right now.\n *\n * The manual \"away\" status overrides the ladder. A person who never reported\n * an input is `idle` rather than `away` — absence of evidence is not evidence\n * of leaving. Every tab backgrounded (`hidden`) caps the result below\n * `active`: whatever they did a moment ago, they are demonstrably not looking\n * at Athena now; it does not force `away`, because alt-tabbing to check\n * something is not leaving. A `lastIntentAt` ahead of `now` (a publisher whose\n * clock runs fast) counts as \"just acted\" rather than a negative elapsed.\n */\nexport function derivePresenceState({\n lastIntentAt,\n hidden,\n manualAway,\n now,\n}: {\n lastIntentAt: number | null;\n hidden: boolean;\n manualAway: boolean;\n now: number;\n}): PresenceState {\n if (manualAway) return 'away';\n if (lastIntentAt === null) return 'idle';\n const elapsed = Math.max(0, now - lastIntentAt);\n if (elapsed <= PRESENCE_ACTIVE_WINDOW_MS) return hidden ? 'idle' : 'active';\n if (elapsed <= PRESENCE_IDLE_WINDOW_MS) return 'idle';\n return 'away';\n}\n"],"names":["existing"],"mappings":";;AAkBO,MAAM,wBAAwB;AAAA,EACnC,OAAO;AAAA,EACP,SAAS;AAAA;AAAA,EAET,SAAS;AACX;AAMO,MAAM,iCAAiC;AAEvC,MAAM,4BAA4B;AAQlC,MAAM,4BAA4B;AAClC,MAAM,0BAA0B;AA2EvC,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGA,SAAS,YAAY,OAA+B;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAA;AACtB,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,MAAM,GAAG,yBAAyB;AACnD;AAGA,SAAS,aAAa,OAA+B;AACnD,MAAI,OAAO,UAAU,YAAY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AO,UAAU,MAAM,SAAS,IAAI,iBAAiB,IAAI,EAC9E,KAAK,MAAM;AAAA,EAAA;AAElB;AAaO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKkB;AAChB,MAAI,WAAY,QAAO;AACvB,MAAI,iBAAiB,KAAM,QAAO;AAClC,QAAM,UAAU,KAAK,IAAI,GAAG,MAAM,YAAY;AAC9C,MAAI,WAAW,0BAA2B,QAAO,SAAS,SAAS;AACnE,MAAI,WAAW,wBAAyB,QAAO;AAC/C,SAAO;AACT;;;;;;;;"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure decoding of workspace awareness slots into typed presence entries.
|
|
3
|
+
*
|
|
4
|
+
* Every connected Olympus tab (and every agent run, published by the backend)
|
|
5
|
+
* holds one slot in the workspace awareness room. Keryx narrows what each
|
|
6
|
+
* recipient receives (a document the viewer may not open collapses into a
|
|
7
|
+
* coarse `project` context, agents with nothing visible are dropped), so the
|
|
8
|
+
* slots seen here are already scoped to the token holder. This module treats
|
|
9
|
+
* every field as untrusted anyway: a slot is JSON a browser published, and a
|
|
10
|
+
* malformed one must be dropped rather than crash the feed or merge every
|
|
11
|
+
* anonymous tab into one phantom person.
|
|
12
|
+
*
|
|
13
|
+
* The shape mirrors Olympus's `WorkspaceAwarenessSlot`
|
|
14
|
+
* (`olympus/src/store/workspaceAwarenessStore.ts`) and the bounds mirror
|
|
15
|
+
* Agora's observer (`agora/agora/services/presence/awareness_slots.py`).
|
|
16
|
+
* No React, no network — the merge and the intent ladder are testable directly.
|
|
17
|
+
*/
|
|
18
|
+
export declare const PRESENCE_CONTEXT_TYPE: {
|
|
19
|
+
readonly ASSET: 'asset';
|
|
20
|
+
readonly SESSION: 'session';
|
|
21
|
+
/** Server-written only: "somewhere in that project", never which document. */
|
|
22
|
+
readonly PROJECT: 'project';
|
|
23
|
+
};
|
|
24
|
+
export type PresenceContextType = (typeof PRESENCE_CONTEXT_TYPE)[keyof typeof PRESENCE_CONTEXT_TYPE];
|
|
25
|
+
/** Contexts kept per slot; anything past this is publisher junk. */
|
|
26
|
+
export declare const MAX_PRESENCE_CONTEXTS_PER_SLOT = 64;
|
|
27
|
+
/** Characters kept per string field. */
|
|
28
|
+
export declare const MAX_PRESENCE_STRING_CHARS = 512;
|
|
29
|
+
/**
|
|
30
|
+
* Intent ladder thresholds, mirroring `agora/agora/services/presence/types.py`
|
|
31
|
+
* and `olympus/src/sections/presence-monitor/presence-state.ts`. Readers
|
|
32
|
+
* recompute the state from `lastIntentAt` on every tick so it decays smoothly
|
|
33
|
+
* instead of stepping when a snapshot lands.
|
|
34
|
+
*/
|
|
35
|
+
export declare const PRESENCE_ACTIVE_WINDOW_MS = 60000;
|
|
36
|
+
export declare const PRESENCE_IDLE_WINDOW_MS = 300000;
|
|
37
|
+
export type PresenceState = 'active' | 'idle' | 'away';
|
|
38
|
+
export interface PresenceContext {
|
|
39
|
+
type: PresenceContextType;
|
|
40
|
+
/** Asset id, session thread id, or project asset id depending on `type`. */
|
|
41
|
+
guid: string;
|
|
42
|
+
/** Human-readable location inside the asset ("Slide 4", "Sheet1!B14"), when the tab reported one. */
|
|
43
|
+
locationLabel: string | null;
|
|
44
|
+
/** Server-written: projects containing this document that the viewer may also open. */
|
|
45
|
+
projects: string[];
|
|
46
|
+
/** Server-written on `project` contexts: the viewer may not open the underlying document. */
|
|
47
|
+
coarse: boolean;
|
|
48
|
+
}
|
|
49
|
+
export interface PresenceHuman {
|
|
50
|
+
/** Identity the person's tabs merge by: the server-attested id when present, else the self-reported one. */
|
|
51
|
+
key: string;
|
|
52
|
+
/** Agora user id stamped by Keryx from the publishing socket's token; null on unstamped slots. */
|
|
53
|
+
authUserId: string | null;
|
|
54
|
+
/** Self-reported user identifier (the email, for Olympus tabs). */
|
|
55
|
+
userId: string;
|
|
56
|
+
name: string;
|
|
57
|
+
email: string | null;
|
|
58
|
+
avatarUrl: string | null;
|
|
59
|
+
color: string | null;
|
|
60
|
+
/** Union of open contexts across the person's tabs, deduped by type + guid. */
|
|
61
|
+
contexts: PresenceContext[];
|
|
62
|
+
/** Most recent self-reported input across the person's tabs (epoch ms, publisher clock); null when none reported. */
|
|
63
|
+
lastIntentAt: number | null;
|
|
64
|
+
/** True only when every one of the person's tabs reports itself backgrounded. */
|
|
65
|
+
hidden: boolean;
|
|
66
|
+
/** True when any tab carries the manual "away" status set in Settings. */
|
|
67
|
+
manualAway: boolean;
|
|
68
|
+
/** Number of awareness slots (tabs) merged into this entry. */
|
|
69
|
+
connections: number;
|
|
70
|
+
}
|
|
71
|
+
export interface PresenceAgent {
|
|
72
|
+
/** The agent slot's own id (`agent:<run>`); runs never collapse by publisher. */
|
|
73
|
+
key: string;
|
|
74
|
+
userId: string;
|
|
75
|
+
name: string;
|
|
76
|
+
/** The person the run works for; what a reader shows as "Athena for …". */
|
|
77
|
+
agentInitiator: {
|
|
78
|
+
userId: string | null;
|
|
79
|
+
email: string | null;
|
|
80
|
+
name: string | null;
|
|
81
|
+
} | null;
|
|
82
|
+
contexts: PresenceContext[];
|
|
83
|
+
lastIntentAt: number | null;
|
|
84
|
+
}
|
|
85
|
+
export interface PresenceRoster {
|
|
86
|
+
humans: PresenceHuman[];
|
|
87
|
+
agents: PresenceAgent[];
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Merge the awareness room's slots into one entry per person and one per
|
|
91
|
+
* agent run.
|
|
92
|
+
*
|
|
93
|
+
* Humans merge by the server-attested `authUserId` when Keryx stamped one
|
|
94
|
+
* (a tab that merely *claims* a colleague's `userId` gets its own row, with its
|
|
95
|
+
* real identity on it) and by the self-reported `userId` only for unstamped
|
|
96
|
+
* slots — the same rule as Agora's observer and Olympus's store. A person is
|
|
97
|
+
* as active as their most active tab, backgrounded only when every tab is,
|
|
98
|
+
* and away whenever any tab carries the manual flag. Agents keep their own
|
|
99
|
+
* slot id: every run is published by the same service identity, so merging
|
|
100
|
+
* by publisher would collapse concurrent runs into one.
|
|
101
|
+
*/
|
|
102
|
+
export declare function mergePresenceStates(states: ReadonlyMap<number, unknown>): PresenceRoster;
|
|
103
|
+
/**
|
|
104
|
+
* Where a person sits on the intent ladder right now.
|
|
105
|
+
*
|
|
106
|
+
* The manual "away" status overrides the ladder. A person who never reported
|
|
107
|
+
* an input is `idle` rather than `away` — absence of evidence is not evidence
|
|
108
|
+
* of leaving. Every tab backgrounded (`hidden`) caps the result below
|
|
109
|
+
* `active`: whatever they did a moment ago, they are demonstrably not looking
|
|
110
|
+
* at Athena now; it does not force `away`, because alt-tabbing to check
|
|
111
|
+
* something is not leaving. A `lastIntentAt` ahead of `now` (a publisher whose
|
|
112
|
+
* clock runs fast) counts as "just acted" rather than a negative elapsed.
|
|
113
|
+
*/
|
|
114
|
+
export declare function derivePresenceState({ lastIntentAt, hidden, manualAway, now, }: {
|
|
115
|
+
lastIntentAt: number | null;
|
|
116
|
+
hidden: boolean;
|
|
117
|
+
manualAway: boolean;
|
|
118
|
+
now: number;
|
|
119
|
+
}): PresenceState;
|