agy-bar 0.9.1 → 0.9.3

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.
@@ -0,0 +1,291 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { configDir } from './config.mjs';
6
+ import { writeFileAtomic } from './fs-atomic.mjs';
7
+
8
+ // Go / protobuf zero timestamp ("1970-01-01T00:00:00Z") indicates an unused window, not an expired one.
9
+ export const EPOCH_SENTINEL_MS = 86_400_000;
10
+ export const RESET_TOLERANCE_MS = 5_000;
11
+ export const MAX_CACHE_AGE_MS = 6 * 60 * 60 * 1000;
12
+ const FRACTION_EPSILON = 1e-6;
13
+
14
+ const WEEKLY_SIBLING_BUCKET = Object.freeze({
15
+ 'gemini-5h': 'gemini-weekly',
16
+ '3p-5h': '3p-weekly',
17
+ });
18
+
19
+ function nonNeg(value) {
20
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
21
+ }
22
+
23
+ function readFraction(bucket) {
24
+ if (!bucket || typeof bucket !== 'object') return null;
25
+ const f = nonNeg(bucket.remaining_fraction ?? bucket.remaining);
26
+ return f !== null ? Math.min(1, f) : null;
27
+ }
28
+
29
+ export function quotaCachePath(baseDir = configDir(homedir())) {
30
+ return join(baseDir, 'quota-cache.json');
31
+ }
32
+
33
+ export function parseRealResetTs(bucket) {
34
+ if (!bucket || typeof bucket !== 'object' || typeof bucket.reset_time !== 'string') return null;
35
+ const ts = Date.parse(bucket.reset_time);
36
+ return Number.isFinite(ts) && ts > EPOCH_SENTINEL_MS ? ts : null;
37
+ }
38
+
39
+ export function isEpochSentinelReset(bucket) {
40
+ if (!bucket || typeof bucket !== 'object' || typeof bucket.reset_time !== 'string') return false;
41
+ const ts = Date.parse(bucket.reset_time);
42
+ return Number.isFinite(ts) && ts <= EPOCH_SENTINEL_MS;
43
+ }
44
+
45
+ export function isBucketResetDue(bucket, now = Date.now()) {
46
+ if (!bucket || typeof bucket !== 'object' || bucket.disabled === true) return false;
47
+ if (isEpochSentinelReset(bucket)) return false;
48
+ const resetTs = parseRealResetTs(bucket);
49
+ if (resetTs !== null) return resetTs <= now;
50
+ const resetSec = nonNeg(bucket.reset_in_seconds);
51
+ return resetSec !== null && resetSec <= 0;
52
+ }
53
+
54
+ export function isWeeklyBucketBlocking(bucketId, quotaMap, now = Date.now()) {
55
+ const weeklyId = WEEKLY_SIBLING_BUCKET[bucketId];
56
+ if (!weeklyId || !quotaMap || typeof quotaMap !== 'object') return false;
57
+ const weekly = quotaMap[weeklyId];
58
+ if (!weekly || typeof weekly !== 'object' || weekly.disabled === true) return false;
59
+ const weeklyFrac = readFraction(weekly);
60
+ if (weeklyFrac === null || weeklyFrac > 0.005) return false;
61
+ return !isBucketResetDue(weekly, now);
62
+ }
63
+
64
+ export function extractAccountKey(payload) {
65
+ const raw =
66
+ payload?.email ||
67
+ payload?.account?.email ||
68
+ payload?.user_email ||
69
+ payload?.account?.id ||
70
+ payload?.account_id ||
71
+ payload?.user_id ||
72
+ '';
73
+ const cleaned = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
74
+ if (!cleaned) return 'default';
75
+ return createHash('sha1').update(cleaned).digest('hex').slice(0, 12);
76
+ }
77
+
78
+ export function normalizeQuotaBucket(raw, observedAt = Date.now()) {
79
+ if (!raw || typeof raw !== 'object' || raw.disabled === true) return null;
80
+ const remaining_fraction = readFraction(raw);
81
+ const remaining_amount = nonNeg(raw.remaining_amount);
82
+ if (remaining_fraction === null && remaining_amount === null) return null;
83
+
84
+ const reset_time = typeof raw.reset_time === 'string' && raw.reset_time.trim() ? raw.reset_time.trim() : null;
85
+ const reset_ts = parseRealResetTs({ reset_time });
86
+ const reset_in_seconds = nonNeg(raw.reset_in_seconds);
87
+ const obs = nonNeg(raw.observedAt) ?? observedAt;
88
+
89
+ return {
90
+ remaining_fraction,
91
+ remaining_amount,
92
+ reset_time,
93
+ reset_ts,
94
+ reset_in_seconds,
95
+ observedAt: obs,
96
+ };
97
+ }
98
+
99
+ export function pickFresherBucket(incoming, cached, now = Date.now()) {
100
+ if (!incoming && !cached) return { bucket: null, source: 'none', changedCache: false };
101
+ if (!incoming) return { bucket: cached, source: 'cached', changedCache: false };
102
+ if (!cached) return { bucket: incoming, source: 'incoming', changedCache: true };
103
+
104
+ if (now - cached.observedAt > MAX_CACHE_AGE_MS) {
105
+ return { bucket: incoming, source: 'incoming', changedCache: true };
106
+ }
107
+
108
+ const inTs = incoming.reset_ts;
109
+ const caTs = cached.reset_ts;
110
+
111
+ // Case 1 & 2: Both buckets carry real reset timestamps.
112
+ if (inTs !== null && caTs !== null) {
113
+ if (caTs > inTs + RESET_TOLERANCE_MS) {
114
+ return { bucket: cached, source: 'cached', changedCache: false };
115
+ }
116
+ if (inTs > caTs + RESET_TOLERANCE_MS) {
117
+ return { bucket: incoming, source: 'incoming', changedCache: true };
118
+ }
119
+
120
+ // Same window: remaining quota is monotonically non-increasing until reset_time changes.
121
+ if (incoming.remaining_fraction !== null && cached.remaining_fraction !== null) {
122
+ if (cached.remaining_fraction < incoming.remaining_fraction - FRACTION_EPSILON) {
123
+ return { bucket: cached, source: 'cached', changedCache: false };
124
+ }
125
+ if (incoming.remaining_fraction < cached.remaining_fraction - FRACTION_EPSILON) {
126
+ return { bucket: incoming, source: 'incoming', changedCache: true };
127
+ }
128
+ return { bucket: incoming, source: 'incoming', changedCache: false };
129
+ }
130
+
131
+ if (incoming.remaining_amount !== null && cached.remaining_amount !== null) {
132
+ if (cached.remaining_amount < incoming.remaining_amount) {
133
+ return { bucket: cached, source: 'cached', changedCache: false };
134
+ }
135
+ if (incoming.remaining_amount < cached.remaining_amount) {
136
+ return { bucket: incoming, source: 'incoming', changedCache: true };
137
+ }
138
+ return { bucket: incoming, source: 'incoming', changedCache: false };
139
+ }
140
+
141
+ return { bucket: incoming, source: 'incoming', changedCache: false };
142
+ }
143
+
144
+ // Case 3a: Incoming is an unused/sentinel bucket (e.g. 100%, 1970-01-01) while cache has a real window.
145
+ if (inTs === null && caTs !== null) {
146
+ const inFull = incoming.remaining_fraction !== null && incoming.remaining_fraction >= 0.999;
147
+ if (caTs > now && inFull && (cached.remaining_fraction === null || cached.remaining_fraction < 0.999)) {
148
+ return { bucket: cached, source: 'cached', changedCache: false };
149
+ }
150
+ if (caTs <= now && inFull) {
151
+ return { bucket: incoming, source: 'incoming', changedCache: true };
152
+ }
153
+ return { bucket: incoming, source: 'incoming', changedCache: false };
154
+ }
155
+
156
+ // Case 3b: Incoming has a real window while cache is an unused/sentinel bucket.
157
+ if (inTs !== null && caTs === null) {
158
+ if (inTs > now) {
159
+ return { bucket: incoming, source: 'incoming', changedCache: true };
160
+ }
161
+ const caFull = cached.remaining_fraction !== null && cached.remaining_fraction >= 0.999;
162
+ if (caFull && cached.observedAt > inTs) {
163
+ return { bucket: cached, source: 'cached', changedCache: false };
164
+ }
165
+ return { bucket: incoming, source: 'incoming', changedCache: false };
166
+ }
167
+
168
+ // Case 4: Neither has a real reset_time (e.g. synthetic fixtures with only reset_in_seconds).
169
+ return { bucket: incoming, source: 'incoming', changedCache: false };
170
+ }
171
+
172
+ function materializeBucket(baseRaw, winner, now) {
173
+ const out = baseRaw && typeof baseRaw === 'object' ? { ...baseRaw } : {};
174
+ if (winner.remaining_fraction !== null) {
175
+ out.remaining_fraction = winner.remaining_fraction;
176
+ } else {
177
+ delete out.remaining_fraction;
178
+ }
179
+ if (winner.remaining_amount !== null) {
180
+ out.remaining_amount = winner.remaining_amount;
181
+ } else {
182
+ delete out.remaining_amount;
183
+ }
184
+ if (winner.reset_time !== null) {
185
+ out.reset_time = winner.reset_time;
186
+ } else {
187
+ delete out.reset_time;
188
+ }
189
+ if (winner.reset_ts !== null) {
190
+ out.reset_in_seconds = Math.max(0, Math.round((winner.reset_ts - now) / 1000));
191
+ } else if (winner.reset_in_seconds !== null) {
192
+ out.reset_in_seconds = winner.reset_in_seconds;
193
+ } else {
194
+ delete out.reset_in_seconds;
195
+ }
196
+ return out;
197
+ }
198
+
199
+ export function readSharedQuota({ baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {}) {
200
+ const filePath = quotaCachePath(baseDir);
201
+ if (!existsSync(filePath)) return null;
202
+ try {
203
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
204
+ if (!parsed || typeof parsed !== 'object' || !parsed.buckets || typeof parsed.buckets !== 'object') return null;
205
+ const cachedAccount = typeof parsed.accountKey === 'string' ? parsed.accountKey : 'default';
206
+ if (accountKey !== 'default' && cachedAccount !== 'default' && cachedAccount !== accountKey) {
207
+ return null;
208
+ }
209
+ const buckets = {};
210
+ for (const [id, raw] of Object.entries(parsed.buckets)) {
211
+ const norm = normalizeQuotaBucket(raw, nonNeg(parsed.updatedAt) ?? now);
212
+ if (norm && now - norm.observedAt <= MAX_CACHE_AGE_MS) {
213
+ buckets[id] = norm;
214
+ }
215
+ }
216
+ return {
217
+ accountKey: cachedAccount,
218
+ updatedAt: nonNeg(parsed.updatedAt) ?? now,
219
+ buckets,
220
+ };
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ export function mergeQuotaSnapshots(snapshots = [], now = Date.now()) {
227
+ const merged = {};
228
+ for (const item of snapshots) {
229
+ if (!item || typeof item !== 'object') continue;
230
+ const isWrapped = Object.hasOwn(item, 'quota');
231
+ const snap = isWrapped ? item.quota : item;
232
+ const obs = isWrapped ? nonNeg(item.observedAt) ?? now : now;
233
+ if (!snap || typeof snap !== 'object') continue;
234
+ for (const [id, raw] of Object.entries(snap)) {
235
+ const incoming = normalizeQuotaBucket(raw, obs);
236
+ if (!incoming) continue;
237
+ const existing = merged[id] || null;
238
+ const { bucket } = pickFresherBucket(incoming, existing, now);
239
+ if (bucket) merged[id] = bucket;
240
+ }
241
+ }
242
+ return Object.keys(merged).length > 0 ? merged : null;
243
+ }
244
+
245
+ export function syncSharedQuota(
246
+ rawQuota,
247
+ { baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {},
248
+ ) {
249
+ if (!rawQuota || typeof rawQuota !== 'object') return rawQuota;
250
+
251
+ const existingCache = readSharedQuota({ baseDir, now, accountKey });
252
+ const nextCacheBuckets = existingCache ? { ...existingCache.buckets } : {};
253
+ const mergedQuota = { ...rawQuota };
254
+
255
+ let anyAdopted = false;
256
+ let cacheDirty = !existingCache;
257
+
258
+ for (const [id, rawBucket] of Object.entries(rawQuota)) {
259
+ if (!rawBucket || typeof rawBucket !== 'object' || rawBucket.disabled === true) continue;
260
+ const incoming = normalizeQuotaBucket(rawBucket, now);
261
+ if (!incoming) continue;
262
+
263
+ const cached = nextCacheBuckets[id] || null;
264
+ const { bucket: winner, source, changedCache } = pickFresherBucket(incoming, cached, now);
265
+ if (!winner) continue;
266
+
267
+ if (source === 'cached') {
268
+ mergedQuota[id] = materializeBucket(rawBucket, winner, now);
269
+ anyAdopted = true;
270
+ } else if (changedCache) {
271
+ nextCacheBuckets[id] = winner;
272
+ cacheDirty = true;
273
+ }
274
+ }
275
+
276
+ if (cacheDirty && Object.keys(nextCacheBuckets).length > 0) {
277
+ try {
278
+ const payload = {
279
+ version: 1,
280
+ accountKey: accountKey !== 'default' ? accountKey : existingCache?.accountKey || 'default',
281
+ updatedAt: now,
282
+ buckets: nextCacheBuckets,
283
+ };
284
+ writeFileAtomic(quotaCachePath(baseDir), JSON.stringify(payload) + '\n');
285
+ } catch {
286
+ // Never fail statusline rendering due to disk issues.
287
+ }
288
+ }
289
+
290
+ return anyAdopted ? mergedQuota : rawQuota;
291
+ }
package/src/render.mjs CHANGED
@@ -3,6 +3,7 @@ import { classifyAgentActivity, countRunningSubagents } from './agent-state.mjs'
3
3
  import { bold, clipAnsi, detectColorDepth, fg, sanitizeText, visibleWidth } from './ansi.mjs';
4
4
  import { BAR_STYLES, DEFAULT_CONFIG, normalizeConfig } from './config.mjs';
5
5
  import { formatUsd } from './pricing.mjs';
6
+ import { isBucketResetDue, isEpochSentinelReset, isWeeklyBucketBlocking } from './quota-sync.mjs';
6
7
  import { resolvePalette } from './themes.mjs';
7
8
 
8
9
  export { countRunningSubagents };
@@ -48,6 +49,7 @@ function formatCompactUsd(amount) {
48
49
 
49
50
  export function formatReset(bucket, now = Date.now()) {
50
51
  if (!bucket || typeof bucket !== 'object') return '';
52
+ if (isEpochSentinelReset(bucket)) return '';
51
53
  const ts = typeof bucket.reset_time === 'string' ? Date.parse(bucket.reset_time) : NaN;
52
54
  const seconds = Number.isFinite(ts) ? (ts - now) / 1000 : nonNegNumber(bucket.reset_in_seconds);
53
55
  if (seconds === null) return '';
@@ -664,15 +666,19 @@ function buildSessionSegment(opts, config, palette, color, telemetry) {
664
666
  return fg(parts.join('·'), palette.muted, color);
665
667
  }
666
668
 
667
- function buildQuotaSegment(entries, opts, config, palette, color, now) {
669
+ function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota = null) {
668
670
  if (!entries.length) return '';
669
671
  const { show, barStyle, barWidth, quotaWarn, quotaDanger } = config;
670
- const parts = entries.map(({ label, bucket }) => {
672
+ const quotaMap = rawQuota && typeof rawQuota === 'object' ? rawQuota : Object.fromEntries(entries.map((e) => [e.id, e.bucket]));
673
+ const parts = entries.map(({ id, label, bucket }) => {
671
674
  const fraction = nonNegNumber(bucket.remaining_fraction);
672
675
  const amount = nonNegNumber(bucket.remaining_amount);
673
676
  const pct = fraction !== null ? Math.round(fraction * 100) : null;
674
677
  const valText = pct !== null ? `${pct}%` : amount !== null ? formatTokens(amount) : '--';
675
- const tone =
678
+ const due = isBucketResetDue(bucket, now);
679
+ const blockedByWeekly = due && isWeeklyBucketBlocking(id, quotaMap, now);
680
+ const resetReady = due && !blockedByWeekly;
681
+ const baseTone =
676
682
  pct === null
677
683
  ? palette.muted
678
684
  : pct <= quotaDanger
@@ -680,6 +686,7 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
680
686
  : pct <= quotaWarn
681
687
  ? palette.warn
682
688
  : palette.good;
689
+ const tone = resetReady && pct !== null && pct <= quotaDanger ? palette.warn : baseTone;
683
690
 
684
691
  const pieces = [fg(label, palette.muted, color)];
685
692
  if (opts.withQuotaBar && show.quotaBar && fraction !== null) {
@@ -695,8 +702,12 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
695
702
  }
696
703
  pieces.push(pct !== null && pct <= quotaWarn ? bold(fg(valText, tone, color), color) : fg(valText, palette.text, color));
697
704
  if (opts.withReset && show.reset) {
698
- const reset = formatReset(bucket, now);
699
- if (reset) pieces.push(fg(`(${reset})`, palette.muted, color));
705
+ if (resetReady) {
706
+ pieces.push(fg('(ready)', palette.good, color));
707
+ } else {
708
+ const reset = formatReset(bucket, now);
709
+ if (reset) pieces.push(fg(`(${reset})`, palette.muted, color));
710
+ }
700
711
  }
701
712
  return pieces.join(' ');
702
713
  });
@@ -759,7 +770,7 @@ function renderMetricsRow(
759
770
  if (sessionSeg) leftParts.push(sessionSeg);
760
771
 
761
772
  const left = joinWithSep(leftParts, stage.tight ? ' ' : sep, palette, color);
762
- const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now);
773
+ const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now, payload?.quota);
763
774
  const minGap = left && right ? 2 : 0;
764
775
  chosenLeft = left;
765
776
  chosenRight = right;
@@ -6,10 +6,12 @@ import { loadConfig } from './config.mjs';
6
6
  import { readGitInfo } from './git.mjs';
7
7
  import { getOrRefreshUsageSummary } from './history-scan.mjs';
8
8
  import { maybeTriggerBackgroundPricingSync } from './pricing-sync.mjs';
9
+ import { extractAccountKey, syncSharedQuota } from './quota-sync.mjs';
9
10
  import { renderFallback, renderStatusline } from './render.mjs';
10
11
  import { readLatestStepTiming } from './step-timing.mjs';
11
12
  import { syncTabTitle } from './tab-title.mjs';
12
- import { maybeCaptureRedactedPayload, peekSessionState, recordTelemetry, updateSessionTabTitle } from './telemetry.mjs';
13
+ import { deriveSessionId, maybeCaptureRedactedPayload, peekSessionState, recordTelemetry, resolveSessionTitles } from './telemetry.mjs';
14
+ import { isNativeTitleActive } from './title.mjs';
13
15
 
14
16
  const GIT_DIRTY_CACHE_MS = 3000;
15
17
 
@@ -27,8 +29,12 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
27
29
  const payload = JSON.parse(raw);
28
30
  const now = Date.now();
29
31
  maybeCaptureRedactedPayload(payload);
30
- const prevSession = peekSessionState(payload);
31
- const cwd = payload?.workspace?.current_dir || payload?.cwd || null;
32
+ const syncedQuota = payload?.quota
33
+ ? syncSharedQuota(payload.quota, { now, accountKey: extractAccountKey(payload) })
34
+ : null;
35
+ const effectivePayload = syncedQuota && syncedQuota !== payload.quota ? { ...payload, quota: syncedQuota } : payload;
36
+ const prevSession = peekSessionState(effectivePayload);
37
+ const cwd = effectivePayload?.workspace?.current_dir || effectivePayload?.cwd || null;
32
38
  const wantGitStatus = Boolean(config.show.gitDirty || config.show.gitDiff);
33
39
  const canReuseGitStatus = Boolean(
34
40
  wantGitStatus &&
@@ -50,19 +56,41 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
50
56
  : null,
51
57
  })
52
58
  : null;
59
+
60
+ // Sync terminal tab title synchronously before async DB scans when AGY's native
61
+ // `settings.json.title` hook is not already driving this session's title.
62
+ let tabSync = null;
63
+ if (!plain && config.tabTitle) {
64
+ const sessionIdForTitle = deriveSessionId(effectivePayload);
65
+ if (!isNativeTitleActive(sessionIdForTitle, { now, hostPid: process.ppid })) {
66
+ const { customTitle } = resolveSessionTitles(effectivePayload, prevSession);
67
+ tabSync = syncTabTitle(effectivePayload, {
68
+ config,
69
+ git,
70
+ customTitle,
71
+ prevTabTitle: prevSession?.lastTabTitle || null,
72
+ prevTabHostPid: prevSession?.lastTabHostPid ?? null,
73
+ prevTabTty: prevSession?.lastTabTty || null,
74
+ hostPidHint: process.ppid,
75
+ resolveOpts: { env },
76
+ });
77
+ }
78
+ }
79
+
53
80
  const stepTiming = config.dbTiming
54
- ? await readLatestStepTiming(payload, { prevDbStamp: prevSession?.dbStamp ?? null })
81
+ ? await readLatestStepTiming(effectivePayload, { prevDbStamp: prevSession?.dbStamp ?? null })
55
82
  : null;
56
- const telemetry = recordTelemetry(payload, {
83
+ const telemetry = recordTelemetry(effectivePayload, {
57
84
  now,
58
85
  git,
59
86
  stepTiming,
60
87
  prevSession,
88
+ tabSync,
61
89
  cacheTtlSec: config.cacheTtlSec,
62
90
  enableLedger: config.ledger,
63
91
  });
64
92
 
65
- const activity = classifyAgentActivity(payload);
93
+ const activity = classifyAgentActivity(effectivePayload);
66
94
  let usageSummary = null;
67
95
  if (
68
96
  config.show.todayTokens ||
@@ -82,33 +110,18 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
82
110
  });
83
111
  }
84
112
 
85
- const nativeCostUsd = extractNativeCostUsd(payload);
113
+ const nativeCostUsd = extractNativeCostUsd(effectivePayload);
86
114
  const effectiveSessionCostUsd = Math.max(telemetry.sessionCostUsd || 0, usageSummary?.sessionCostUsd || 0, nativeCostUsd || 0);
87
115
  const effectiveTelemetry =
88
116
  effectiveSessionCostUsd !== telemetry.sessionCostUsd
89
117
  ? { ...telemetry, sessionCostUsd: effectiveSessionCostUsd }
90
118
  : telemetry;
91
119
 
92
- if (!plain && config.tabTitle) {
93
- const tab = syncTabTitle(payload, {
94
- config,
95
- git,
96
- customTitle: telemetry.customTitle,
97
- prevTabTitle: telemetry.prevTabTitle,
98
- prevTabHostPid: telemetry.prevTabHostPid,
99
- hostPidHint: process.ppid,
100
- resolveOpts: { env },
101
- });
102
- if (tab.changed && tab.title) {
103
- updateSessionTabTitle(telemetry.sessionId, tab.title, { hostPid: tab.hostPid });
104
- }
105
- }
106
-
107
120
  if (config.pricingAutoSync) {
108
121
  maybeTriggerBackgroundPricingSync({ enabled: true, now, env });
109
122
  }
110
123
 
111
- const rendered = renderStatusline(payload, {
124
+ const rendered = renderStatusline(effectivePayload, {
112
125
  config,
113
126
  now,
114
127
  color,
package/src/tab-title.mjs CHANGED
@@ -5,6 +5,7 @@ import { classifyAgentActivity } from './agent-state.mjs';
5
5
  import { clipPlain, sanitizeText, visibleWidth } from './ansi.mjs';
6
6
 
7
7
  const VALID_TTY_RE = /^(?:tty[a-z0-9]+|pts\/\d+)$/i;
8
+ const VALID_DEV_TTY_RE = /^\/dev\/(?:tty[a-z0-9]+|pts\/\d+)$/i;
8
9
 
9
10
  const FILLER_PREFIXES = [
10
11
  /^(?:请|麻烦|能不能|可以|能否)?(?:帮我|给我|帮忙)/,
@@ -85,7 +86,7 @@ function defaultReadProc(pid) {
85
86
  try {
86
87
  const out = execFileSync('ps', ['-o', 'ppid=,tty=,comm=', '-p', String(pid)], {
87
88
  encoding: 'utf8',
88
- timeout: 120,
89
+ timeout: 500,
89
90
  stdio: ['ignore', 'pipe', 'ignore'],
90
91
  }).trim();
91
92
  if (!out) return null;
@@ -153,25 +154,53 @@ export function resolveTerminalTty(opts = {}) {
153
154
  return resolveTerminalTarget(opts).tty;
154
155
  }
155
156
 
156
- export function writeOscTitle(title, { ttyPath = null, writer = null, resolveOpts = {} } = {}) {
157
+ export function writeOscTitle(title, { ttyPath = null, writer = null, resolveOpts = {}, writeToTty = null } = {}) {
157
158
  const seq = formatOscTitle(title);
158
- if (!seq) return { written: false, tty: null, hostPid: null, sequence: '' };
159
+ if (!seq) return { written: false, tty: null, hostPid: null, sequence: '', error: 'empty_title' };
159
160
 
160
161
  if (typeof writer === 'function') {
161
162
  writer(seq);
162
- return { written: true, tty: ttyPath || 'custom', hostPid: null, sequence: seq };
163
+ return { written: true, tty: ttyPath || 'custom', hostPid: null, sequence: seq, error: null };
163
164
  }
164
165
 
165
166
  const resolved = ttyPath ? { tty: ttyPath, hostPid: null } : resolveTerminalTarget(resolveOpts);
166
- if (!resolved.tty) return { written: false, tty: null, hostPid: null, sequence: seq };
167
+ if (!resolved.tty) return { written: false, tty: null, hostPid: null, sequence: seq, error: 'no_tty' };
168
+
169
+ if (typeof writeToTty === 'function') {
170
+ try {
171
+ const ok = writeToTty(resolved.tty, seq);
172
+ return {
173
+ written: ok !== false,
174
+ tty: resolved.tty,
175
+ hostPid: resolved.hostPid,
176
+ sequence: seq,
177
+ error: ok === false ? 'write_failed' : null,
178
+ };
179
+ } catch (err) {
180
+ return {
181
+ written: false,
182
+ tty: resolved.tty,
183
+ hostPid: resolved.hostPid,
184
+ sequence: seq,
185
+ error: err?.code || err?.message || 'write_failed',
186
+ };
187
+ }
188
+ }
167
189
 
168
190
  let fd = null;
169
191
  try {
170
- fd = openSync(resolved.tty, 'w');
192
+ const flags = (constants.O_WRONLY ?? 1) | (constants.O_NOCTTY ?? 0);
193
+ fd = openSync(resolved.tty, flags);
171
194
  writeSync(fd, seq);
172
- return { written: true, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq };
173
- } catch {
174
- return { written: false, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq };
195
+ return { written: true, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq, error: null };
196
+ } catch (err) {
197
+ return {
198
+ written: false,
199
+ tty: resolved.tty,
200
+ hostPid: resolved.hostPid,
201
+ sequence: seq,
202
+ error: err?.code || err?.message || 'write_failed',
203
+ };
175
204
  } finally {
176
205
  if (fd !== null) {
177
206
  try {
@@ -191,33 +220,51 @@ export function syncTabTitle(
191
220
  customTitle = null,
192
221
  prevTabTitle = null,
193
222
  prevTabHostPid = null,
223
+ prevTabTty = null,
194
224
  hostPidHint = null,
195
225
  force = false,
196
226
  ttyPath = null,
197
227
  writer = null,
228
+ writeToTty = null,
198
229
  resolveOpts = {},
199
230
  } = {},
200
231
  ) {
201
232
  if (config.tabTitle === false) {
202
- return { changed: false, written: false, title: null, tty: null, hostPid: null };
233
+ return { changed: false, written: false, title: null, tty: null, hostPid: null, error: null };
203
234
  }
204
235
 
205
236
  const title = buildTabTitle(payload, { config, git, customTitle });
206
237
  if (!title) {
207
- return { changed: false, written: false, title: null, tty: null, hostPid: null };
238
+ return { changed: false, written: false, title: null, tty: null, hostPid: null, error: null };
208
239
  }
209
240
 
210
- // Fast path: skip spawning `ps` when neither title nor host agy PID changed.
241
+ const sameHostHint =
242
+ prevTabHostPid !== null && typeof hostPidHint === 'number' && hostPidHint === prevTabHostPid;
243
+
244
+ // Fast path 1: skip spawning `ps` when neither title nor host agy PID changed.
245
+ if (!force && !writer && !ttyPath && title === prevTabTitle && sameHostHint) {
246
+ return { changed: false, written: false, title, tty: prevTabTty || null, hostPid: prevTabHostPid, error: null };
247
+ }
248
+
249
+ // Fast path 2: on title/state change under the same agy host PID, write directly to cached TTY (zero `ps` spawns).
211
250
  if (
212
- !force &&
213
251
  !writer &&
214
252
  !ttyPath &&
215
- title === prevTabTitle &&
216
- prevTabHostPid !== null &&
217
- typeof hostPidHint === 'number' &&
218
- hostPidHint === prevTabHostPid
253
+ sameHostHint &&
254
+ typeof prevTabTty === 'string' &&
255
+ VALID_DEV_TTY_RE.test(prevTabTty)
219
256
  ) {
220
- return { changed: false, written: false, title, tty: null, hostPid: prevTabHostPid };
257
+ const fastWrite = writeOscTitle(title, { ttyPath: prevTabTty, writeToTty });
258
+ if (fastWrite.written) {
259
+ return {
260
+ changed: true,
261
+ written: true,
262
+ title,
263
+ tty: prevTabTty,
264
+ hostPid: prevTabHostPid,
265
+ error: null,
266
+ };
267
+ }
221
268
  }
222
269
 
223
270
  const resolved = !writer && !ttyPath ? resolveTerminalTarget(resolveOpts) : { tty: ttyPath, hostPid: null };
@@ -225,9 +272,16 @@ export function syncTabTitle(
225
272
  const hostUnknownBefore = resolved.hostPid !== null && prevTabHostPid === null;
226
273
 
227
274
  if (!force && title === prevTabTitle && !hostChanged && !hostUnknownBefore) {
228
- return { changed: false, written: false, title, tty: resolved.tty, hostPid: resolved.hostPid };
275
+ return { changed: false, written: false, title, tty: resolved.tty, hostPid: resolved.hostPid, error: null };
229
276
  }
230
277
 
231
- const result = writeOscTitle(title, { ttyPath: resolved.tty, writer, resolveOpts });
232
- return { changed: true, written: result.written, title, tty: result.tty, hostPid: resolved.hostPid };
278
+ const result = writeOscTitle(title, { ttyPath: resolved.tty, writer, writeToTty, resolveOpts });
279
+ return {
280
+ changed: true,
281
+ written: result.written,
282
+ title,
283
+ tty: result.tty,
284
+ hostPid: resolved.hostPid ?? (sameHostHint ? prevTabHostPid : null),
285
+ error: result.error || null,
286
+ };
233
287
  }