File size: 23,421 Bytes
bf8519f d598032 bf8519f 9a6cb9a bf8519f cfa8541 bf8519f cfa8541 bf8519f 9a6cb9a bf8519f cfa8541 7fc8605 cfa8541 bf8519f a83fcff bdac669 cfa8541 bdac669 cfa8541 bdac669 cfa8541 c920df3 cfa8541 81a8217 cfa8541 bdac669 9a6cb9a bdac669 d598032 9a6cb9a d598032 9a6cb9a d598032 9a6cb9a d598032 9a6cb9a d598032 9a6cb9a d598032 9a6cb9a d598032 9a6cb9a d598032 1ad1eea 9a6cb9a a93637f d598032 a93637f bdac669 81a8217 bdac669 d598032 4e84128 d598032 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | // ---------------------------------------------------------------------------
// home/homeModel.ts β WAVE 23 item 9 (ruling R7, contract C10): the Home
// landing's PURE half. React-free and fetch-free, so `verify_home.py` can run it
// under node the way `verify_alerts.py` runs the inbox model.
//
// Everything here is a function of values that were passed in β including the
// clock. `todayStart` and `now` are PARAMETERS, never `Date.now()` calls, for two
// reasons that pull the same way:
//
// Β· a gate can then assert the boundary cases (23:59 vs 00:01, exactly seven
// days) instead of asserting whatever today happens to be;
// Β· [[date-window-vocabulary]]'s standing rule β `today` is a parameter β was
// written for the server's window vocabulary and holds just as well here.
//
// β THE ONE CLOCK THIS FEATURE MAY READ IS THE READER'S OWN, and that is not a
// contradiction of `alertsModel.stampText`'s "never touch a clock". Two different
// statements: a notification re-states WHEN A SERVER EVENT HAPPENED (re-deriving
// it in the browser is how a tenant a day ahead gets told an event happened
// tomorrow), while "Opened 30 minutes ago" states HOW LONG AGO THE READER
// THEMSELVES DID SOMETHING, and the Today bucket means the reader's today. The
// component reads the clock once and hands the numbers in here.
// ---------------------------------------------------------------------------
import type { DatabaseEntry, Recent } from "../shell/nav";
import type { FolderIcon } from "../customer-grid/types";
import { CUSTOM_ORIGIN_KEY, dataOriginLabel, groupDataDatabases } from "../customer-grid/dataPath";
/** One rendered recents tile: the RESOLVED database, never the raw stamp. */
export interface RecentTile {
key: string;
label: string;
icon?: FolderIcon;
source?: string;
sourceGroup?: string;
managedBy?: "loopable";
/** Epoch seconds, as stored. Kept so a tile can be re-sorted without re-fetching. */
at: number;
/** "Opened 30 minutes ago" β already assembled, so the component holds no clock logic. */
ago: string;
/** The chip's two letters. */
initials: string;
/**
* The entry's OWN href, carried through rather than rebuilt as `#/${key}`.
*
* β A TILE THAT REBUILDS ITS OWN LINK IS A SECOND ROUTER. `shapeNav` already decided what a
* key resolves to β `#/key` for a native surface, the current application's deep link for a
* hand-off β and a `#/${key}` assembled here would send a hand-off row to a hash this shell
* cannot render. Today only native keys are ever stamped (the frame stamps `active.kind ===
* "native"` alone), so this is defence rather than a fix; it costs one field and removes the
* class.
*/
href: string;
/** A hand-off opens the current application in a new tab, and the tile says so. */
external: boolean;
}
/* β `RecentSection` (today | week | older) IS DELETED WITH ITS BUCKETS β wave 24 item 13 / R10.
Home has ONE database section now, so a section id and a title lookup were two pieces of
machinery describing a shape that no longer varies. */
const SECOND = 1;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
export const DAY = 24 * HOUR;
/* β `WEEK_DAYS` deleted with the buckets (item 13 / R10). */
/**
* The chip's two letters.
*
* β `\p{L}\p{N}` AND NOT `[A-Za-z0-9]`, and this shell has already paid for that once: the
* account monogram at `Shell.tsx:299` carries the same note, because the Streamlit host's
* `_account_css` uses Python's `str.isalnum()` and an ASCII-only class here would give a
* non-Latin name an initial in one shell and a blank circle in the other. A database called
* "ΠΠ»ΠΈΠ΅Π½ΡΡ" gets "ΠΠ", not an empty tile.
*
* Two letters, not one: the reference tiles read "Un" / "Aa", and a single letter over a 26px
* chip is a bullet point rather than a name.
*/
export function initials(label: string): string {
const chars = String(label ?? "").match(/[\p{L}\p{N}]/gu) ?? [];
return chars.slice(0, 2).join("").toUpperCase();
}
/**
* "Opened N ago", in the largest unit that is still true.
*
* Rounds DOWN throughout (`Math.floor`), so a tile never claims more time has passed than has:
* at 119 minutes this says "1 hour ago", never "2 hours ago". A stamp in the FUTURE β a clock
* skew between the browser and the host β clamps to "just now" rather than rendering a negative
* count, which is the only honest thing a relative label can say about it.
*/
export function agoText(at: number, now: number): string {
const d = Math.max(0, Math.floor(now) - Math.floor(at));
if (d < MINUTE) return "Opened just now";
const unit = (n: number, one: string) => `Opened ${n} ${one}${n === 1 ? "" : "s"} ago`;
if (d < HOUR) return unit(Math.floor(d / MINUTE), "minute");
if (d < DAY) return unit(Math.floor(d / HOUR), "hour");
return unit(Math.floor(d / DAY), "day");
}
/* β `bucketOf`, `TITLES` and `groupRecents` STOOD HERE AND ARE DELETED (wave 24 item 13, R10).
They bucketed the recents into Today / Past 7 days / Older -- and bucketing RECENTS is exactly
what made a database you had never opened invisible on Home, which is the complaint item 13
answers. `allDatabases` below replaces them: it starts from `entries` (so the C10 law is
STRUCTURAL now rather than a dropped-key `if`) and uses the stamps only to order.
β SWEPT IN THE SAME CHANGE that removed the last call site, and its TESTS retargeted with it.
`verify_home` stayed 107/107 green over this whole edit because its node section still ran
`groupRecents` directly -- a gate passing on a function the product no longer calls. That is
the GATE-DELTA tell, caught here rather than at close-out. */
// ββ WAVE 24 item 13 (ruling R10): EVERY database, and EVERY automation ββββββββββββββββββββββ
//
// β WHY THE DATE BUCKETS WENT. The deleted `groupRecents` only ever emitted a tile for a key
// already in the reader's RECENTS bucket, so a database you had never opened did not appear on
// Home at all β which is exactly the complaint. Sorting is the part worth keeping:
// most-recently-opened first is a real ranking and costs nothing.
//
// β THE CLOCK IS STILL A PARAMETER and the C10 law still holds: every tile is resolved from
// `entries`, the shaped server-filtered nav, so Home cannot name a database `/nav` did not send.
// What changed is which of those entries get drawn β all of them now, not just the stamped ones.
/** One automation, as Home draws it. The shape `AutomationSurface`'s rail already computes. */
export interface AutomationTile {
id: string;
name: string;
/* β WAVE 26 Β· ITEM 18 (R14) β `state` STOOD HERE AND IS DELETED WITH THE DOT IT FED.
It carried the dot's vocabulary (`ok` | `error` | `partial` | `running` | `idle`), computed by
`stateOf` in the frame. R14 removes status colour from the automation module, so nothing reads
it β and a tile field that survives its only reader is how the dot gets rendered back in by
somebody who finds the data already there and assumes it is wanted. Removing it from the TYPE
is what makes that impossible rather than merely unlikely: `tsc` now rejects the producer too,
which is the point (`Shell.tsx` computed it). */
/** The rail's own second line: "Next β¦" when scheduled, else "Last run β¦", else "Manual only". */
sub: string;
}
/**
* Every database this account may open, most-recently-opened first, then alphabetical.
*
* β NOT `recents` DRIVEN β `recents` only ORDERS it. A key with no stamp sorts after every
* stamped one and keeps its place alphabetically, which is what makes a never-opened database
* visible for the first time (R10's whole point).
*
* β `ago` IS EMPTY FOR AN UNSTAMPED TILE, deliberately: "Opened just now" is what `agoText`
* returns for a missing stamp (it clamps), and printing that under a database nobody has ever
* opened would be the surface inventing a fact. An empty string renders no line at all.
*/
/* β WAVE 25 (D-54) β `DatabaseEntry[]`, so the function that MAKES the tiles cannot be handed a
list containing a surface. This is where the wave-24 defect actually rendered: `entries` was
the raw nav, the Automation surface is a native entry with an href, and both of this filter's
conditions passed it through. The filter is unchanged and still right for what it tests
(a folder head has no destination); what it never tested is whether a destination is a
DATABASE, which is not a question this module can answer and is now settled before the call. */
export function allDatabases(
entries: DatabaseEntry[],
recents: Recent[],
now: number
): RecentTile[] {
const at = new Map(recents.map((r) => [r.key, r.at]));
const seen = new Set<string>();
return entries
// W63-T29 / D-762: a granted connector database is identified by its native `ut_` key,
// not by whether an older nav shaper happened to attach an href. The server-filtered entry
// remains the outer permission bound; this only stops the Data projection from narrowing a
// valid connector row away. De-duplicate by key because the same database can transiently be
// present in both a registry refresh and the user-table merge, but it has one Data identity.
.filter((e) => e.kind !== "group" && (!!e.href || e.key.startsWith("ut_")))
.filter((e) => {
if (seen.has(e.key)) return false;
seen.add(e.key);
return true;
})
.map((e) => {
const stamp = at.get(e.key);
return {
key: e.key,
label: e.label,
...(e.icon ? { icon: e.icon } : {}),
source: e.source,
sourceGroup: e.sourceGroup,
managedBy: e.managedBy,
at: stamp ?? 0,
ago: stamp === undefined ? "" : agoText(stamp, now),
initials: initials(e.label),
// Data owns one canonical, shareable address for every user-table database. This also
// repairs old/stale nav rows that pre-date that address without inventing any database:
// the row still had to arrive through the granted `/nav` payload above.
href: e.href ?? `#/table?database=${encodeURIComponent(e.key)}`,
external: e.kind === "handoff" && !e.key.startsWith("ut_"),
};
})
.sort((a, b) => (b.at - a.at) || a.label.localeCompare(b.label));
}
/**
* The server's recents, plus the stamps THIS SESSION made since the nav was fetched.
*
* β WITHOUT THIS, HOME IS ALWAYS ONE NAVIGATION STALE β and it is the wave's headline feature
* that would be stale. `recents` rides the `GET /nav` payload (one round trip per sign-in, per
* `navEpoch` bump), while the stamp is a fire-and-forget POST that changes nothing the client
* holds. So: open a database, go Home, and the database you just opened is not in Today. The
* alternative β refetching the whole nav on every route change to pick up one integer β is a
* request per navigation for a decoration.
*
* LOCAL WINS ON A KEY, always: it is strictly newer by construction (it happened after the
* fetch). And it is deliberately NOT persisted anywhere β a reload re-asks the server, which is
* the only end that actually knows.
*/
export function mergeRecents(server: Recent[], local: Record<string, number>): Recent[] {
const byKey = new Map<string, number>();
for (const r of server) byKey.set(r.key, r.at);
for (const [key, at] of Object.entries(local)) {
const cur = byKey.get(key);
if (cur === undefined || at > cur) byKey.set(key, at);
}
return [...byKey.entries()]
.map(([key, at]) => ({ key, at }))
.sort((a, b) => b.at - a.at);
}
// ββ the list/grid toggle ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type HomeLayout = "grid" | "list";
/** Per-browser, like the nav's collapsed state β a display preference, not account state. */
export const HOME_LAYOUT_KEY = "aios-home-layout";
/** Anything unrecognised reads as `grid`, which is the reference layout and the denser one. */
export function parseLayout(raw: unknown): HomeLayout {
return raw === "list" ? "list" : "grid";
}
// ββ WAVE 55: Home's starred-only filter βββββββββββββββββββββββββββββββββββββββββββββββββββ
export type HomeFilter = "all" | "starred";
/** An old `#/starred` bookmark is rewritten to Home with this query value. */
export function parseHomeFilter(raw: unknown): HomeFilter {
return raw === "starred" ? "starred" : "all";
}
/** One pure filter for every Home tile species, so the toggle cannot mean different things. */
export function applyHomeFilter<T>(
rows: T[],
filter: HomeFilter,
isStarred: (row: T) => boolean,
): T[] {
return filter === "starred" ? rows.filter(isStarred) : rows;
}
// W61-T20 / C6: the same module index can be consumed by a home or its rail.
export type ModuleFolder = { id: string; name: string; parent?: string | null };
export type ModuleFolderIndex = {
folders: ModuleFolder[];
itemFolders: Record<string, string>;
rev: number;
/** Additive per-user disclosure state shared by App-derived chrome groups. */
collapsedGroups?: string[];
};
export function parseModuleFolderIndex(raw: unknown): ModuleFolderIndex | null {
if (!raw || typeof raw !== "object") return null;
const value = raw as ModuleFolderIndex;
if (!Number.isInteger(value.rev) || value.rev < 0 || !Array.isArray(value.folders)
|| !value.itemFolders || typeof value.itemFolders !== "object" || Array.isArray(value.itemFolders)) return null;
if (value.collapsedGroups !== undefined && (!Array.isArray(value.collapsedGroups)
|| value.collapsedGroups.some((id) => typeof id !== "string"))) return null;
if (value.folders.some((folder) => !folder || typeof folder.id !== "string" || typeof folder.name !== "string"
|| (folder.parent != null && typeof folder.parent !== "string"))
|| Object.values(value.itemFolders).some((id) => typeof id !== "string")) return null;
return value;
}
export const FINANCE_NAV_GROUP = "finance";
export type NavigationApplication = {
id: string;
name: string;
deepLink?: string;
compatibleDatabases?: string[];
openTarget?: { database?: string | null };
navPlacement?: { section?: string; order?: number };
};
// Retired Finance Apps never contribute navigation, including historical payloads.
export function financeNavigation<T extends NavigationApplication>(_rows: readonly T[]): T[] {
return [];
}
type ModuleTile = { id: string; kind?: "agent" | "voice" } | { key: string };
export function moduleTileId(row: ModuleTile): string {
if ("key" in row) return row.key;
return row.kind ? row.kind + ":" + row.id : row.id;
}
export function modulePlacementMap(index: ModuleFolderIndex): Record<string, string> {
const folders = new Set(index.folders.map((folder) => folder.id));
return Object.fromEntries(Object.entries(index.itemFolders).filter(([, id]) => folders.has(id)));
}
export function moduleFolderPath(index: { folders: readonly ModuleFolder[] }, folderId: string | null): ModuleFolder[] {
const byId = new Map(index.folders.map((folder) => [folder.id, folder]));
const path: ModuleFolder[] = [];
const seen = new Set<string>();
let folder = folderId ? byId.get(folderId) : undefined;
while (folder && !seen.has(folder.id)) {
path.unshift(folder);
seen.add(folder.id);
folder = folder.parent ? byId.get(folder.parent) : undefined;
}
return path;
}
export function moduleFolderLevel<T extends ModuleTile>(
rows: readonly T[], index: ModuleFolderIndex, folderId: string | null,
) {
const breadcrumb = moduleFolderPath(index, folderId);
const current = breadcrumb[breadcrumb.length - 1]?.id ?? null;
const placement = modulePlacementMap(index);
const folders = index.folders.filter((folder) => (folder.parent ?? null) === current);
const items = rows.filter((row) => (placement[moduleTileId(row)] ?? null) === current);
return { current, breadcrumb, folders, items,
empty: current !== null && folders.length === 0 && items.length === 0 };
}
/** An origin is addressed by its stable key (`CUSTOM_ORIGIN_KEY` or a connector label), never its name. */
export type DataHomeLocation = { kind: "root" } | { kind: "folder"; id: string }
| { kind: "origin"; key: string };
export type HomeFolderTile = ({ kind: "folder" } & ModuleFolder
| { kind: "origin"; key: string; name: string; connector: string | null }) & { count: number };
type DataHomeRow = Pick<RecentTile, "key" | "label" | "source" | "sourceGroup" | "managedBy">;
/** C5: user placement comes from the shared index; origin identity comes from the rail helper. */
export function dataHomeLevel<T extends DataHomeRow>(
rows: readonly T[], index: ModuleFolderIndex, at: DataHomeLocation, navOrder: readonly string[] = [],
) {
const level = moduleFolderLevel(rows, index, at.kind === "folder" ? at.id : null);
// The same placement map `moduleFolderLevel` reads: a placement naming a folder that no longer
// exists counts as unplaced, so its database returns to its origin instead of vanishing.
const placement = modulePlacementMap(index);
const tiles: HomeFolderTile[] = level.folders.map((folder) => ({
...folder, kind: "folder", count: rows.filter((row) => placement[row.key] === folder.id).length,
}));
if (at.kind === "folder" && level.current) return { ...level, tiles, origin: null };
const unplaced = rows.filter((row) => !placement[row.key]);
// Custom comes first; connector origins keep the nav order, independent of database recency.
const rank = new Map(navOrder.map((key, at) => [key, at]));
const byNav = [...unplaced].sort((a, b) => (rank.get(a.key) ?? rank.size) - (rank.get(b.key) ?? rank.size));
const groups = groupDataDatabases(byNav.map((row) => ({ ...row, source: row.sourceGroup ?? row.source })));
const hasConnector = groups.some((group) => group.key !== CUSTOM_ORIGIN_KEY);
if (at.kind === "origin") {
const keys = new Set(groups.find((group) => group.key === at.key)?.databases.map((row) => row.key));
const items = unplaced.filter((row) => keys.has(row.key));
// Origins never acquire an id, ancestry or placement in the server's user-folder index.
return { current: null, breadcrumb: [], folders: [], tiles: [], items,
origin: dataOriginLabel(at.key), empty: items.length === 0 };
}
if (!hasConnector) return { ...level, tiles, origin: null };
return { ...level, items: [], origin: null, tiles: [...tiles, ...groups.map((group) => ({
kind: "origin" as const, key: group.key, name: group.label, connector: group.connector,
count: group.databases.length,
}))] };
}
/** S67-T37 (O17): Home folds its Databases through `dataHomeLevel` whenever a connector database
* is granted, so the two homes cannot disagree about the root. With none, Home keeps its flat
* list (the NC). Same origin rule as the Data home, applied to every row, filed or not. */
export function homeDataFolds<T extends DataHomeRow>(rows: readonly T[]): boolean {
return groupDataDatabases(rows.map((row) => ({ ...row, source: row.sourceGroup ?? row.source })))
.some((group) => group.key !== CUSTOM_ORIGIN_KEY);
}
export function moveModuleItems(index: ModuleFolderIndex, ids: readonly string[], folder: string | null): ModuleFolderIndex {
if (folder !== null && !index.folders.some((row) => row.id === folder)) return index;
// Preserve untouched placements, including Sheet's explicit top-level marker.
const itemFolders = { ...index.itemFolders };
for (const id of ids) {
if (folder === null) delete itemFolders[id];
else itemFolders[id] = folder;
}
return { ...index, itemFolders };
}
export function saveModuleFolder(index: ModuleFolderIndex, folder: ModuleFolder): ModuleFolderIndex {
const name = folder.name.trim();
if (!name) return index;
const exists = index.folders.some((row) => row.id === folder.id);
const folders = exists
? index.folders.map((row) => row.id === folder.id ? { ...row, name } : row)
: [...index.folders, { ...folder, name }];
return { ...index, folders };
}
/** Count the direct items and child folders that deletion promotes to the top level. */
export function moduleFolderChildCount(index: ModuleFolderIndex, id: string): number {
if (!index.folders.some((folder) => folder.id === id)) return 0;
return index.folders.filter((folder) => folder.parent === id).length
+ Object.values(modulePlacementMap(index)).filter((folderId) => folderId === id).length;
}
export function deleteModuleFolder(index: ModuleFolderIndex, id: string): ModuleFolderIndex {
// Remove the folder, promote its children, and return its items to the top level.
const folders = index.folders.filter((folder) => folder.id !== id)
.map((folder) => folder.parent === id ? { ...folder, parent: null } : folder);
const itemFolders = Object.fromEntries(Object.entries(index.itemFolders).filter(([, folderId]) => folderId !== id));
return { ...index, folders, itemFolders };
}
// ββ S79-T61 (R54): one shared icon for shared-with-me and shared-by-me βββββββββββββββββββββ
/** One tile's share mark from `GET /share/marks`. The icon is one; the words say the direction. */
export type ShareMark = { direction: "with_me"; by: string }
| { direction: "by_me"; count: number; everyone: boolean };
export type ShareMarks = ReadonlyMap<string, ShareMark>;
export const NO_SHARE_MARKS: ShareMarks = new Map();
export type ShareMarkKind = "database" | "view" | "folder" | "workbook" | "app" | "agent";
/** The wire key: `<kind>:<id>`. View ids are bare, as the grant registry stores them. */
export function shareMarkKey(kind: ShareMarkKind, id: string): string {
return kind + ":" + id;
}
/** A malformed or failed answer reads as no marks: a tile never shows a wrong icon. */
export function parseShareMarks(body: unknown): ShareMarks {
const raw = body && typeof body === "object" ? (body as { marks?: unknown }).marks : null;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return NO_SHARE_MARKS;
const out = new Map<string, ShareMark>();
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (!value || typeof value !== "object") continue;
const mark = value as Record<string, unknown>;
if (mark.direction === "with_me") {
out.set(key, { direction: "with_me", by: typeof mark.by === "string" ? mark.by.trim() : "" });
} else if (mark.direction === "by_me" && Number.isSafeInteger(mark.count) && (mark.count as number) >= 0
&& (mark.everyone === true || (mark.count as number) > 0)) {
out.set(key, { direction: "by_me", count: mark.count as number, everyone: mark.everyone === true });
}
}
return out;
}
/** The tooltip: who shared it with me, or how many I shared it with. */
export function shareMarkText(mark: ShareMark): string {
if (mark.direction === "with_me") return mark.by ? `Shared with you by ${mark.by}` : "Shared with you";
if (mark.everyone) return "Shared with everyone";
return mark.count === 1 ? "Shared with 1 person" : `Shared with ${mark.count} people`;
}
|