agy-family 0.6.4 → 0.6.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -71,7 +71,7 @@ import {
71
71
  upsertHostEntry,
72
72
  } from '../src/host.mjs';
73
73
 
74
- const CLI_VERSION = '0.6.4';
74
+ const CLI_VERSION = '0.6.6';
75
75
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
76
76
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
77
77
 
@@ -382,6 +382,32 @@ async function runHookCommand(eventArg) {
382
382
  child.unref();
383
383
  }
384
384
  } catch {}
385
+ } else if (capturedRes.captured) {
386
+ // Collaborative family quota sync: verified members passively help keep the shared family pool up to date!
387
+ try {
388
+ const clientCfg = readJsonSafe(clientConfigPath(home));
389
+ const expectedHash = String(clientCfg?.expectedEmailHash || '').trim().toLowerCase();
390
+ const capturedHash = String(capturedRes.emailHash || '').trim().toLowerCase();
391
+ const memberMatches = Boolean(
392
+ clientCfg?.url &&
393
+ clientCfg?.token &&
394
+ (!expectedHash || (capturedHash && capturedHash === expectedHash)),
395
+ );
396
+ if (memberMatches) {
397
+ const throttlePath = join(configBaseDir(home), 'last-member-quota-push.json');
398
+ const prev = readJsonSafe(throttlePath);
399
+ const now = Date.now();
400
+ if (!prev?.ts || now - Number(prev.ts) >= 60_000) {
401
+ writePrivateJson(throttlePath, { ts: now });
402
+ const child = spawn(process.execPath, [THIS_CLI_PATH, 'sync', '--quiet'], {
403
+ detached: true,
404
+ stdio: 'ignore',
405
+ windowsHide: true,
406
+ });
407
+ child.unref();
408
+ }
409
+ }
410
+ } catch {}
385
411
  }
386
412
 
387
413
  const chain = readJsonSafe(statusLineChainPath(home));
@@ -451,6 +477,13 @@ async function performJoin({ rawInvite, noHook = false, withDaemon = false }) {
451
477
  cliPath: THIS_CLI_PATH,
452
478
  });
453
479
  console.log(`✓ Installed /family zero-token command & auto-sync hook (${info.hooksFile})`);
480
+ const tap = installStatusLineTap({
481
+ executable: process.execPath,
482
+ cliPath: THIS_CLI_PATH,
483
+ });
484
+ console.log(
485
+ `✓ Enabled zero-secret statusLine quota capture (${tap.chained ? 'chained seamlessly with your existing statusLine' : 'standalone'})`,
486
+ );
454
487
  }
455
488
  if (withDaemon) {
456
489
  const d = installBackgroundDaemon({
@@ -553,18 +586,31 @@ async function main() {
553
586
  executable: process.execPath,
554
587
  cliPath: THIS_CLI_PATH,
555
588
  });
556
- console.log(`✓ Enabled /family slash command & Stop auto-sync hook:\n Skill: ${info.skillFile}\n Hooks: ${info.hooksFile}`);
589
+ const tap = installStatusLineTap({
590
+ executable: process.execPath,
591
+ cliPath: THIS_CLI_PATH,
592
+ });
593
+ console.log(
594
+ `✓ Enabled /family slash command, Stop auto-sync & zero-secret statusLine quota capture:\n Skill : ${info.skillFile}\n Hooks : ${info.hooksFile}\n statusLine : active (${tap.chained ? 'chained with existing statusLine' : 'standalone'})`,
595
+ );
557
596
  return;
558
597
  }
559
598
  if (action === 'off' || action === 'uninstall' || action === 'remove') {
560
599
  const info = uninstallAntigravityIntegration();
561
- console.log(`✓ Removed agy-family hook (${info.removedHook ? 'deleted' : 'not present'}) and /family skill (${info.removedSkill ? 'deleted' : 'not present'}).`);
600
+ const sl = !readMasterConfig() ? uninstallStatusLineTap() : { restored: false };
601
+ console.log(
602
+ `✓ Removed agy-family hook (${info.removedHook ? 'deleted' : 'not present'}) and /family skill (${info.removedSkill ? 'deleted' : 'not present'})${sl.restored ? '; restored previous statusLine' : ''}.`,
603
+ );
562
604
  return;
563
605
  }
564
606
  const status = inspectAntigravityIntegration();
607
+ const tapStatus = inspectStatusLineTap();
565
608
  console.log(`Antigravity /family Integration:`);
566
- console.log(` Hook : ${status.hookInstalled ? (status.hookEnabled ? 'enabled' : 'disabled') : 'not installed'} (${status.hooksFile})`);
567
- console.log(` Skill : ${status.skillInstalled ? 'installed' : 'not installed'} (${status.skillFile})`);
609
+ console.log(` Hook : ${status.hookInstalled ? (status.hookEnabled ? 'enabled' : 'disabled') : 'not installed'} (${status.hooksFile})`);
610
+ console.log(` Skill : ${status.skillInstalled ? 'installed' : 'not installed'} (${status.skillFile})`);
611
+ console.log(
612
+ ` statusLine : ${tapStatus.installed ? `active (${tapStatus.chained ? 'chained' : 'standalone'})` : 'not installed'}`,
613
+ );
568
614
  return;
569
615
  }
570
616
 
@@ -890,7 +890,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
890
890
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
891
891
  deviceId,
892
892
  clientKind: 'cli',
893
- clientVersion: '0.6.4',
893
+ clientVersion: '0.6.6',
894
894
  home,
895
895
  fileCache: cache,
896
896
  syncedHashes: prevHashes,
