cdpm-mcp 0.0.0-stage → 0.1.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/CHANGELOG.md +33 -0
- package/LICENSE +21 -0
- package/README.ko.md +245 -0
- package/README.md +167 -2
- package/dist/agent-setup.js +134 -0
- package/dist/auto-setup.js +110 -0
- package/dist/cdp/client.js +127 -0
- package/dist/cdp/downloads.js +69 -0
- package/dist/cdp/network.js +118 -0
- package/dist/cdp/sessions.js +519 -0
- package/dist/cdp/targets.js +43 -0
- package/dist/chrome/finder.js +87 -0
- package/dist/chrome/launcher.js +52 -0
- package/dist/chrome/proxy.js +109 -0
- package/dist/claude-md-setup.js +68 -0
- package/dist/cli.js +230 -0
- package/dist/errors.js +3 -0
- package/dist/index.js +26 -0
- package/dist/install.js +34 -0
- package/dist/page/actions.js +1101 -0
- package/dist/page/keys.js +115 -0
- package/dist/page/snapshot.js +283 -0
- package/dist/paths.js +43 -0
- package/dist/pause.js +74 -0
- package/dist/proxy-forwarder.js +191 -0
- package/dist/registry/lock.js +93 -0
- package/dist/registry/messages.js +106 -0
- package/dist/registry/store.js +27 -0
- package/dist/service.js +340 -0
- package/dist/slots.js +72 -0
- package/dist/statusline-setup.js +142 -0
- package/dist/statusline.js +82 -0
- package/dist/taskbar/dock.js +94 -0
- package/dist/taskbar/icon-gdi.js +191 -0
- package/dist/taskbar/icon.js +300 -0
- package/dist/taskbar/watcher.js +65 -0
- package/dist/taskbar/win32.js +135 -0
- package/dist/tools/format.js +48 -0
- package/dist/tools/read.js +81 -0
- package/dist/tools/register.js +907 -0
- package/dist/util.js +111 -0
- package/dist/version.js +3 -0
- package/package.json +62 -4
package/dist/service.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// 슬롯 실행 보장, 탭 목록과 기록부 맞추기, 행동 기록.
|
|
2
|
+
import { launchChrome } from './chrome/launcher.js';
|
|
3
|
+
import { describeProxy } from './chrome/proxy.js';
|
|
4
|
+
import { browserConnection, dropSlotConnections, hasLiveBrowserConnection, pageSession } from './cdp/sessions.js';
|
|
5
|
+
import { listPages, probe } from './cdp/targets.js';
|
|
6
|
+
import { CdpmError } from './errors.js';
|
|
7
|
+
import { newSlotRecord, readRegistry, updateRegistry } from './registry/store.js';
|
|
8
|
+
import { MAX_SLOT, portOf } from './slots.js';
|
|
9
|
+
import { applyDock, DOCK_SUPPORTED } from './taskbar/dock.js';
|
|
10
|
+
import { applyTaskbar } from './taskbar/watcher.js';
|
|
11
|
+
import { ago, josa, nowIso, pidAlive, secondsSince, sleep } from './util.js';
|
|
12
|
+
export const EXTERNAL = '(외부)';
|
|
13
|
+
/** 이 프로세스가 직접 만든 탭 → 만든 에이전트. 기록부에 처음 올릴 때 openedBy로 쓴다. */
|
|
14
|
+
const createdBy = new Map();
|
|
15
|
+
const createdAt = new Map();
|
|
16
|
+
export function markCreated(targetId, agent) {
|
|
17
|
+
createdBy.set(targetId, agent);
|
|
18
|
+
createdAt.set(targetId, Date.now());
|
|
19
|
+
// 기록부에 올리기 전에 닫힌 탭은 지워지지 않으므로, 10분 넘은 것은 정리한다
|
|
20
|
+
if (createdAt.size > 100) {
|
|
21
|
+
const cutoff = Date.now() - 10 * 60_000;
|
|
22
|
+
for (const [id, at] of createdAt)
|
|
23
|
+
if (at < cutoff) {
|
|
24
|
+
createdAt.delete(id);
|
|
25
|
+
createdBy.delete(id);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export const notRunningMessage = (slot) => `${slot}번 Chrome은 꺼져 있어요. CDPM은 사용자가 켜 달라고 할 때만 Chrome을 켭니다. ` +
|
|
30
|
+
`사용자에게 켤지 물어보고, 켜라고 하면 browser_launch를 쓰세요.`;
|
|
31
|
+
/** 떠 있는 슬롯에 붙는다 (기록·작업표시줄 맞춤). 꺼져 있으면 켜지 않고 오류. */
|
|
32
|
+
/** 포트 확인. 늦게 답하면(바쁜 Chrome) 길게 한 번 더 묻는다. */
|
|
33
|
+
async function probeSure(slot) {
|
|
34
|
+
let p = await probe(slot);
|
|
35
|
+
if (p.state === 'slow')
|
|
36
|
+
p = await probe(slot, 8000);
|
|
37
|
+
if (p.state === 'slow') {
|
|
38
|
+
throw new CdpmError(`${slot}번 포트(${portOf(slot)})가 8초 넘게 응답하지 않아요. Chrome이 매우 바쁘거나 멈췄을 수 있어요. 잠시 뒤 다시 시도하세요.`);
|
|
39
|
+
}
|
|
40
|
+
return p;
|
|
41
|
+
}
|
|
42
|
+
export async function attachSlot(slot) {
|
|
43
|
+
// 빠른 길: 이 프로세스의 연결이 살아 있고 기록된 Chrome도 살아 있으면 포트에 다시 묻지 않는다.
|
|
44
|
+
const known = readRegistry().slots[String(slot)];
|
|
45
|
+
if (known?.pid && pidAlive(known.pid) && hasLiveBrowserConnection(slot))
|
|
46
|
+
return;
|
|
47
|
+
const p = await probeSure(slot);
|
|
48
|
+
if (p.state === 'other')
|
|
49
|
+
throw portBusy(slot, p.detail);
|
|
50
|
+
if (p.state === 'free') {
|
|
51
|
+
await forgetSlot(slot);
|
|
52
|
+
throw new CdpmError(notRunningMessage(slot));
|
|
53
|
+
}
|
|
54
|
+
const rec = readRegistry().slots[String(slot)];
|
|
55
|
+
let pid = rec?.pid;
|
|
56
|
+
if (!pid || !pidAlive(pid)) {
|
|
57
|
+
// 기록이 없거나 기록된 Chrome이 이미 죽었으면, 포트에 응답하는 Chrome이 이 PC의 프로세스인지 확인한다.
|
|
58
|
+
// SSH 터널(ssh -L 9222:...)처럼 다른 PC의 Chrome이 이 포트로 보이는 경우 그 PID는 이 PC에 없다.
|
|
59
|
+
pid = await browserPid(slot);
|
|
60
|
+
if (!pid || !pidAlive(pid)) {
|
|
61
|
+
await forgetSlot(slot);
|
|
62
|
+
throw new CdpmError(`${slot}번 포트(${portOf(slot)})에 이 PC가 아닌 Chrome이 연결돼 있어요 (SSH 터널 등). 그 연결을 닫거나 다른 슬롯을 쓰세요.`);
|
|
63
|
+
}
|
|
64
|
+
await updateRegistry((r) => {
|
|
65
|
+
const s = (r.slots[String(slot)] ??= newSlotRecord(EXTERNAL, nowIso()));
|
|
66
|
+
s.pid = pid;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
applyTaskbar(slot, pid);
|
|
70
|
+
if (DOCK_SUPPORTED && !rec?.headless)
|
|
71
|
+
void applyDock(slot, pid); // macOS만
|
|
72
|
+
}
|
|
73
|
+
function portBusy(slot, detail) {
|
|
74
|
+
return new CdpmError(`${slot}번 슬롯의 포트 ${portOf(slot)}를 Chrome이 아닌 프로그램이 사용 중입니다 (${detail}). 그 프로그램을 종료하거나 다른 슬롯을 쓰세요.`);
|
|
75
|
+
}
|
|
76
|
+
/** 사용자가 켜라고 했을 때만 부른다. 이미 떠 있으면 붙기만 한다. */
|
|
77
|
+
export async function launchSlot(slot, agent, opts = {}) {
|
|
78
|
+
const p = await probeSure(slot);
|
|
79
|
+
if (p.state === 'other')
|
|
80
|
+
throw portBusy(slot, p.detail);
|
|
81
|
+
if (p.state === 'chrome') {
|
|
82
|
+
await attachSlot(slot);
|
|
83
|
+
return { launched: false };
|
|
84
|
+
}
|
|
85
|
+
// 방금 끈 Chrome은 포트를 닫은 뒤에도 잠깐 살아서 프로필을 붙잡고 있다. 그때 새로 켜면 새 Chrome이
|
|
86
|
+
// 꺼지는 중인 옛 Chrome에 넘어가 버리므로, 기록된 프로세스가 끝날 때까지(최대 5초) 기다린다.
|
|
87
|
+
const old = readRegistry().slots[String(slot)]?.pid;
|
|
88
|
+
for (let i = 0; old && i < 50 && pidAlive(old); i++)
|
|
89
|
+
await sleep(100);
|
|
90
|
+
await forgetSlot(slot); // 남아 있던 죽은 기록 정리
|
|
91
|
+
const launched = await launchChrome(slot, opts);
|
|
92
|
+
const pid = launched.pid ?? (await browserPid(slot));
|
|
93
|
+
const pages = await listPages(slot).catch(() => []);
|
|
94
|
+
for (const page of pages)
|
|
95
|
+
markCreated(page.id, agent);
|
|
96
|
+
// macOS만: Dock 아이콘을 슬롯 아이콘으로 (첫 빈 탭이 있을 때 그림을 그려 저장해 둔다)
|
|
97
|
+
if (DOCK_SUPPORTED && !opts.headless)
|
|
98
|
+
await applyDock(slot, pid);
|
|
99
|
+
await updateRegistry((r) => {
|
|
100
|
+
r.slots[String(slot)] = { ...newSlotRecord(agent, nowIso(), pid), ...(opts.headless ? { headless: true } : {}), ...(opts.proxy ? { proxy: describeProxy(opts.proxy) } : {}) };
|
|
101
|
+
});
|
|
102
|
+
// 처음 열린 탭을 지금(이 프로세스 안에서) 기록해야 "연 사람"이 실행한 에이전트로 남는다.
|
|
103
|
+
await syncTabs(slot).catch(() => undefined);
|
|
104
|
+
// 창이 뜨는 데 시간이 걸리므로 창이 나타날 때까지 적용을 시도 (창이 나타나는 것이 신호; 이후는 watcher가 맡음).
|
|
105
|
+
// 헤드리스는 창이 없으니 기다리지 않는다.
|
|
106
|
+
for (let i = 0; !opts.headless && i < 50; i++) {
|
|
107
|
+
if (applyTaskbar(slot, pid) > 0)
|
|
108
|
+
break;
|
|
109
|
+
await sleep(100);
|
|
110
|
+
}
|
|
111
|
+
return { launched: true };
|
|
112
|
+
}
|
|
113
|
+
/** 포트가 비어 있는(Chrome도 다른 프로그램도 없는) 슬롯을 작은 번호부터 n개. 모자라면 있는 만큼. */
|
|
114
|
+
export async function freeSlots(n) {
|
|
115
|
+
const states = await Promise.all(Array.from({ length: MAX_SLOT }, (_, i) => probe(i + 1, 2000)));
|
|
116
|
+
return states.flatMap((s, i) => (s.state === 'free' ? [i + 1] : [])).slice(0, n);
|
|
117
|
+
}
|
|
118
|
+
/** 포트가 비어 있는 가장 작은 슬롯. 없으면 undefined. */
|
|
119
|
+
export async function firstFreeSlot() {
|
|
120
|
+
return (await freeSlots(1))[0];
|
|
121
|
+
}
|
|
122
|
+
async function browserPid(slot) {
|
|
123
|
+
try {
|
|
124
|
+
const conn = await browserConnection(slot);
|
|
125
|
+
const info = await conn.send('SystemInfo.getProcessInfo', {}, 5000);
|
|
126
|
+
return info.processInfo.find((x) => x.type === 'browser')?.id;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Chrome의 실제 탭 목록과 기록부를 맞추고, 처음 본 순서대로 돌려준다. */
|
|
133
|
+
export async function syncTabs(slot) {
|
|
134
|
+
const pages = await listPages(slot);
|
|
135
|
+
const live = new Set(pages.map((p) => p.id));
|
|
136
|
+
// 바뀐 게 없으면 기록부를 쓰지 않는다 (여러 에이전트가 동시에 쓸 때 잠금 경쟁을 줄임).
|
|
137
|
+
let slotRec = readRegistry().slots[String(slot)];
|
|
138
|
+
// 처음 보는 탭은 Chrome에게 '누가 열었는지(openerId)'를 물어 둔다 (시간으로 추측하지 않음).
|
|
139
|
+
const openers = new Map();
|
|
140
|
+
const unseen = pages.filter((p) => !slotRec?.tabs[p.id] && !createdBy.has(p.id));
|
|
141
|
+
if (unseen.length) {
|
|
142
|
+
const browser = await browserConnection(slot).catch(() => undefined);
|
|
143
|
+
await Promise.all(unseen.map(async (p) => {
|
|
144
|
+
const info = await browser?.send('Target.getTargetInfo', { targetId: p.id }, 10_000).catch(() => undefined);
|
|
145
|
+
openers.set(p.id, info?.targetInfo.openerId);
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
const deadBlocks = (t) => (t.blocks ?? []).some((b) => !pidAlive(b.pid));
|
|
149
|
+
const changed = !slotRec || pages.some((p) => !slotRec.tabs[p.id]) || Object.keys(slotRec.tabs).some((id) => !live.has(id))
|
|
150
|
+
|| Object.values(slotRec.tabs).some(deadBlocks);
|
|
151
|
+
if (changed) {
|
|
152
|
+
slotRec = await updateRegistry((r) => {
|
|
153
|
+
const s = (r.slots[String(slot)] ??= newSlotRecord(EXTERNAL, nowIso()));
|
|
154
|
+
for (const id of Object.keys(s.tabs))
|
|
155
|
+
if (!live.has(id))
|
|
156
|
+
delete s.tabs[id];
|
|
157
|
+
// 규칙을 건 세션(프로세스)이 끝났으면 Chrome에서도 이미 풀린 규칙이다.
|
|
158
|
+
for (const t of Object.values(s.tabs)) {
|
|
159
|
+
if (!t.blocks)
|
|
160
|
+
continue;
|
|
161
|
+
t.blocks = t.blocks.filter((b) => pidAlive(b.pid));
|
|
162
|
+
if (!t.blocks.length)
|
|
163
|
+
delete t.blocks;
|
|
164
|
+
}
|
|
165
|
+
for (const p of pages) {
|
|
166
|
+
if (s.tabs[p.id])
|
|
167
|
+
continue;
|
|
168
|
+
let openedBy = createdBy.get(p.id);
|
|
169
|
+
const opener = openers.get(p.id);
|
|
170
|
+
if (!openedBy && opener) {
|
|
171
|
+
const by = s.tabs[opener]?.last?.agent;
|
|
172
|
+
openedBy = by ? `${by} (페이지가 염)` : `${s.tabs[opener]?.id ?? '다른 탭'}에서 페이지가 염`;
|
|
173
|
+
}
|
|
174
|
+
const seq = s.nextTabSeq++;
|
|
175
|
+
s.tabs[p.id] = { id: `t${seq}`, seq, seenAt: nowIso(), openedBy: openedBy ?? EXTERNAL };
|
|
176
|
+
createdBy.delete(p.id);
|
|
177
|
+
}
|
|
178
|
+
return s;
|
|
179
|
+
}).catch(() => readRegistry().slots[String(slot)] ?? newSlotRecord(EXTERNAL, nowIso()));
|
|
180
|
+
}
|
|
181
|
+
// 앞에 있는 탭: 각 탭의 실제 보임 상태로 판단한다 (/json/list 순서는 탭을 바꿔도 갱신되지 않음).
|
|
182
|
+
const visible = await Promise.all(pages.map(async (p) => {
|
|
183
|
+
try {
|
|
184
|
+
const session = await pageSession(slot, p.id, p.webSocketDebuggerUrl);
|
|
185
|
+
return (await session.visibilityForList()) === 'visible';
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}));
|
|
191
|
+
const rec = slotRec;
|
|
192
|
+
return pages
|
|
193
|
+
.map((p, i) => ({ p, visible: visible[i], rec: rec.tabs[p.id] ?? { id: '?', seq: Number.MAX_SAFE_INTEGER, seenAt: nowIso(), openedBy: EXTERNAL } }))
|
|
194
|
+
.sort((a, b) => a.rec.seq - b.rec.seq)
|
|
195
|
+
.map(({ p, visible: v, rec: r }, i) => ({ no: i + 1, targetId: p.id, id: r.id, title: p.title, url: p.url, active: v, rec: r }));
|
|
196
|
+
}
|
|
197
|
+
/** 탭 선택 규칙. 정할 수 없으면 이유. */
|
|
198
|
+
export function pickTab(tabs, tabArg, kind, preferred) {
|
|
199
|
+
if (tabArg !== undefined && tabArg !== '') {
|
|
200
|
+
const s = String(tabArg).trim();
|
|
201
|
+
const byId = /^t\d+$/i.test(s) ? tabs.find((t) => t.id.toLowerCase() === s.toLowerCase()) : undefined;
|
|
202
|
+
const byNo = /^\d+$/.test(s) ? tabs.find((t) => t.no === Number(s)) : undefined;
|
|
203
|
+
const found = byId ?? byNo;
|
|
204
|
+
if (found)
|
|
205
|
+
return { tab: found };
|
|
206
|
+
const list = tabs.map((t) => `${t.no}번 [${t.id}]`).join(', ');
|
|
207
|
+
return { error: `없는 탭이에요: "${s}". 지금 있는 탭: ${list || '없음'}` };
|
|
208
|
+
}
|
|
209
|
+
if (tabs.length === 1)
|
|
210
|
+
return { tab: tabs[0] };
|
|
211
|
+
if (tabs.length === 0)
|
|
212
|
+
return { error: '열린 탭이 없어요.' };
|
|
213
|
+
// 이 에이전트가 마지막으로 쓴(또는 새로 연) 탭이 있으면 보기·조작 모두 그 탭
|
|
214
|
+
const mine = tabs.find((t) => t.targetId === preferred);
|
|
215
|
+
if (mine)
|
|
216
|
+
return { tab: mine };
|
|
217
|
+
// 보기 도구: 앞에 보이는 탭 → 첫 탭. 조작 도구: 쓴 적 있는 탭이 없으면 지정을 요구한다.
|
|
218
|
+
if (kind === 'view')
|
|
219
|
+
return { tab: tabs.find((t) => t.active) ?? tabs[0] };
|
|
220
|
+
return { error: `탭이 ${tabs.length}개 있고 이 에이전트가 아직 쓴 탭이 없어요. 어느 탭에서 실행할지 tab에 번호나 ID(예: "${tabs[0].id}")를 지정하세요.` };
|
|
221
|
+
}
|
|
222
|
+
/** 다른 에이전트가 최근(2분 안)에 조작한 탭을 조작할 때 붙일 경고 (막지는 않음). */
|
|
223
|
+
export function ownershipWarnings(tab, agent) {
|
|
224
|
+
const last = tab.rec.last;
|
|
225
|
+
if (!last || last.agent === agent || secondsSince(last.at) > 120)
|
|
226
|
+
return [];
|
|
227
|
+
const when = ago(last.at);
|
|
228
|
+
return [`이 탭 [${tab.id}]은 ${josa(last.agent, '이', '가')} ${when === '방금' ? when : `${when}에`} ${last.action}했어요. 같이 쓰는 중이면 slot_send로 알려 주세요.`];
|
|
229
|
+
}
|
|
230
|
+
/** 행동 기록. 기록부 잠금에 실패해도 도구 동작은 성공으로 두고 false를 돌려준다. */
|
|
231
|
+
export async function recordAction(slot, targetId, agent, action, summary, anon = false, title) {
|
|
232
|
+
try {
|
|
233
|
+
await updateRegistry((r) => {
|
|
234
|
+
const s = r.slots[String(slot)];
|
|
235
|
+
if (!s)
|
|
236
|
+
return;
|
|
237
|
+
const at = nowIso();
|
|
238
|
+
s.last = { agent, action, at, ...(anon ? { anon: true } : {}) };
|
|
239
|
+
if (targetId)
|
|
240
|
+
s.lastTarget = targetId;
|
|
241
|
+
if (title !== undefined)
|
|
242
|
+
s.title = title;
|
|
243
|
+
const t = s.tabs[targetId];
|
|
244
|
+
if (t)
|
|
245
|
+
t.last = { agent, action, at };
|
|
246
|
+
if (summary?.trim()) {
|
|
247
|
+
const stamp = { agent, text: summary.trim(), at };
|
|
248
|
+
s.summary = stamp;
|
|
249
|
+
if (t)
|
|
250
|
+
t.summary = stamp;
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
export async function forgetSlot(slot) {
|
|
260
|
+
dropSlotConnections(slot);
|
|
261
|
+
await updateRegistry((r) => {
|
|
262
|
+
delete r.slots[String(slot)];
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* 사용자가 슬롯 Chrome의 창을 직접 모두 닫았는데 프로세스가 남은 경우 그 슬롯을 끝낸다 (Windows·Linux).
|
|
267
|
+
* 탭(페이지)이 하나도 없는 상태가 2번 연속(2초 간격) 보이면 Browser.close로 정상 종료하고 기록을 지운다.
|
|
268
|
+
* 켠 지 10초가 안 된 슬롯은 건너뛴다 (첫 탭이 생기기 전일 수 있음).
|
|
269
|
+
* macOS는 하지 않는다: 맥에서는 창을 닫아도 앱이 살아 있는 게 원래 동작이라, 슬롯은 Cmd+Q(앱 종료)로만 끝난다.
|
|
270
|
+
*/
|
|
271
|
+
const emptySeen = new Map();
|
|
272
|
+
let slotWatcher;
|
|
273
|
+
export async function checkClosedWindows() {
|
|
274
|
+
const closed = [];
|
|
275
|
+
if (process.platform === 'darwin')
|
|
276
|
+
return closed;
|
|
277
|
+
const reg = readRegistry();
|
|
278
|
+
await Promise.all(Object.entries(reg.slots).map(async ([key, rec]) => {
|
|
279
|
+
const slot = Number(key);
|
|
280
|
+
if (!pidAlive(rec.pid) || secondsSince(rec.launchedAt) < 10)
|
|
281
|
+
return;
|
|
282
|
+
let pages;
|
|
283
|
+
try {
|
|
284
|
+
pages = await listPages(slot, 2000);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return; // 응답이 없으면 판단하지 않는다 (바쁘거나 이미 꺼지는 중)
|
|
288
|
+
}
|
|
289
|
+
if (pages.length) {
|
|
290
|
+
emptySeen.delete(slot);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const n = (emptySeen.get(slot) ?? 0) + 1;
|
|
294
|
+
emptySeen.set(slot, n);
|
|
295
|
+
if (n < 2)
|
|
296
|
+
return;
|
|
297
|
+
emptySeen.delete(slot);
|
|
298
|
+
const browser = await browserConnection(slot).catch(() => undefined);
|
|
299
|
+
await browser?.send('Browser.close', {}, 5000).catch(() => undefined);
|
|
300
|
+
await forgetSlot(slot).catch(() => undefined);
|
|
301
|
+
closed.push(slot);
|
|
302
|
+
}));
|
|
303
|
+
return closed;
|
|
304
|
+
}
|
|
305
|
+
export function startSlotWatcher(intervalMs = 2000) {
|
|
306
|
+
if (slotWatcher)
|
|
307
|
+
return;
|
|
308
|
+
let busy = false;
|
|
309
|
+
slotWatcher = setInterval(() => {
|
|
310
|
+
if (busy)
|
|
311
|
+
return;
|
|
312
|
+
busy = true;
|
|
313
|
+
checkClosedWindows().catch(() => undefined).finally(() => (busy = false));
|
|
314
|
+
}, intervalMs);
|
|
315
|
+
slotWatcher.unref();
|
|
316
|
+
}
|
|
317
|
+
/** 1~30번 중 실제로 Chrome이 떠 있는 슬롯 (CDPM 밖에서 띄운 것 포함). 기록부의 죽은 슬롯은 정리한다. */
|
|
318
|
+
export async function liveSlots() {
|
|
319
|
+
const reg = readRegistry();
|
|
320
|
+
const out = [];
|
|
321
|
+
const dead = [];
|
|
322
|
+
await Promise.all(Array.from({ length: MAX_SLOT }, (_, i) => i + 1).map(async (slot) => {
|
|
323
|
+
const rec = reg.slots[String(slot)];
|
|
324
|
+
// 기록이 있는 슬롯은 넉넉히 기다린다 (바쁜 Chrome을 꺼진 것으로 오해해 기록을 지우지 않게)
|
|
325
|
+
const p = await probe(slot, rec ? 5000 : 800);
|
|
326
|
+
if (p.state === 'chrome' || (p.state === 'slow' && rec))
|
|
327
|
+
out.push([slot, rec ?? newSlotRecord(EXTERNAL, nowIso())]);
|
|
328
|
+
else if (rec && p.state === 'free')
|
|
329
|
+
dead.push(slot);
|
|
330
|
+
}));
|
|
331
|
+
if (dead.length) {
|
|
332
|
+
for (const slot of dead)
|
|
333
|
+
dropSlotConnections(slot);
|
|
334
|
+
await updateRegistry((r) => {
|
|
335
|
+
for (const slot of dead)
|
|
336
|
+
delete r.slots[String(slot)];
|
|
337
|
+
}).catch(() => undefined);
|
|
338
|
+
}
|
|
339
|
+
return out.sort((a, b) => a[0] - b[0]);
|
|
340
|
+
}
|
package/dist/slots.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// 슬롯 1~30 ↔ CDP 포트 변환과 슬롯별 고정 색.
|
|
2
|
+
import { CdpmError } from './errors.js';
|
|
3
|
+
export const MIN_SLOT = 1;
|
|
4
|
+
export const MAX_SLOT = 30;
|
|
5
|
+
/**
|
|
6
|
+
* 슬롯 N의 포트 = PORT_BASE + N (기본 1번=14050 … 30번=14079).
|
|
7
|
+
* 다른 도구가 흔히 쓰는 9222를 피하려고 잘 안 쓰는 구간을 쓴다. 그 구간을 다른 프로그램이 쓰면 CDPM_PORT_BASE로 옮긴다.
|
|
8
|
+
* 통합 테스트는 CDPM_TEST_PORT_BASE로 실제 슬롯과 부딪히지 않게 한다.
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_PORT_BASE = 14049;
|
|
11
|
+
export const PORT_BASE = portBaseFrom(process.env.CDPM_TEST_PORT_BASE || process.env.CDPM_PORT_BASE);
|
|
12
|
+
export function portBaseFrom(value) {
|
|
13
|
+
const n = Number(value);
|
|
14
|
+
// 예약 포트(1023 이하)와 65535를 넘는 값은 받지 않는다
|
|
15
|
+
return Number.isInteger(n) && n >= 1023 && n + MAX_SLOT <= 65535 ? n : DEFAULT_PORT_BASE;
|
|
16
|
+
}
|
|
17
|
+
export function portOf(slot) {
|
|
18
|
+
assertSlot(slot);
|
|
19
|
+
return PORT_BASE + slot;
|
|
20
|
+
}
|
|
21
|
+
export function isValidSlot(slot) {
|
|
22
|
+
return typeof slot === 'number' && Number.isInteger(slot) && slot >= MIN_SLOT && slot <= MAX_SLOT;
|
|
23
|
+
}
|
|
24
|
+
export function assertSlot(slot) {
|
|
25
|
+
if (!isValidSlot(slot)) {
|
|
26
|
+
throw new CdpmError(`슬롯은 ${MIN_SLOT}~${MAX_SLOT}번입니다. (받은 값: ${String(slot)})`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 슬롯 N은 항상 N번째 색을 쓴다. 모두 흰 글씨 대비 4.5:1 이상.
|
|
31
|
+
* 1–10: 서로 가장 잘 구분되는 기본색, 11–30: 진한 톤 변형.
|
|
32
|
+
*/
|
|
33
|
+
export const SLOT_COLORS = [
|
|
34
|
+
'#2563EB', // 1 파랑
|
|
35
|
+
'#C2410C', // 2 주황
|
|
36
|
+
'#15803D', // 3 초록
|
|
37
|
+
'#DC2626', // 4 빨강
|
|
38
|
+
'#9333EA', // 5 보라
|
|
39
|
+
'#0E7490', // 6 청록
|
|
40
|
+
'#BE185D', // 7 분홍
|
|
41
|
+
'#B45309', // 8 호박
|
|
42
|
+
'#0F766E', // 9 틸
|
|
43
|
+
'#4338CA', // 10 남색
|
|
44
|
+
'#BE123C', // 11 장미
|
|
45
|
+
'#3F6212', // 12 라임
|
|
46
|
+
'#0369A1', // 13 하늘
|
|
47
|
+
'#A21CAF', // 14 자홍
|
|
48
|
+
'#047857', // 15 에메랄드
|
|
49
|
+
'#6D28D9', // 16 바이올렛
|
|
50
|
+
'#854D0E', // 17 겨자
|
|
51
|
+
'#1E40AF', // 18 진파랑
|
|
52
|
+
'#9A3412', // 19 진주황
|
|
53
|
+
'#166534', // 20 진초록
|
|
54
|
+
'#991B1B', // 21 진빨강
|
|
55
|
+
'#6B21A8', // 22 진보라
|
|
56
|
+
'#155E75', // 23 진청록
|
|
57
|
+
'#9D174D', // 24 진분홍
|
|
58
|
+
'#115E59', // 25 진틸
|
|
59
|
+
'#312E81', // 26 진남색
|
|
60
|
+
'#475569', // 27 슬레이트
|
|
61
|
+
'#57534E', // 28 스톤
|
|
62
|
+
'#92400E', // 29 진호박
|
|
63
|
+
'#0C4A6E', // 30 진하늘
|
|
64
|
+
];
|
|
65
|
+
export function colorOf(slot) {
|
|
66
|
+
assertSlot(slot);
|
|
67
|
+
return SLOT_COLORS[slot - 1];
|
|
68
|
+
}
|
|
69
|
+
export function hexToRgb(hex) {
|
|
70
|
+
const n = parseInt(hex.slice(1), 16);
|
|
71
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
72
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Claude Code 상태줄에 CDPM 슬롯 표시를 켠다. MCP 설치만으로는 상태줄이 바뀌지 않으므로,
|
|
2
|
+
// 사용자가 원할 때 이 기능으로 설정 파일에 한 줄을 넣는다. 바꾸기 전 원래 파일은 백업해 둔다.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { stableNodePath } from './paths.js';
|
|
8
|
+
export function defaultSetupPaths() {
|
|
9
|
+
const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
|
|
10
|
+
return {
|
|
11
|
+
claudeSettings: path.join(claudeDir, 'settings.json'),
|
|
12
|
+
ccstatusline: path.join(os.homedir(), '.config', 'ccstatusline', 'settings.json'),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** 상태줄이 부를 명령: 지금 이 cdpm의 node와 cli.js를 그대로 쓴다. */
|
|
16
|
+
export function statuslineCommand() {
|
|
17
|
+
const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
|
|
18
|
+
return `"${stableNodePath()}" "${cli}" statusline`;
|
|
19
|
+
}
|
|
20
|
+
// JSON 파일 안에서는 따옴표가 \" 로 저장되므로 앞의 역슬래시도 허용한다
|
|
21
|
+
/** 상태줄을 다시 그리는 주기(초). 슬롯을 켜고 끄는 것은 대화와 상관없이 일어나므로 주기적으로 갱신해야 실시간으로 보인다. */
|
|
22
|
+
const REFRESH_SECONDS = 3;
|
|
23
|
+
const MARK = /(?:cli\.js|cdpm)\\?["']?\s+statusline(?!-)/;
|
|
24
|
+
function readJson(file) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function readText(file) {
|
|
33
|
+
try {
|
|
34
|
+
return fs.readFileSync(file, 'utf8');
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** 처음 바꿀 때만 원래 파일을 <파일>.before-cdpm 으로 남긴다. */
|
|
41
|
+
function backup(file) {
|
|
42
|
+
if (!fs.existsSync(file))
|
|
43
|
+
return undefined;
|
|
44
|
+
const to = `${file}.before-cdpm`;
|
|
45
|
+
if (!fs.existsSync(to))
|
|
46
|
+
fs.copyFileSync(file, to);
|
|
47
|
+
return to;
|
|
48
|
+
}
|
|
49
|
+
function writeJson(file, data) {
|
|
50
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
51
|
+
const tmp = `${file}.cdpm-tmp`;
|
|
52
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
|
|
53
|
+
fs.renameSync(tmp, file);
|
|
54
|
+
}
|
|
55
|
+
/** 상태줄에 CDPM 표시가 이미 들어가 있는지. */
|
|
56
|
+
export function isStatuslineConfigured(p = defaultSetupPaths()) {
|
|
57
|
+
const claude = readJson(p.claudeSettings);
|
|
58
|
+
const cmd = claude?.statusLine?.command ?? '';
|
|
59
|
+
if (MARK.test(cmd))
|
|
60
|
+
return true;
|
|
61
|
+
return /ccstatusline/i.test(cmd) && MARK.test(readText(p.ccstatusline));
|
|
62
|
+
}
|
|
63
|
+
export function setupStatusline(p = defaultSetupPaths(), command = statuslineCommand()) {
|
|
64
|
+
if (isStatuslineConfigured(p)) {
|
|
65
|
+
// 이미 켜져 있어도 다시 그리는 주기가 없거나 3초보다 길면 3초로 (예전 버전으로 켠 경우: 대화가 없으면 상태줄이 옛 화면에 머묾)
|
|
66
|
+
const current = readJson(p.claudeSettings);
|
|
67
|
+
if (current?.statusLine && !(current.statusLine.refreshInterval <= REFRESH_SECONDS)) {
|
|
68
|
+
backup(p.claudeSettings);
|
|
69
|
+
writeJson(p.claudeSettings, { ...current, statusLine: { ...current.statusLine, refreshInterval: REFRESH_SECONDS } });
|
|
70
|
+
return { state: 'already', message: `상태줄은 이미 켜져 있었고, ${REFRESH_SECONDS}초마다 다시 그리도록 설정을 더했어요 (새 세션부터).` };
|
|
71
|
+
}
|
|
72
|
+
return { state: 'already', message: '상태줄에 CDPM 슬롯 표시가 이미 켜져 있어요.' };
|
|
73
|
+
}
|
|
74
|
+
const claude = readJson(p.claudeSettings);
|
|
75
|
+
if (fs.existsSync(p.claudeSettings) && !claude) {
|
|
76
|
+
return { state: 'other', message: `${p.claudeSettings} 파일을 읽지 못해서(JSON 형식 오류) 건드리지 않았어요.` };
|
|
77
|
+
}
|
|
78
|
+
const current = claude?.statusLine?.command ?? '';
|
|
79
|
+
// 상태줄이 없으면: Claude 설정에 CDPM 상태줄을 넣는다.
|
|
80
|
+
if (!current) {
|
|
81
|
+
const saved = backup(p.claudeSettings);
|
|
82
|
+
writeJson(p.claudeSettings, { ...(claude ?? {}), statusLine: { type: 'command', command, padding: 0, refreshInterval: REFRESH_SECONDS } });
|
|
83
|
+
return {
|
|
84
|
+
state: 'claude',
|
|
85
|
+
message: `Claude Code 상태줄에 CDPM 슬롯 표시를 켰어요 (${p.claudeSettings}).` +
|
|
86
|
+
(saved ? ` 원래 설정은 ${saved}에 백업했어요.` : '') + ' 새 세션부터 보여요.',
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// ccstatusline을 쓰고 있으면: 내용이 있는 마지막 줄 다음 줄에 위젯을 넣는다 (3줄을 다 쓰고 있으면 마지막 줄 끝에).
|
|
90
|
+
if (/ccstatusline/i.test(current)) {
|
|
91
|
+
const cc = readJson(p.ccstatusline);
|
|
92
|
+
if (cc && Array.isArray(cc.lines)) {
|
|
93
|
+
const saved = backup(p.ccstatusline);
|
|
94
|
+
const widget = { id: 'cdpm', type: 'custom-command', commandPath: command, preserveColors: true, timeout: 2000 };
|
|
95
|
+
const lines = cc.lines.map((l) => (Array.isArray(l) ? l : []));
|
|
96
|
+
const used = lines.reduce((n, l, i) => (l.length ? i + 1 : n), 0); // 마지막으로 내용이 있는 줄 다음
|
|
97
|
+
if (used < 3) {
|
|
98
|
+
while (lines.length <= used)
|
|
99
|
+
lines.push([]);
|
|
100
|
+
lines[used] = [widget];
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
lines[used - 1].push({ id: 'cdpm-sep', type: 'separator' }, widget);
|
|
104
|
+
}
|
|
105
|
+
writeJson(p.ccstatusline, { ...cc, lines });
|
|
106
|
+
// 슬롯 상태가 대화 없이도 바뀌므로, 상태줄이 3초마다 다시 그려지게 한다 (이미 3초 이하면 그대로)
|
|
107
|
+
if (claude?.statusLine && !(claude.statusLine.refreshInterval <= REFRESH_SECONDS)) {
|
|
108
|
+
backup(p.claudeSettings);
|
|
109
|
+
writeJson(p.claudeSettings, { ...claude, statusLine: { ...claude.statusLine, refreshInterval: REFRESH_SECONDS } });
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
state: 'ccstatusline',
|
|
113
|
+
message: `ccstatusline에 CDPM 슬롯 표시 위젯을 추가했어요 (${p.ccstatusline}).` +
|
|
114
|
+
(saved ? ` 원래 설정은 ${saved}에 백업했어요.` : ''),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// 다른 상태줄 프로그램을 쓰고 있으면 덮어쓰지 않는다.
|
|
119
|
+
return {
|
|
120
|
+
state: 'other',
|
|
121
|
+
message: '이미 다른 상태줄을 쓰고 있어서 바꾸지 않았어요. 그 상태줄에서 아래 명령의 출력을 한 줄 덧붙이면 돼요:\n' + command,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** CDPM이 넣은 상태줄 설정을 뺀다 (ccstatusline 위젯, 또는 CDPM만 쓰는 Claude 상태줄). */
|
|
125
|
+
export function removeStatusline(p = defaultSetupPaths()) {
|
|
126
|
+
const out = [];
|
|
127
|
+
const cc = readJson(p.ccstatusline);
|
|
128
|
+
if (cc && Array.isArray(cc.lines)) {
|
|
129
|
+
const lines = cc.lines.map((l) => (Array.isArray(l) ? l.filter((w) => w?.id !== 'cdpm' && w?.id !== 'cdpm-sep' && !MARK.test(String(w?.commandPath ?? ''))) : l));
|
|
130
|
+
if (JSON.stringify(lines) !== JSON.stringify(cc.lines)) {
|
|
131
|
+
writeJson(p.ccstatusline, { ...cc, lines });
|
|
132
|
+
out.push(`ccstatusline에서 CDPM 위젯을 뺐어요 (${p.ccstatusline}).`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const claude = readJson(p.claudeSettings);
|
|
136
|
+
if (claude?.statusLine && MARK.test(String(claude.statusLine.command ?? ''))) {
|
|
137
|
+
const { statusLine: _, ...rest } = claude;
|
|
138
|
+
writeJson(p.claudeSettings, rest);
|
|
139
|
+
out.push(`Claude 상태줄에서 CDPM을 뺐어요 (${p.claudeSettings}).`);
|
|
140
|
+
}
|
|
141
|
+
return out.length ? out.join('\n') : '상태줄에 CDPM 설정이 없어요.';
|
|
142
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Claude Code 상태줄용 한 줄. 네트워크를 쓰지 않고 기록부와 PID만 본다 (빠르게 끝나야 하므로).
|
|
2
|
+
import { readRegistry } from './registry/store.js';
|
|
3
|
+
import { colorOf, hexToRgb, isValidSlot } from './slots.js';
|
|
4
|
+
import { listPages } from './cdp/targets.js';
|
|
5
|
+
import { displayWidth, pidAlive, shortUrl, truncate } from './util.js';
|
|
6
|
+
const paint = (slot, text) => {
|
|
7
|
+
const [r, g, b] = hexToRgb(colorOf(slot));
|
|
8
|
+
return `\x1b[1;38;2;${r};${g};${b}m${text}\x1b[0m`;
|
|
9
|
+
};
|
|
10
|
+
/** 폭을 모를 때 가정하는 터미널 폭 */
|
|
11
|
+
export const DEFAULT_WIDTH = 120;
|
|
12
|
+
/** 제목 길이를 이 순서로 줄여 가며 한 줄에 맞춘다 */
|
|
13
|
+
const TITLE_STEPS = [20, 16, 12, 8, 5];
|
|
14
|
+
/**
|
|
15
|
+
* "CDPM 1 NAVER 2 Daum 3": 슬롯 번호(슬롯 색), 번호 순서. 슬롯마다 마지막으로 조작한 탭의 페이지 제목.
|
|
16
|
+
* 터미널 폭(width)에 맞춘다: 넘치면 제목을 점점 짧게 → 그래도 넘치면 번호만 → 그래도 넘치면 앞에서부터 들어가는 만큼 + "+N".
|
|
17
|
+
* 하나도 없으면 흐린 "CDPM -".
|
|
18
|
+
*/
|
|
19
|
+
export function formatStatusline(entries, color = true, width = DEFAULT_WIDTH) {
|
|
20
|
+
// 켜진 슬롯이 없으면 줄이 비어 보이지 않게 흐린 회색으로 "CDPM -"
|
|
21
|
+
if (!entries.length)
|
|
22
|
+
return color ? '[90mCDPM -[0m' : 'CDPM -';
|
|
23
|
+
const sorted = [...entries].sort(([a], [b]) => a - b);
|
|
24
|
+
const room = Math.max(20, width - 2); // 끝에 여유 2칸
|
|
25
|
+
// 멈춘 슬롯은 번호를 슬롯 색 대신 흐린 회색으로 (글자는 늘리지 않아 폭이 그대로)
|
|
26
|
+
const mark = (slot, rec) => (!color ? String(slot) : rec?.paused ? '[90m' + slot + '[0m' : paint(slot, String(slot)));
|
|
27
|
+
// 폭은 색 코드를 뺀 실제 글자로 잰다
|
|
28
|
+
const num = (slot, _rec) => String(slot);
|
|
29
|
+
const plain = (titleMax) => 'CDPM ' + sorted.map(([slot, rec]) => (titleMax && rec.title ? `${num(slot, rec)} ${truncate(rec.title, titleMax)}` : num(slot, rec))).join(' ');
|
|
30
|
+
const build = (titleMax) => 'CDPM ' + sorted.map(([slot, rec]) => (titleMax && rec.title ? `${mark(slot, rec)} ${truncate(rec.title, titleMax)}` : mark(slot, rec))).join(' ');
|
|
31
|
+
for (const t of TITLE_STEPS)
|
|
32
|
+
if (displayWidth(plain(t)) <= room)
|
|
33
|
+
return build(t);
|
|
34
|
+
if (displayWidth(plain(null)) <= room)
|
|
35
|
+
return build(null);
|
|
36
|
+
// 번호만으로도 넘치면 앞에서부터 들어가는 만큼만 + 나머지 개수
|
|
37
|
+
const shown = [];
|
|
38
|
+
let used = displayWidth('CDPM ');
|
|
39
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
40
|
+
const add = (shown.length ? 2 : 0) + displayWidth(num(sorted[i][0], sorted[i][1]));
|
|
41
|
+
const left = sorted.length - i - 1; // 이걸 넣고 나서 남는 개수
|
|
42
|
+
const tail = left ? displayWidth(` +${left}`) : 0;
|
|
43
|
+
if (used + add + tail > room)
|
|
44
|
+
return 'CDPM ' + shown.join(' ') + ` +${sorted.length - i}`;
|
|
45
|
+
shown.push(mark(sorted[i][0], sorted[i][1]));
|
|
46
|
+
used += add;
|
|
47
|
+
}
|
|
48
|
+
return 'CDPM ' + shown.join(' ');
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 상태줄 한 줄. 기록부에 있고 프로세스가 살아 있는 슬롯 중에서, 실제로 탭(창)이 있는 슬롯만 보여준다.
|
|
52
|
+
* 포트가 닫힌(Chrome이 끝난) 슬롯은 빼고, 창을 다 닫은 슬롯은 Windows·Linux에서는 빼고 macOS에서는 남긴다(Cmd+Q로만 끝남).
|
|
53
|
+
* 제목은 마지막으로 조작한 탭(없으면 첫 탭)의 지금 제목, 탭이 없으면 마지막으로 기록된 제목.
|
|
54
|
+
* 응답이 늦으면(0.5초) 기록대로 보여준다 (상태줄은 빨리 끝나야 하므로).
|
|
55
|
+
*/
|
|
56
|
+
/** 내용이 없는 탭: 빈 탭, Chrome 새 탭 페이지. */
|
|
57
|
+
export function isBlankPage(url) {
|
|
58
|
+
return !url || url === 'about:blank' || /^chrome:\/\/(newtab|new-tab-page)\/?$/.test(url) || url.startsWith('chrome-search://local-ntp');
|
|
59
|
+
}
|
|
60
|
+
export async function statusline(width = DEFAULT_WIDTH) {
|
|
61
|
+
const reg = readRegistry();
|
|
62
|
+
const entries = Object.entries(reg.slots)
|
|
63
|
+
.map(([k, rec]) => [Number(k), rec])
|
|
64
|
+
.filter(([slot, rec]) => isValidSlot(slot) && pidAlive(rec.pid));
|
|
65
|
+
const checked = await Promise.all(entries.map(async ([slot, rec]) => {
|
|
66
|
+
try {
|
|
67
|
+
const pages = await listPages(slot, 500);
|
|
68
|
+
// 창(탭)이 하나도 없음: macOS는 앱이 살아 있는 게 원래 동작이라 슬롯을 그대로 두고 마지막 탭 제목을 보여준다.
|
|
69
|
+
// 다른 OS에서는 창을 다 닫은 것이므로 뺀다.
|
|
70
|
+
if (!pages.length)
|
|
71
|
+
return process.platform === 'darwin' ? [slot, rec] : null;
|
|
72
|
+
// 빈 탭·새 탭(about:blank, chrome://newtab 등)은 제목으로 쓰지 않는다. 그런 탭만 남았으면 번호만.
|
|
73
|
+
const real = pages.filter((p) => !isBlankPage(p.url));
|
|
74
|
+
const page = real.find((p) => p.id === rec.lastTarget) ?? real[0];
|
|
75
|
+
return [slot, { ...rec, title: page ? page.title || shortUrl(page.url) : undefined }];
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
return e?.name === 'TimeoutError' ? [slot, rec] : null;
|
|
79
|
+
}
|
|
80
|
+
}));
|
|
81
|
+
return formatStatusline(checked.filter((x) => x !== null), true, width);
|
|
82
|
+
}
|