@@ -83,7 +83,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
83
83
  export async function buildSyncPayload({
84
84
  deviceId,
85
85
  clientKind = 'cli',
86
- clientVersion = '0.6.4',
86
+ clientVersion = '0.6.6',
87
87
  home,
88
88
  roots = null,
89
89
  sourceFilter = 'all',
@@ -164,7 +164,7 @@ export async function buildSyncPayload({
164
164
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
165
165
  client: {
166
166
  kind: clientKind === 'extension' ? 'extension' : 'cli',
167
- version: String(clientVersion || '0.6.4').slice(0, 24),
167
+ version: String(clientVersion || '0.6.6').slice(0, 24),
168
168
  ...(platformLabel ? { platform: platformLabel } : {}),
169
169
  },
170
170
  account: {
@@ -26,7 +26,7 @@ import {
26
26
  import { FAVICON_SVG, renderDashboardHtml } from './ui.mjs';
27
27
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
28
28
 
29
- export const SERVER_VERSION = '0.6.4';
29
+ export const SERVER_VERSION = '0.6.6';
30
30
  const MAX_BUCKETS_PER_SYNC = 1000;
31
31
  const MAX_DEVICES_PER_MEMBER = 8;
32
32
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -1202,19 +1202,22 @@ export function createApp({
1202
1202
  const isExplicitMaster = Boolean(body.subscriptionQuota?.isMasterExplicit);
1203
1203
  const incomingQuotaHash = String(body.subscriptionQuota?.emailHash || '').trim().toLowerCase();
1204
1204
  const validIncomingHash = /^[a-f0-9]{64}$/.test(incomingQuotaHash) ? incomingQuotaHash : '';
1205
- const mgrBoundHash = String(member.expected_email_hash || '').trim().toLowerCase();
1206
- const quotaHashMatchesManager = mgrBoundHash
1207
- ? (validIncomingHash ? validIncomingHash === mgrBoundHash : !isMismatch)
1205
+ const boundHash = String(member.expected_email_hash || '').trim().toLowerCase();
1206
+ const quotaHashMatchesMember = boundHash
1207
+ ? (validIncomingHash ? validIncomingHash === boundHash : !isMismatch)
1208
1208
  : (!isMismatch || isExplicitMaster);
1209
1209
  const safeLabel = normSubQuota.accountLabel || member.email_address || member.email_hint || member.name || '';
1210
1210
  const normWithLabel = { ...normSubQuota, accountLabel: safeLabel };
1211
- if (!isMismatch) {
1211
+ if (!isMismatch && quotaHashMatchesMember) {
1212
1212
  writeStmts.push({
1213
1213
  sql: UPSERT_SUBSCRIPTION_QUOTA_SQL,
1214
1214
  params: buildSubscriptionQuotaParams(`member:${member.id}`, member.id, normWithLabel, now),
1215
1215
  });
1216
+ if (member.role === 'member' && boundHash && accountStatus === 'verified') {
1217
+ masterQuotaUpdated = true;
1218
+ }
1216
1219
  }
1217
- if (member.role === 'manager' && quotaHashMatchesManager) {
1220
+ if (member.role === 'manager' && quotaHashMatchesMember) {
1218
1221
  writeStmts.push({
1219
1222
  sql: UPSERT_SUBSCRIPTION_QUOTA_SQL,
1220
1223
  params: buildSubscriptionQuotaParams('master', member.id, normWithLabel, now),
@@ -1765,7 +1768,7 @@ export function createApp({
1765
1768
  }
1766
1769
 
1767
1770
  if (request.method === 'DELETE' && path === '/api/admin/master-quota') {
1768
- await db.run('DELETE FROM subscription_quotas WHERE scope = ?', ['master']);
1771
+ await db.run('DELETE FROM subscription_quotas');
1769
1772
  const masterSubscriptionQuota = await loadMasterSubscriptionQuota(db, now);
1770
1773
  return adminJsonRes({ ok: true, masterSubscriptionQuota });
1771
1774
  }
@@ -378,15 +378,287 @@ export function evaluateSubscriptionQuotaRow(row, now = Date.now()) {
378
378
  };
379
379
  }
380
380
 
381
- export async function loadMasterSubscriptionQuota(db, now = Date.now()) {
381
+ const TIER_RANK = Object.freeze({
382
+ 'Google AI Ultra': 3,
383
+ 'Google AI Pro': 2,
384
+ Free: 1,
385
+ });
386
+
387
+ function pickConsensusPlanTier(masterRow, memberEntries) {
388
+ if (masterRow?.plan_tier) return normalizePlanTierLabel(masterRow.plan_tier);
389
+ const votes = new Map();
390
+ for (const e of memberEntries) {
391
+ const tier = normalizePlanTierLabel(e.row?.plan_tier || '');
392
+ if (!tier) continue;
393
+ const prev = votes.get(tier) || { count: 0, latestObserved: 0 };
394
+ prev.count += 1;
395
+ prev.latestObserved = Math.max(prev.latestObserved, e.observedAt);
396
+ votes.set(tier, prev);
397
+ }
398
+ let best = '';
399
+ let bestScore = null;
400
+ for (const [tier, info] of votes.entries()) {
401
+ const rank = TIER_RANK[tier] || 0;
402
+ if (
403
+ !bestScore ||
404
+ info.count > bestScore.count ||
405
+ (info.count === bestScore.count && rank > bestScore.rank) ||
406
+ (info.count === bestScore.count && rank === bestScore.rank && info.latestObserved > bestScore.latestObserved)
407
+ ) {
408
+ best = tier;
409
+ bestScore = { count: info.count, rank, latestObserved: info.latestObserved };
410
+ }
411
+ }
412
+ return best;
413
+ }
414
+
415
+ function reconcileQuotaBucket(candidates, { now, maxAgeMs }) {
416
+ const valid = candidates.filter((c) => c.pct !== null && c.pct !== undefined && Number.isFinite(Number(c.pct)));
417
+ if (valid.length === 0) return { pct: null, resetAt: null, winner: null };
418
+
419
+ const fresh = valid.filter((c) => c.observedAt > 0 && now - c.observedAt <= maxAgeMs);
420
+ const pool = fresh.length > 0 ? fresh : valid;
421
+
422
+ const annotated = pool.map((c) => {
423
+ const rawReset = c.resetAt && Number(c.resetAt) > QUOTA_EPOCH_SENTINEL_MS ? Number(c.resetAt) : null;
424
+ const isActiveFuture = Boolean(rawReset && rawReset > now);
425
+ const isExpired = Boolean(rawReset && rawReset <= now);
426
+ return {
427
+ ...c,
428
+ rawReset,
429
+ isActiveFuture,
430
+ isExpired,
431
+ effPct: isExpired ? 100 : Math.max(0, Math.min(100, Number(c.pct))),
432
+ };
433
+ });
434
+
435
+ const activeFuture = annotated.filter((c) => c.isActiveFuture);
436
+ if (activeFuture.length > 0) {
437
+ // Pick the active window observed most recently (breaking ties by master priority then later reset),
438
+ // then reconcile monotonically (minimum remaining %) across all observations in that same reset window (±10 min).
439
+ const newest = [...activeFuture].sort((a, b) => {
440
+ if (b.observedAt !== a.observedAt) return b.observedAt - a.observedAt;
441
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
442
+ return b.rawReset - a.rawReset;
443
+ })[0];
444
+ const sameWindow = activeFuture.filter((c) => Math.abs(c.rawReset - newest.rawReset) <= 10 * 60_000);
445
+ sameWindow.sort((a, b) => {
446
+ if (Math.abs(a.effPct - b.effPct) > 0.5) return a.effPct - b.effPct;
447
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
448
+ return b.observedAt - a.observedAt;
449
+ });
450
+ const winner = sameWindow[0];
451
+ return { pct: winner.effPct, resetAt: winner.rawReset, winner };
452
+ }
453
+
454
+ annotated.sort((a, b) => {
455
+ const dt = Math.abs(b.observedAt - a.observedAt);
456
+ if (dt <= 15 * 60_000 && Math.abs(a.effPct - b.effPct) > 0.5) return a.effPct - b.effPct;
457
+ if (b.observedAt !== a.observedAt) return b.observedAt - a.observedAt;
458
+ if (a.isMaster !== b.isMaster) return a.isMaster ? -1 : 1;
459
+ return a.effPct - b.effPct;
460
+ });
461
+ const winner = annotated[0];
462
+ return { pct: winner.effPct, resetAt: winner.rawReset, winner };
463
+ }
464
+
465
+ export function reconcileFamilySubscriptionQuota(allRows = [], membersRaw = [], now = Date.now()) {
466
+ const rows = Array.isArray(allRows) ? allRows : [];
467
+ const activeMembers = (membersRaw || []).filter((m) => m && (m.active === undefined || Boolean(m.active)));
468
+ const memberById = new Map(activeMembers.map((m) => [m.id, m]));
469
+ const mgrRow = activeMembers.find((m) => m.role === 'manager') || null;
470
+
471
+ const masterRow = rows.find((r) => r && r.scope === 'master') || null;
472
+ const memberQuotasById = new Map();
473
+ const eligibleMembers = [];
474
+
475
+ for (const r of rows) {
476
+ if (!r || typeof r.scope !== 'string' || !r.scope.startsWith('member:')) continue;
477
+ const mid = r.scope.slice(7);
478
+ const m = memberById.get(mid);
479
+ if (!m || m.last_account_status === 'mismatch') continue;
480
+ const ev = evaluateSubscriptionQuotaRow(r, now);
481
+ if (!ev.configured) continue;
482
+ memberQuotasById.set(mid, ev);
483
+
484
+ const isEligible =
485
+ m.role === 'manager' ||
486
+ (Boolean(m.expected_email_hash) && m.last_account_status === 'verified');
487
+ if (isEligible) {
488
+ eligibleMembers.push({
489
+ row: r,
490
+ member: m,
491
+ observedAt: Number(r.observed_at || r.updated_at) || 0,
492
+ updatedAt: Number(r.updated_at || r.observed_at) || 0,
493
+ isMaster: m.role === 'manager',
494
+ });
495
+ }
496
+ }
497
+
498
+ const isManualMaster = Boolean(masterRow && masterRow.source === 'manual');
499
+ const manualCutoffMs = isManualMaster ? Number(masterRow.updated_at || masterRow.observed_at || 0) : 0;
500
+ const postManualMembers = isManualMaster
501
+ ? eligibleMembers.filter((e) => e.observedAt > manualCutoffMs)
502
+ : eligibleMembers;
503
+
504
+ const authPlanTier = pickConsensusPlanTier(masterRow, postManualMembers);
505
+ const tierAlignedMembers = authPlanTier
506
+ ? postManualMembers.filter((e) => {
507
+ if (e.isMaster) return true;
508
+ const mt = normalizePlanTierLabel(e.row?.plan_tier || '');
509
+ return !mt || mt === authPlanTier;
510
+ })
511
+ : postManualMembers;
512
+
513
+ const allSources = [];
514
+ if (masterRow) {
515
+ allSources.push({
516
+ row: masterRow,
517
+ isMaster: true,
518
+ memberId: masterRow.member_id || mgrRow?.id || null,
519
+ memberName: mgrRow?.name || 'Master',
520
+ role: 'manager',
521
+ observedAt: Number(masterRow.observed_at || masterRow.updated_at) || 0,
522
+ updatedAt: Number(masterRow.updated_at || masterRow.observed_at) || 0,
523
+ source: masterRow.source || 'sync',
524
+ });
525
+ }
526
+ for (const e of tierAlignedMembers) {
527
+ // Avoid double-counting the manager's own older `member:<mgr>` row when `scope='master'` is already newer.
528
+ if (masterRow && (e.isMaster || e.member.id === masterRow.member_id) && e.observedAt <= Number(masterRow.observed_at || masterRow.updated_at || 0)) {
529
+ continue;
530
+ }
531
+ allSources.push({
532
+ row: e.row,
533
+ isMaster: e.isMaster,
534
+ memberId: e.member.id,
535
+ memberName: e.member.name,
536
+ role: e.member.role === 'manager' ? 'manager' : 'member',
537
+ observedAt: e.observedAt,
538
+ updatedAt: e.updatedAt,
539
+ source: e.row.source || 'sync',
540
+ });
541
+ }
542
+
543
+ if (allSources.length === 0) {
544
+ return {
545
+ masterSubscriptionQuota: evaluateSubscriptionQuotaRow(null, now),
546
+ memberQuotasById,
547
+ };
548
+ }
549
+
550
+ const buildCands = (pctField, resetField) =>
551
+ allSources.map((s) => ({
552
+ pct: s.row[pctField],
553
+ resetAt: s.row[resetField],
554
+ observedAt: s.observedAt,
555
+ updatedAt: s.updatedAt,
556
+ isMaster: s.isMaster,
557
+ memberId: s.memberId,
558
+ memberName: s.memberName,
559
+ role: s.role,
560
+ source: s.source,
561
+ }));
562
+
563
+ const g5 = reconcileQuotaBucket(buildCands('gemini_5h_pct', 'gemini_5h_reset_at'), { now, maxAgeMs: 12 * HOUR_MS });
564
+ const gw = reconcileQuotaBucket(buildCands('gemini_weekly_pct', 'gemini_weekly_reset_at'), { now, maxAgeMs: 7 * DAY_MS });
565
+ const c5 = reconcileQuotaBucket(buildCands('third_party_5h_pct', 'third_party_5h_reset_at'), { now, maxAgeMs: 12 * HOUR_MS });
566
+ const cw = reconcileQuotaBucket(buildCands('third_party_weekly_pct', 'third_party_weekly_reset_at'), { now, maxAgeMs: 7 * DAY_MS });
567
+
568
+ const winners = [g5.winner, gw.winner, c5.winner, cw.winner].filter(Boolean);
569
+ const latestObservedAt = winners.length > 0
570
+ ? Math.max(...winners.map((w) => w.observedAt || 0))
571
+ : Math.max(...allSources.map((s) => s.observedAt || 0));
572
+ const latestUpdatedAt = winners.length > 0
573
+ ? Math.max(...winners.map((w) => w.updatedAt || 0))
574
+ : Math.max(...allSources.map((s) => s.updatedAt || 0));
575
+
576
+ const freshContributorsMap = new Map();
577
+ for (const s of allSources) {
578
+ const isFresh = s.observedAt > 0 && now - s.observedAt <= 12 * HOUR_MS;
579
+ if (!isFresh && !winners.some((w) => w.memberId === s.memberId && w.isMaster === s.isMaster)) continue;
580
+ const key = s.memberId || (s.isMaster ? '__master__' : s.memberName);
581
+ const prev = freshContributorsMap.get(key);
582
+ if (!prev || s.observedAt > prev.observedAt) {
583
+ freshContributorsMap.set(key, {
584
+ id: s.memberId || null,
585
+ name: s.memberName,
586
+ role: s.role,
587
+ isMaster: s.isMaster,
588
+ observedAt: s.observedAt,
589
+ });
590
+ }
591
+ }
592
+ const contributors = Array.from(freshContributorsMap.values()).sort((a, b) => b.observedAt - a.observedAt);
593
+ const hasMasterContrib = Boolean(masterRow) || contributors.some((c) => c.isMaster);
594
+ const hasMemberContrib = contributors.some((c) => !c.isMaster);
595
+ const syncMode = hasMemberContrib ? (hasMasterContrib ? 'reconciled' : 'collaborative') : 'master';
596
+ const primaryWinner = g5.winner || gw.winner || c5.winner || cw.winner || allSources[0];
597
+
598
+ const mergedRow = {
599
+ scope: 'master',
600
+ member_id: masterRow?.member_id || mgrRow?.id || primaryWinner?.memberId || null,
601
+ account_label: masterRow?.account_label || mgrRow?.email_address || mgrRow?.email_hint || mgrRow?.name || '',
602
+ plan_tier: authPlanTier || masterRow?.plan_tier || '',
603
+ gemini_5h_pct: g5.pct,
604
+ gemini_5h_reset_at: g5.resetAt,
605
+ gemini_weekly_pct: gw.pct,
606
+ gemini_weekly_reset_at: gw.resetAt,
607
+ third_party_5h_pct: c5.pct,
608
+ third_party_5h_reset_at: c5.resetAt,
609
+ third_party_weekly_pct: cw.pct,
610
+ third_party_weekly_reset_at: cw.resetAt,
611
+ source: syncMode === 'master' ? (masterRow?.source || primaryWinner?.source || 'sync') : `family-${syncMode}`,
612
+ observed_at: latestObservedAt || now,
613
+ updated_at: latestUpdatedAt || now,
614
+ };
615
+
616
+ const evaluated = evaluateSubscriptionQuotaRow(mergedRow, now);
617
+ return {
618
+ masterSubscriptionQuota: {
619
+ ...evaluated,
620
+ syncMode,
621
+ contributorCount: contributors.length,
622
+ contributors: contributors.map((c) => ({ name: c.name, role: c.role, observedAt: c.observedAt })),
623
+ latestContributorName: contributors[0]?.name || '',
624
+ },
625
+ memberQuotasById,
626
+ };
627
+ }
628
+
629
+ export async function loadMasterSubscriptionQuota(db, now = Date.now(), membersRaw = null) {
382
630
  try {
383
- const row = await db.get('SELECT * FROM subscription_quotas WHERE scope = ?', ['master']);
384
- return evaluateSubscriptionQuotaRow(row || null, now);
631
+ const rows = await db.all('SELECT * FROM subscription_quotas');
632
+ const members =
633
+ Array.isArray(membersRaw)
634
+ ? membersRaw
635
+ : await db.all(
636
+ 'SELECT id, name, role, expected_email_hash, email_address, email_hint, last_account_status, active FROM members WHERE active = 1',
637
+ );
638
+ return reconcileFamilySubscriptionQuota(rows || [], members || [], now).masterSubscriptionQuota;
385
639
  } catch {
386
640
  return evaluateSubscriptionQuotaRow(null, now);
387
641
  }
388
642
  }
389
643
 
644
+ export async function loadAllSubscriptionQuotas(db, now = Date.now(), membersRaw = null) {
645
+ try {
646
+ const rows = await db.all('SELECT * FROM subscription_quotas');
647
+ const members =
648
+ Array.isArray(membersRaw)
649
+ ? membersRaw
650
+ : await db.all(
651
+ 'SELECT id, name, role, expected_email_hash, email_address, email_hint, last_account_status, active FROM members WHERE active = 1',
652
+ );
653
+ return reconcileFamilySubscriptionQuota(rows || [], members || [], now);
654
+ } catch {
655
+ return {
656
+ masterSubscriptionQuota: evaluateSubscriptionQuotaRow(null, now),
657
+ memberQuotasById: new Map(),
658
+ };
659
+ }
660
+ }
661
+
390
662
  /**
391
663
  * Resolve per-member percentage quota allocation across active family members.
392
664
  * - Members with explicit `quota_pct > 0` keep their pinned percentage.
@@ -1283,6 +1555,7 @@ export async function buildBoardPayload(
1283
1555
  const activeMemberCount = (membersRaw || []).length;
1284
1556
  const maskPublicEmail = Boolean(settings.maskPublicEmail);
1285
1557
  const maskPublicIp = Boolean(settings.maskPublicIp);
1558
+ const { masterSubscriptionQuota, memberQuotasById } = await loadAllSubscriptionQuotas(db, now, membersRaw);
1286
1559
 
1287
1560
  const members = (membersRaw || []).map((raw) => {
1288
1561
  const agg = byMember.get(raw.id);
@@ -1375,6 +1648,18 @@ export async function buildBoardPayload(
1375
1648
  emailHint: formatBoardEmail(raw.email_address, raw.email_hint, maskPublicEmail),
1376
1649
  accountStatus: raw.expected_email_hash ? raw.last_account_status || 'unknown' : 'unbound',
1377
1650
  integrityFlags7d: integrityByMember.get(raw.id) || 0,
1651
+ subscriptionQuota: (() => {
1652
+ const mq = memberQuotasById.get(raw.id);
1653
+ if (!mq || !mq.configured) return null;
1654
+ return {
1655
+ planTier: mq.planTier || '',
1656
+ status: mq.status,
1657
+ observedAt: mq.observedAt,
1658
+ stale: mq.stale,
1659
+ gemini: mq.gemini,
1660
+ thirdParty: mq.thirdParty,
1661
+ };
1662
+ })(),
1378
1663
  };
1379
1664
  });
1380
1665
 
@@ -1415,7 +1700,6 @@ export async function buildBoardPayload(
1415
1700
  poolTotalCredits > 0 ? roundPct(((projectedCycleUsd * creditsPerUsd) / poolTotalCredits) * 100) : null;
1416
1701
 
1417
1702
  const creditsReconciliation = await computeCreditsReconciliation(db, membersRaw, settings, cycleInfo);
1418
- const masterSubscriptionQuota = await loadMasterSubscriptionQuota(db, now);
1419
1703
 
1420
1704
  const estUsedCredits = Math.round(totalUsd * creditsPerUsd);
1421
1705
  const poolUsedPct = poolTotalCredits > 0 ? roundPct((estUsedCredits / poolTotalCredits) * 100) : null;
@@ -180,6 +180,37 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
180
180
  border-radius: 50%;
181
181
  background: var(--good);
182
182
  flex-shrink: 0;
183
+ transition: background 0.15s ease;
184
+ }
185
+ .sync-dot.paused {
186
+ background: var(--muted);
187
+ opacity: 0.6;
188
+ }
189
+ .sync-sep {
190
+ opacity: 0.45;
191
+ user-select: none;
192
+ }
193
+ .refresh-select {
194
+ appearance: none;
195
+ -webkit-appearance: none;
196
+ border: none;
197
+ background: transparent;
198
+ color: var(--body);
199
+ font-family: var(--font-mono);
200
+ font-size: 11px;
201
+ line-height: 1.2;
202
+ padding: 1px 4px;
203
+ border-radius: 4px;
204
+ cursor: pointer;
205
+ outline: none;
206
+ }
207
+ .refresh-select:hover, .refresh-select:focus-visible {
208
+ background: var(--hover);
209
+ color: var(--ink);
210
+ }
211
+ .refresh-select option {
212
+ background: var(--surface-card);
213
+ color: var(--ink);
183
214
  }
184
215
  .icon-refresh {
185
216
  display: inline-grid;
@@ -1740,8 +1771,17 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
1740
1771
  <div class="brand-mark" aria-hidden="true">${FAVICON_SVG}</div>
1741
1772
  <h1 class="brand-title" id="boardTitle">${safeTitle}</h1>
1742
1773
  <span class="sync-pill">
1743
- <span class="sync-dot"></span>
1774
+ <span class="sync-dot" id="syncDot"></span>
1744
1775
  <span id="updatedLine">--:--</span>
1776
+ <span class="sync-sep" aria-hidden="true">·</span>
1777
+ <select class="refresh-select" id="autoRefreshSelect" aria-label="自动刷新间隔" title="自动刷新间隔">
1778
+ <option value="10">10s</option>
1779
+ <option value="15">15s</option>
1780
+ <option value="30" selected>30s</option>
1781
+ <option value="60">1m</option>
1782
+ <option value="300">5m</option>
1783
+ <option value="0">关闭</option>
1784
+ </select>
1745
1785
  <button class="icon-refresh" id="refreshBtn" title="Refresh" aria-label="Refresh">
1746
1786
  <svg width="11" height="11" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1747
1787
  <path d="M13.5 8A5.5 5.5 0 1 1 11.9 4.1M13.5 2.5V5.2H10.8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
@@ -1924,7 +1964,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
1924
1964
 
1925
1965
  <footer class="foot">
1926
1966
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1927
- <span class="mono">agy-family v0.6.4 · MIT</span>
1967
+ <span class="mono">agy-family v0.6.6 · MIT</span>
1928
1968
  </footer>
1929
1969
  </main>
1930
1970
 
@@ -2481,6 +2521,15 @@ function applyI18n() {
2481
2521
  if (tpBtn) tpBtn.textContent = lang === 'zh' ? '查看 / 自定义单价' : 'View / Edit rates';
2482
2522
  const advSum = document.getElementById('advancedRulesSummary');
2483
2523
  if (advSum) advSum.textContent = lang === 'zh' ? '高级设置与群通知(时区 / 预警 / 查看密码 / Webhook)' : 'Advanced & Notifications (Timezone / Warn / View Key / Webhook)';
2524
+ const arSel = document.getElementById('autoRefreshSelect');
2525
+ if (arSel) {
2526
+ arSel.title = lang === 'zh' ? '页面自动刷新间隔' : 'Auto-refresh interval';
2527
+ arSel.setAttribute('aria-label', arSel.title);
2528
+ const offOpt = arSel.querySelector('option[value="0"]');
2529
+ if (offOpt) offOpt.textContent = lang === 'zh' ? '关闭' : 'Off';
2530
+ }
2531
+ const rfBtn = document.getElementById('refreshBtn');
2532
+ if (rfBtn) rfBtn.title = lang === 'zh' ? '立即刷新' : 'Refresh now';
2484
2533
  updateRangeTriggerLabel(lastBoardData?.window || null);
2485
2534
  updateAdminHeaderTitle();
2486
2535
  renderGuideBody();
@@ -2724,6 +2773,7 @@ async function fetchBoard(opts) {
2724
2773
  }
2725
2774
  const isTabOrManual = !silent && hasLoadedBoard;
2726
2775
  hasLoadedBoard = true;
2776
+ lastBoardFetchedAt = Date.now();
2727
2777
  lastBoardData = data;
2728
2778
  renderBoard(data);
2729
2779
  if (isTabOrManual) {
@@ -3182,6 +3232,30 @@ function renderMemberRows(d) {
3182
3232
  const emailHintHtml = m.emailHint
3183
3233
  ? '<span class="mono" style="color:var(--body)">· ' + esc(m.emailHint) + '</span>'
3184
3234
  : '';
3235
+ const mqMem = m.subscriptionQuota || null;
3236
+ let memQuotaTag = '';
3237
+ if (mqMem && mqMem.gemini) {
3238
+ const g5 = mqMem.gemini.fiveHourPct;
3239
+ const gw = mqMem.gemini.weeklyPct;
3240
+ const qBits = [];
3241
+ if (g5 !== null && g5 !== undefined) qBits.push('5h ' + Math.round(Number(g5)) + '%');
3242
+ if (gw !== null && gw !== undefined) qBits.push((lang === 'zh' ? '周 ' : 'wk ') + Math.round(Number(gw)) + '%');
3243
+ if (qBits.length) {
3244
+ const qCls = mqMem.status === 'limited' ? 'ntag-over' : (mqMem.status === 'low' ? 'ntag-warn' : 'ntag-gray');
3245
+ const tipParts = [];
3246
+ if (mqMem.planTier) tipParts.push(mqMem.planTier);
3247
+ if (g5 !== null && g5 !== undefined) tipParts.push('Gemini 5h: ' + g5 + '%');
3248
+ if (gw !== null && gw !== undefined) tipParts.push('Gemini wk: ' + gw + '%');
3249
+ if (mqMem.thirdParty?.fiveHourPct !== null && mqMem.thirdParty?.fiveHourPct !== undefined) {
3250
+ tipParts.push('3P 5h: ' + mqMem.thirdParty.fiveHourPct + '%');
3251
+ }
3252
+ if (mqMem.thirdParty?.weeklyPct !== null && mqMem.thirdParty?.weeklyPct !== undefined) {
3253
+ tipParts.push('3P wk: ' + mqMem.thirdParty.weeklyPct + '%');
3254
+ }
3255
+ if (mqMem.observedAt) tipParts.push(fmtAgo(mqMem.observedAt));
3256
+ memQuotaTag = '<span class="ntag ' + qCls + ' mono" title="' + esc(tipParts.join(' · ')) + '">' + esc(qBits.join(' · ')) + '</span>';
3257
+ }
3258
+ }
3185
3259
  const devMetaBits = [];
3186
3260
  if (m.lastPlatform) devMetaBits.push(m.lastPlatform);
3187
3261
  if (m.lastMaskedIp && m.lastMaskedIp !== 'local') {
@@ -3201,7 +3275,7 @@ function renderMemberRows(d) {
3201
3275
  '<span class="toggle-tri' + (isExpanded ? ' open' : '') + '">' + triSvg + '</span>' +
3202
3276
  '<span class="dot" style="background:' + esc(m.color) + '"></span>' +
3203
3277
  '<div>' +
3204
- '<div class="member-name-row"><span class="member-name">' + esc(m.name) + '</span>' + roleTag + meTag + acctTag + statusTag + integrityTag + '</div>' +
3278
+ '<div class="member-name-row"><span class="member-name">' + esc(m.name) + '</span>' + roleTag + meTag + acctTag + memQuotaTag + statusTag + integrityTag + '</div>' +
3205
3279
  '<div class="member-sub"><span class="live-dot ' + (m.online ? 'on' : 'off') + '"></span><span>' + esc(m.online ? t('online') : t('offline')) + '</span><span>' + esc(fmtAgo(m.lastSeenAt)) + '</span>' + emailHintHtml + devMetaHtml + '</div>' +
3206
3280
  '</div>' +
3207
3281
  '</div></td>' +
@@ -3380,9 +3454,22 @@ function renderBoard(d) {
3380
3454
  if (k4Sub) {
3381
3455
  const subBits = [];
3382
3456
  if (mq.accountLabel) subBits.push(mq.accountLabel);
3457
+ if (mq.syncMode === 'collaborative' && mq.latestContributorName) {
3458
+ subBits.push(
3459
+ lang === 'zh'
3460
+ ? (mq.contributorCount > 1
3461
+ ? '成员 ' + mq.latestContributorName + ' 等 ' + mq.contributorCount + ' 人协同'
3462
+ : '成员 ' + mq.latestContributorName + ' 协同同步')
3463
+ : (mq.contributorCount > 1
3464
+ ? 'Synced by ' + mq.contributorCount + ' members'
3465
+ : 'Synced via ' + mq.latestContributorName),
3466
+ );
3467
+ } else if (mq.syncMode === 'reconciled' && mq.contributorCount > 1) {
3468
+ subBits.push(lang === 'zh' ? mq.contributorCount + ' 人协同校准' : mq.contributorCount + '-way reconciled');
3469
+ }
3383
3470
  if (mq.stale) subBits.push(lang === 'zh' ? '缓存偏旧 · 点击刷新指引' : 'Stale cache');
3384
3471
  else if (g.weeklyResetInMs) subBits.push((lang === 'zh' ? '周重置 ' : 'Wk reset ') + fmtResetCountdown(g.weeklyResetInMs));
3385
- else subBits.push(lang === 'zh' ? '主号实时同步' : 'Synced from master');
3472
+ else if (!mq.syncMode || mq.syncMode === 'master') subBits.push(lang === 'zh' ? '主号实时同步' : 'Synced from master');
3386
3473
  k4Sub.style.color = mq.status === 'limited' ? 'var(--danger)' : (mq.status === 'low' || mq.stale ? 'var(--warn)' : 'var(--muted)');
3387
3474
  k4Sub.textContent = subBits.join(' · ');
3388
3475
  }
@@ -3392,11 +3479,11 @@ function renderBoard(d) {
3392
3479
  k4Meta.textContent = t('bindMasterLink');
3393
3480
  }
3394
3481
  if (k4Body) {
3395
- k4Body.innerHTML = '<div class="kpi-val-row"><div class="kpi-val" style="font-size:18px;color:var(--muted)">' + (lang === 'zh' ? '待绑定主号' : 'Not bound') + '</div></div>';
3482
+ k4Body.innerHTML = '<div class="kpi-val-row"><div class="kpi-val" style="font-size:18px;color:var(--muted)">' + (lang === 'zh' ? '待任意成员同步' : 'Awaiting sync') + '</div></div>';
3396
3483
  }
3397
3484
  if (k4Sub) {
3398
3485
  k4Sub.style.color = 'var(--muted)';
3399
- k4Sub.textContent = lang === 'zh' ? '运行 agy-family master bind 同步余量' : 'Run agy-family master bind to sync';
3486
+ k4Sub.textContent = lang === 'zh' ? '主号或任一已核验成员使用 agy 后自动捕获' : 'Auto-captured when master or any verified member uses agy';
3400
3487
  }
3401
3488
  }
3402
3489
 
@@ -3829,11 +3916,19 @@ async function loadAdmin() {
3829
3916
  '<div class="mq-track" style="height:5px"><div class="mq-fill ' + cls + '" style="width:' + (hasVal ? Math.max(0, Math.min(100, Number(pct))) : 0) + '%"></div></div>' +
3830
3917
  '</div>';
3831
3918
  };
3919
+ const contribNames = Array.isArray(mq.contributors) ? mq.contributors.map((c) => c.name).filter(Boolean) : [];
3920
+ const contribTag =
3921
+ mq.syncMode === 'collaborative' && contribNames.length
3922
+ ? '<span class="ntag ntag-good">' + esc((lang === 'zh' ? '成员协同:' : 'Via members: ') + contribNames.join(' / ')) + '</span>'
3923
+ : mq.syncMode === 'reconciled' && contribNames.length > 1
3924
+ ? '<span class="ntag ntag-good">' + esc((lang === 'zh' ? '多源综合校准:' : 'Reconciled: ') + contribNames.join(' + ')) + '</span>'
3925
+ : '';
3832
3926
  mqView.innerHTML =
3833
3927
  '<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-size:12px;flex-wrap:wrap">' +
3834
- '<div style="display:flex;align-items:center;gap:6px">' +
3928
+ '<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">' +
3835
3929
  (mq.planTier ? '<span class="mq-tier-pill">' + esc(mq.planTier) + '</span>' : '') +
3836
3930
  (mq.accountLabel ? '<span class="mono" style="color:var(--ink);font-weight:500">' + esc(mq.accountLabel) + '</span>' : '') +
3931
+ contribTag +
3837
3932
  '</div>' +
3838
3933
  '<span class="mono" style="font-size:11px;color:' + (mq.stale ? 'var(--warn)' : 'var(--muted)') + '">' +
3839
3934
  esc((mq.source || 'sync') + ' · ' + fmtAgo(mq.observedAt || mq.updatedAt)) +
@@ -4210,7 +4305,61 @@ document.getElementById('checkOfflineBtn').addEventListener('click', async () =>
4210
4305
  });
4211
4306
  });
4212
4307
 
4213
- document.getElementById('refreshBtn')?.addEventListener('click', () => fetchBoard());
4308
+ const ALLOWED_REFRESH_SECS = [0, 10, 15, 30, 60, 300];
4309
+ let autoRefreshSec = (() => {
4310
+ const raw = localStorage.getItem('agf_refresh_sec');
4311
+ if (raw === null || raw === '') return 30;
4312
+ const n = Number(raw);
4313
+ return ALLOWED_REFRESH_SECS.includes(n) ? n : 30;
4314
+ })();
4315
+ let autoRefreshTimer = null;
4316
+ let lastBoardFetchedAt = 0;
4317
+
4318
+ function formatRefreshLabel(sec) {
4319
+ if (!sec) return lang === 'zh' ? '关闭' : 'Off';
4320
+ if (sec < 60) return sec + 's';
4321
+ return Math.round(sec / 60) + 'm';
4322
+ }
4323
+
4324
+ function scheduleAutoRefresh() {
4325
+ if (autoRefreshTimer) {
4326
+ clearInterval(autoRefreshTimer);
4327
+ autoRefreshTimer = null;
4328
+ }
4329
+ const sel = document.getElementById('autoRefreshSelect');
4330
+ if (sel && String(sel.value) !== String(autoRefreshSec)) sel.value = String(autoRefreshSec);
4331
+ const dot = document.getElementById('syncDot');
4332
+ if (dot) dot.classList.toggle('paused', autoRefreshSec <= 0);
4333
+ if (autoRefreshSec > 0) {
4334
+ autoRefreshTimer = setInterval(() => {
4335
+ if (document.hidden) return;
4336
+ fetchBoard({ silent: true });
4337
+ }, autoRefreshSec * 1000);
4338
+ }
4339
+ }
4340
+
4341
+ document.getElementById('autoRefreshSelect')?.addEventListener('change', (ev) => {
4342
+ const n = Number(ev.target.value);
4343
+ autoRefreshSec = ALLOWED_REFRESH_SECS.includes(n) ? n : 30;
4344
+ localStorage.setItem('agf_refresh_sec', String(autoRefreshSec));
4345
+ scheduleAutoRefresh();
4346
+ showToast(
4347
+ autoRefreshSec > 0
4348
+ ? (lang === 'zh' ? '已设为每 ' + formatRefreshLabel(autoRefreshSec) + ' 自动刷新' : 'Auto-refresh set to every ' + formatRefreshLabel(autoRefreshSec))
4349
+ : (lang === 'zh' ? '已关闭自动刷新' : 'Auto-refresh turned off'),
4350
+ );
4351
+ });
4352
+
4353
+ document.addEventListener('visibilitychange', () => {
4354
+ if (!document.hidden && autoRefreshSec > 0 && Date.now() - lastBoardFetchedAt >= autoRefreshSec * 1000) {
4355
+ fetchBoard({ silent: true });
4356
+ }
4357
+ });
4358
+
4359
+ document.getElementById('refreshBtn')?.addEventListener('click', () => {
4360
+ fetchBoard();
4361
+ scheduleAutoRefresh();
4362
+ });
4214
4363
 
4215
4364
  function fmtShortDate(isoKey) {
4216
4365
  const parts = String(isoKey || '').split('-');
@@ -4762,8 +4911,8 @@ document.getElementById('testWebhookBtn').addEventListener('click', async () =>
4762
4911
  });
4763
4912
 
4764
4913
  applyI18n();
4914
+ scheduleAutoRefresh();
4765
4915
  fetchBoard();
4766
- setInterval(() => fetchBoard({ silent: true }), 60000);
4767
4916
  </script>
4768
4917
  </body>
4769
4918
  </html>`;