v2.2.292-296: 메모리·발열 최적화 + Pixel Office 완전 제거 + 소형 모델 추론 강화(calculate/run_code/지식 스코프)

- v2.2.292 메모리·발열: 헬스체크 워크스페이스 쓰기→fs.access(워처 연쇄 제거)·git 검사 비동기 30분 주기,
  웹뷰 retainContextWhenHidden 정리(채팅만 유지), 브레인 인덱스 유휴 30분 TTL 해제,
  채팅 DOM 200개 상한, @lmstudio/sdk 지연 로드
- v2.2.293 Pixel Office 시각화 폐기: astraOffice 모듈·사이드바 매니저 3종·스프라이트 17MB 삭제,
  sidebarProvider collector 섹션 통삭제 (기업 모드 판단 로직 무변경, vsix 12.2MB→1.3MB)
- v2.2.294 도구 메뉴 'NotebookLM 백엔드 실행/종료' 버튼: OS 자동 감지, 프로젝트 자동 탐색+폴더 선택 저장,
  포트 정리 폴백 (터미널 없이 Research 백엔드 켜고 끄기)
- v2.2.295 추론 강화 1탄: [ACTION 16] <calculate> Python 계산 위임(결과 재주입·자가수정 루프),
  단계별 지식 스코프(General+Specialty, 결정적 도메인 분류, 설정 지식·기억 탭 UI)
- v2.2.296 추론 강화 2탄: [ACTION 17] <run_code> 실행 확인(stdout 회수→수정→재실행 루프),
  문법 오류 재주입 자가수정, 도구 라우팅 힌트(dynamicBlocks), Grounding rescue 도메인 스코프 확장
- 검증: jest 818 통과(신규 29개), tsc 무오류, esbuild 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-05 18:59:47 +09:00
co-authored by Claude Fable 5
parent fa397d7fa1
commit bb7cd6b879
466 changed files with 1285 additions and 6588 deletions
@@ -37,7 +37,9 @@ export class ApprovalPanelProvider implements vscode.WebviewViewProvider {
ApprovalPanelProvider.viewType,
'Pending Approvals',
column,
{ enableScripts: true, localResourceRoots: [this._extensionUri], retainContextWhenHidden: true }
// [메모리 개선] retainContextWhenHidden 제거 — 이 패널은 클라이언트 상태가 없고
// 큐 변경 시 백엔드가 html 을 다시 밀어넣으므로, 숨김 동안 렌더러를 상주시킬 이유가 없다.
{ enableScripts: true, localResourceRoots: [this._extensionUri] }
);
this._panel = panel;
const adapter = wrapPanelAsView(panel);
-18
View File
@@ -1,18 +0,0 @@
// Astra Office — public API. 다음 세션에서 추가될 OfficeSnapshot presenter / schema
// 도 같은 entry 로 노출 예정.
//
// 현재 노출: full webview panel HTML 생성 함수. sidebarProvider.ts 는 이 한 줄만 import.
export { renderAstraOfficePanelHtml } from './view/panelHtml';
export type { AstraOfficePanelAssets } from './view/panelHtml';
export type {
OfficeSnapshot,
OfficeAgentSnapshot,
OfficePhase,
OfficeActivityItem,
OfficeBubbleSeed,
} from './schema';
export { validateOfficeSnapshot, makeEmptyOfficeSnapshot } from './schema';
export { presentOfficeSnapshot } from './presenter';
export type { LayoutV2, OfficeDeskCell, OfficeProp } from './view/layoutSchema';
export { validateLayout, migrateLayout } from './view/layoutSchema';
-181
View File
@@ -1,181 +0,0 @@
/**
* Presenter — 옛 AgentWorkState + bubble queue + activity items 를 OfficeSnapshot 으로
* 변환하는 *pure* 함수. mini / full view 둘 다 같은 OfficeSnapshot 을 받게 만드는 게 목표.
*
* 이번 세션의 범위: 인터페이스 + 스텁. 실제 wiring 은 다음 세션에서:
* - sidebarProvider 의 `_pixelOfficeBroadcast` 가 옛 message 대신 OfficeSnapshot 송신
* - mini view (media/sidebar.js) 와 full view (features/astraOffice/view/runtime.ts)
* 둘 다 `officeSnapshot` message 를 받아 자기 식대로 렌더
*
* 이번 세션에 옛 message 와 OfficeSnapshot 을 *동시에* 보낼 수도 있게 — 호환 모드. 다음
* 세션에서 옛 message 제거.
*/
import type { AgentWorkState, AgentBubble } from '../company/pixelOfficeState';
import type { CompanyState } from '../company/types';
import {
type OfficeSnapshot,
type OfficeAgentSnapshot,
type OfficePhase,
type OfficeActivityItem,
type OfficeBubbleSeed,
makeEmptyOfficeSnapshot,
} from './schema';
/** mini/full view 가 받는 message envelope. */
export interface OfficeSnapshotMessage {
type: 'officeSnapshot';
value: OfficeSnapshot;
}
/** 옛 AgentWorkState.status → OfficePhase 매핑. */
const STATUS_TO_PHASE: Record<string, OfficePhase> = {
idle: 'idle',
intake: 'intake',
analyzing: 'planning',
need_clarification: 'awaiting-approval',
contract_ready: 'planning',
planning: 'planning',
executing: 'executing',
reviewing: 'reviewing',
waiting_approval: 'awaiting-approval',
error: 'error',
done: 'done',
};
/** agentId 가 alias 면 정식 id 로 정규화. dispatcher / agents.ts 와 같은 규칙. */
const AGENT_ALIASES: Record<string, string> = {
writer: 'writer',
editor: 'designer',
secretary: 'support',
business: 'inspector',
};
export function normalizeAgentId(rawAgentId: string | undefined): string | null {
if (!rawAgentId) return null;
const lower = rawAgentId.toLowerCase();
return AGENT_ALIASES[lower] ?? lower;
}
/**
* 옛 입력들을 합쳐 새 OfficeSnapshot 을 만든다. 입력 중 일부가 undefined 라도 안전.
*
* 이번 세션 stub: 옛 AgentWorkState 의 *단일 슬롯* 정보로 roster 1개 짜리 snapshot 만
* 생성. 다음 세션에서 CompanyState 의 active roster 전체로 확장.
*/
export function presentOfficeSnapshot(input: {
activeState?: AgentWorkState;
recentBubbles?: AgentBubble[];
recentActivity?: OfficeActivityItem[];
company?: CompanyState;
/**
* 이 turn 의 active agent roster — `listActiveAgentsByCategory` 결과를 평탄화해서 전달.
* 빈 배열/undefined 면 옛 동작 (active agent 1명만) 으로 fallback.
*/
roster?: Array<{ agentId: string; agentName: string; roleCategory: OfficeAgentSnapshot['roleCategory'] }>;
}): OfficeSnapshot {
const snap = makeEmptyOfficeSnapshot();
const { activeState, recentBubbles, recentActivity, roster: rosterInput } = input;
if (activeState) {
const phase = STATUS_TO_PHASE[activeState.status] ?? 'idle';
snap.phase = phase;
snap.activeAgentId = normalizeAgentId(activeState.agentId);
const activeId = snap.activeAgentId;
// Roster:
// - rosterInput 이 주어지면 (#G) 회사 전체 active agent 사용. active agent 만
// activeState 의 상태로 표시하고 나머지는 idle.
// - 없으면 (옛 caller) 활성 agent 1명만 fallback.
if (rosterInput && rosterInput.length > 0) {
const now = Date.now();
snap.roster = rosterInput.map((r) => {
const isActive = activeId !== null && r.agentId === activeId;
return {
agentId: r.agentId,
agentName: r.agentName,
roleCategory: r.roleCategory,
status: isActive ? activeState.status : 'idle',
currentStep: isActive ? activeState.currentStep : undefined,
lastLog: isActive ? (activeState.recentLogs ?? []).slice(-1)[0] : undefined,
lastActivityAt: isActive ? (activeState.updatedAt ?? now) : 0,
};
});
} else {
const role = _inferRoleCategory(activeState.agentId);
const agent: OfficeAgentSnapshot = {
agentId: snap.activeAgentId ?? activeState.agentId,
agentName: activeState.agentName ?? activeState.agentId,
roleCategory: role,
status: activeState.status,
currentStep: activeState.currentStep,
lastLog: (activeState.recentLogs ?? []).slice(-1)[0],
lastActivityAt: activeState.updatedAt ?? Date.now(),
};
snap.roster = [agent];
}
if (activeState.currentTask) {
snap.task = {
goal: activeState.currentTask,
criteria: activeState.requirementContract?.criteria,
openQuestions: activeState.requirementContract?.openQuestions,
format: activeState.requirementContract?.format,
context: activeState.requirementContract?.context,
};
}
if (activeState.pipelineStages) {
snap.pipeline = {
stages: activeState.pipelineStages.map((s) => ({
label: s.label,
agentId: s.agent,
status: s.status,
})),
index: activeState.pipelineStages.findIndex((s) => s.status === 'active'),
};
}
if (activeState.needUserInput?.length || activeState.awaitingApproval) {
snap.awaiting = {
kind: activeState.awaitingApproval ? 'approval' : 'clarification',
questions: activeState.awaitingApproval
? [activeState.awaitingApproval]
: (activeState.needUserInput ?? []),
};
}
}
if (recentActivity?.length) snap.activity = recentActivity.slice(-32);
if (recentBubbles?.length) {
snap.newBubbles = recentBubbles
.map((b) => _toBubbleSeed(b))
.filter((b): b is OfficeBubbleSeed => b !== null);
}
snap.updatedAt = Date.now();
return snap;
}
// ── helpers ──
function _inferRoleCategory(rawAgentId: string | undefined): OfficeAgentSnapshot['roleCategory'] {
if (!rawAgentId) return 'support';
const id = rawAgentId.toLowerCase();
if (id.includes('ceo')) return 'ceo';
if (id.includes('plan')) return 'planner';
if (id.includes('research')) return 'researcher';
if (id.includes('design')) return 'designer';
if (id.includes('writer')) return 'writer';
if (id.includes('editor')) return 'designer';
if (id.includes('developer') || id.includes('dev')) return 'developer';
if (id.includes('qa')) return 'qa';
if (id.includes('inspect') || id.includes('business')) return 'inspector';
return 'support';
}
function _toBubbleSeed(b: AgentBubble): OfficeBubbleSeed | null {
if (!b || !b.text) return null;
return {
agentId: normalizeAgentId(b.agentId) ?? b.agentId,
text: b.text,
type: (b.type as OfficeBubbleSeed['type']) ?? 'status',
};
}
-305
View File
@@ -1,305 +0,0 @@
/**
* OfficeSnapshot — Astra Office 의 도메인 타입.
*
* 동시성 진실 (docs/ASTRA_OFFICE_REFACTOR.md §1): dispatcher 는 직렬이라 한 시점에
* active agent 는 0 또는 1명. 이걸 데이터로 강제하는 게 이 타입의 핵심 역할.
*
* 이 세션에서는 *타입 + validator + empty factory* 만. 백엔드 emit 측 wiring 은
* 다음 세션에서 단계적으로 옮긴다. 현재는 옛 AgentWorkState/CompanyTurnEvent 가
* presenter 입력으로 살아있고, 출력만 OfficeSnapshot.
*/
import type { AgentStatus } from '../company/pixelOfficeState';
export type OfficePhase =
| 'idle'
| 'intake'
| 'planning'
| 'executing'
| 'reviewing'
| 'awaiting-approval'
| 'reporting'
| 'done'
| 'error';
/** 한 명의 agent 가 한 시점에 가진 상태. */
export interface OfficeAgentSnapshot {
/** company roster 의 정식 id (built-in 또는 custom). */
agentId: string;
/** 표시 이름. */
agentName: string;
/** 책상 색깔 / 매핑에 쓰이는 role category. */
roleCategory:
| 'ceo'
| 'planner'
| 'researcher'
| 'designer'
| 'developer'
| 'qa'
| 'inspector'
| 'support'
| 'writer';
status: AgentStatus;
/** "검수 라운드 2/3", "타입 누락" 같은 짧은 부가 정보. */
currentStep?: string;
/** 머리 위 말풍선 source. presenter 가 비워서 보내면 webview 는 풍선 안 띄움. */
lastLog?: string;
/** 정렬 / 신선도 판정. */
lastActivityAt: number;
}
export interface OfficeActivityItem {
/** epoch ms. */
ts: number;
agentId: string;
text: string;
kind?: 'ok' | 'warn' | 'err' | 'info';
}
/** webview 가 풍선을 띄울 때 참고할 hint. presenter 가 매 update 마다 새 풍선 후보를 만들어 보냄. */
export interface OfficeBubbleSeed {
agentId: string;
text: string;
/** 색깔/스타일. presenter 가 status/event/warning/error/success 중 분류. */
type: 'status' | 'event' | 'warning' | 'error' | 'success';
}
export interface OfficeSnapshot {
/** 회사 전체 phase. activeAgent 가 어떤 단계에 있는지와 분리해서 추적. */
phase: OfficePhase;
/** 활성 agent id — 직렬 dispatch 가정. null 이면 idle. */
activeAgentId: string | null;
/** 이 turn 에 참여 가능한 모든 agent. webview 의 책상 그리드 source. */
roster: OfficeAgentSnapshot[];
/** 현재 요구사항 / 계약 요약. */
task?: {
goal: string;
context?: string;
format?: string;
criteria?: string[];
openQuestions?: string[];
};
/** 파이프라인 모드의 stage 진행도. */
pipeline?: {
stages: Array<{
label: string;
agentId?: string;
status: 'done' | 'active' | 'pending';
}>;
index: number;
};
/** 승인 / 추가 정보 대기. */
awaiting?: {
kind: 'approval' | 'clarification';
questions: string[];
};
/** 누적 활동 ring buffer — webview ticker 의 source. */
activity: OfficeActivityItem[];
/** 이 update 사이클에서 새로 생긴 풍선 후보. presenter 가 매 emit 마다 갱신. */
newBubbles: OfficeBubbleSeed[];
/** 디버깅/정렬용. */
updatedAt: number;
}
const VALID_PHASES: ReadonlySet<OfficePhase> = new Set<OfficePhase>([
'idle',
'intake',
'planning',
'executing',
'reviewing',
'awaiting-approval',
'reporting',
'done',
'error',
]);
const VALID_ROLES: ReadonlySet<OfficeAgentSnapshot['roleCategory']> = new Set([
'ceo',
'planner',
'researcher',
'designer',
'developer',
'qa',
'inspector',
'support',
'writer',
]);
const VALID_STATUSES: ReadonlySet<AgentStatus> = new Set<AgentStatus>([
'idle',
'intake',
'analyzing',
'need_clarification',
'contract_ready',
'planning',
'executing',
'reviewing',
'waiting_approval',
'error',
'done',
]);
const VALID_BUBBLE_TYPES = new Set<OfficeBubbleSeed['type']>([
'status',
'event',
'warning',
'error',
'success',
]);
const VALID_KINDS = new Set<NonNullable<OfficeActivityItem['kind']>>([
'ok',
'warn',
'err',
'info',
]);
/**
* 런타임 schema validation. 임의의 unknown 입력을 받아 *완전한 OfficeSnapshot* 또는
* null 을 반환한다. 누락된 필드는 안전한 기본값으로 채운다. 잘못된 enum 값은 'idle'/
* 기본 role 로 fall through. 호출자는 null 이면 default snapshot 으로 폴백 권장.
*/
export function validateOfficeSnapshot(raw: unknown): OfficeSnapshot | null {
if (!raw || typeof raw !== 'object') return null;
const r = raw as Record<string, unknown>;
const phaseRaw = String(r.phase ?? 'idle');
const phase: OfficePhase = (VALID_PHASES as ReadonlySet<string>).has(phaseRaw)
? (phaseRaw as OfficePhase)
: 'idle';
const activeAgentId =
typeof r.activeAgentId === 'string' && r.activeAgentId.length > 0
? r.activeAgentId
: null;
const rosterRaw = Array.isArray(r.roster) ? r.roster : [];
const roster: OfficeAgentSnapshot[] = rosterRaw
.map((a) => _validateAgent(a))
.filter((a): a is OfficeAgentSnapshot => a !== null);
const taskRaw = r.task as Record<string, unknown> | undefined;
const task = taskRaw && typeof taskRaw === 'object' && typeof taskRaw.goal === 'string'
? {
goal: taskRaw.goal,
context: _optStr(taskRaw.context),
format: _optStr(taskRaw.format),
criteria: Array.isArray(taskRaw.criteria)
? taskRaw.criteria.filter((x): x is string => typeof x === 'string')
: undefined,
openQuestions: Array.isArray(taskRaw.openQuestions)
? taskRaw.openQuestions.filter((x): x is string => typeof x === 'string')
: undefined,
}
: undefined;
const pipelineRaw = r.pipeline as Record<string, unknown> | undefined;
const pipeline = pipelineRaw && Array.isArray(pipelineRaw.stages)
? {
stages: pipelineRaw.stages
.map((s) => _validateStage(s))
.filter((s): s is { label: string; agentId?: string; status: 'done' | 'active' | 'pending' } => s !== null),
index: typeof pipelineRaw.index === 'number' ? pipelineRaw.index : 0,
}
: undefined;
const awaitingRaw = r.awaiting as Record<string, unknown> | undefined;
const awaiting = awaitingRaw && (awaitingRaw.kind === 'approval' || awaitingRaw.kind === 'clarification')
? {
kind: awaitingRaw.kind as 'approval' | 'clarification',
questions: Array.isArray(awaitingRaw.questions)
? awaitingRaw.questions.filter((x): x is string => typeof x === 'string')
: [],
}
: undefined;
const activity: OfficeActivityItem[] = Array.isArray(r.activity)
? r.activity
.map((it) => _validateActivity(it))
.filter((it): it is OfficeActivityItem => it !== null)
: [];
const newBubbles: OfficeBubbleSeed[] = Array.isArray(r.newBubbles)
? r.newBubbles
.map((b) => _validateBubble(b))
.filter((b): b is OfficeBubbleSeed => b !== null)
: [];
const updatedAt = typeof r.updatedAt === 'number' ? r.updatedAt : Date.now();
return { phase, activeAgentId, roster, task, pipeline, awaiting, activity, newBubbles, updatedAt };
}
export function makeEmptyOfficeSnapshot(): OfficeSnapshot {
return {
phase: 'idle',
activeAgentId: null,
roster: [],
activity: [],
newBubbles: [],
updatedAt: Date.now(),
};
}
// ─────────── helpers ───────────
function _optStr(v: unknown): string | undefined {
return typeof v === 'string' ? v : undefined;
}
function _validateAgent(raw: unknown): OfficeAgentSnapshot | null {
if (!raw || typeof raw !== 'object') return null;
const a = raw as Record<string, unknown>;
if (typeof a.agentId !== 'string' || !a.agentId) return null;
const role = typeof a.roleCategory === 'string' && (VALID_ROLES as ReadonlySet<string>).has(a.roleCategory)
? (a.roleCategory as OfficeAgentSnapshot['roleCategory'])
: 'support';
const status: AgentStatus = typeof a.status === 'string' && (VALID_STATUSES as ReadonlySet<string>).has(a.status)
? (a.status as AgentStatus)
: 'idle';
return {
agentId: a.agentId,
agentName: typeof a.agentName === 'string' ? a.agentName : a.agentId,
roleCategory: role,
status,
currentStep: _optStr(a.currentStep),
lastLog: _optStr(a.lastLog),
lastActivityAt: typeof a.lastActivityAt === 'number' ? a.lastActivityAt : 0,
};
}
function _validateStage(raw: unknown): { label: string; agentId?: string; status: 'done' | 'active' | 'pending' } | null {
if (!raw || typeof raw !== 'object') return null;
const s = raw as Record<string, unknown>;
if (typeof s.label !== 'string') return null;
const statusRaw = String(s.status ?? 'pending');
const status = (statusRaw === 'done' || statusRaw === 'active' || statusRaw === 'pending') ? statusRaw : 'pending';
return { label: s.label, agentId: _optStr(s.agentId), status };
}
function _validateActivity(raw: unknown): OfficeActivityItem | null {
if (!raw || typeof raw !== 'object') return null;
const a = raw as Record<string, unknown>;
if (typeof a.text !== 'string' || typeof a.agentId !== 'string') return null;
const kind = typeof a.kind === 'string' && (VALID_KINDS as ReadonlySet<string>).has(a.kind)
? (a.kind as OfficeActivityItem['kind'])
: undefined;
return {
ts: typeof a.ts === 'number' ? a.ts : Date.now(),
agentId: a.agentId,
text: a.text,
kind,
};
}
function _validateBubble(raw: unknown): OfficeBubbleSeed | null {
if (!raw || typeof raw !== 'object') return null;
const b = raw as Record<string, unknown>;
if (typeof b.agentId !== 'string' || typeof b.text !== 'string') return null;
const type = typeof b.type === 'string' && (VALID_BUBBLE_TYPES as ReadonlySet<string>).has(b.type)
? (b.type as OfficeBubbleSeed['type'])
: 'status';
return { agentId: b.agentId, text: b.text, type };
}
@@ -1,180 +0,0 @@
/**
* Pixel Office layout 저장 스키마 — workspaceState 의 `g1nation.pixelOfficeLayout` 키
* 에 저장되는 객체의 런타임 validator + v1 → v2 migration.
*
* 옛 runtime.ts 의 `_isV2Snap()` heuristic 을 정식 schema 로 격상. webview 에서 받는
* 즉시 한 번 통과시키면 깨진 데이터 / 옛 데이터 모두 안전하게 처리된다.
*
* 백엔드는 unknown 그대로 저장하지만, *로드 직후* 이 validator 를 적용해 정규화한다.
*/
export interface OfficeDeskCell {
/** 안정적 식별자 — DOM dataset.role 로도 쓰임. */
roleKey: string;
/** 매핑된 agent id. 비어있으면 unmapped. */
agentKey: string;
label: string;
charRow: number; // 0~7
deskSprite: string;
/** 앉은 face. */
face: 'L' | 'R' | 'U' | 'D';
boss: boolean;
/** seat 에서 잠시 일어났다 가는 dock 좌표. */
dock?: [number, number];
/** 랜덤 roam 후보 좌표들. */
roam?: Array<[number, number]>;
deskX: number;
deskY: number;
deskW: number;
deskRot: number;
deskZ: number;
seatX: number;
seatY: number;
charRot: number;
charZ: number;
/** 캐릭터를 지운 빈 책상. */
noChar: boolean;
}
export interface OfficeProp {
id: string;
name: string;
x: number;
y: number;
w?: number;
rot: number;
z: number;
}
export interface LayoutV2 {
schema: 2;
cells: OfficeDeskCell[];
objs: OfficeProp[];
}
const VALID_FACES = new Set<OfficeDeskCell['face']>(['L', 'R', 'U', 'D']);
/**
* raw 가 valid v2 layout 이면 정규화된 LayoutV2 를, 아니면 null.
* v1 (옛 좌표만 있는 포맷) 은 별도 `migrateLayout()` 사용.
*/
export function validateLayout(raw: unknown): LayoutV2 | null {
if (!raw || typeof raw !== 'object') return null;
const r = raw as Record<string, unknown>;
if (!Array.isArray(r.cells)) return null;
const isV2 = r.schema === 2 || r.cells.some(
(c) =>
c && typeof c === 'object' &&
(typeof (c as Record<string, unknown>).deskSprite === 'string'
|| typeof (c as Record<string, unknown>).agentKey === 'string'
|| typeof (c as Record<string, unknown>).charRow === 'number'),
);
if (!isV2) return null;
const cells = r.cells.map((c) => _normalizeCell(c)).filter((c): c is OfficeDeskCell => c !== null);
const objsRaw = Array.isArray(r.objs) ? r.objs : [];
const objs = objsRaw.map((o) => _normalizeProp(o)).filter((o): o is OfficeProp => o !== null);
return { schema: 2, cells, objs };
}
/**
* v1 (옛 좌표 패치 포맷) → v2 (전체 station 정의) 마이그레이션. v1 은 좌표만 갖고 있어
* default station 의 나머지 필드(charRow, deskSprite 등)를 채워줘야 한다. webview 의
* default station 매핑이 함께 주어져야 정확. 없으면 best-effort.
*
* 이번 세션 stub: v1 입력이 들어오면 v2 shape 으로 일단 변환 (default 필드는 0/빈 값).
* 다음 세션에서 default station 룩업과 결합.
*/
export function migrateLayout(raw: unknown): LayoutV2 | null {
const asV2 = validateLayout(raw);
if (asV2) return asV2;
if (!raw || typeof raw !== 'object') return null;
const r = raw as Record<string, unknown>;
if (!Array.isArray(r.cells)) return null;
const cells: OfficeDeskCell[] = r.cells
.map((cRaw) => {
if (!cRaw || typeof cRaw !== 'object') return null;
const c = cRaw as Record<string, unknown>;
if (typeof c.roleKey !== 'string') return null;
return _normalizeCell({
...c,
// v1 은 charRow / deskSprite 등이 없으니 안전한 기본값.
charRow: 0,
deskSprite: 'desk-main',
face: 'R',
boss: false,
agentKey: c.roleKey, // 옛 키가 곧 agent 였음.
label: c.roleKey,
noChar: false,
});
})
.filter((c): c is OfficeDeskCell => c !== null);
const objs = Array.isArray(r.objs)
? r.objs.map((o) => _normalizeProp(o)).filter((o): o is OfficeProp => o !== null)
: [];
return { schema: 2, cells, objs };
}
function _normalizeCell(raw: unknown): OfficeDeskCell | null {
if (!raw || typeof raw !== 'object') return null;
const c = raw as Record<string, unknown>;
if (typeof c.roleKey !== 'string' || !c.roleKey) return null;
const face = typeof c.face === 'string' && (VALID_FACES as ReadonlySet<string>).has(c.face)
? (c.face as OfficeDeskCell['face'])
: 'R';
return {
roleKey: c.roleKey,
agentKey: typeof c.agentKey === 'string' ? c.agentKey : '',
label: typeof c.label === 'string' ? c.label : c.roleKey,
charRow: _num(c.charRow, 0),
deskSprite: typeof c.deskSprite === 'string' ? c.deskSprite : 'desk-main',
face,
boss: !!c.boss,
dock: _pair(c.dock),
roam: Array.isArray(c.roam)
? (c.roam.map(_pair).filter(Boolean) as Array<[number, number]>)
: undefined,
deskX: _num(c.deskX, 0),
deskY: _num(c.deskY, 0),
deskW: _num(c.deskW, 112),
deskRot: _num(c.deskRot, 0),
deskZ: _num(c.deskZ, 0),
seatX: _num(c.seatX, 0),
seatY: _num(c.seatY, 0),
charRot: _num(c.charRot, 0),
charZ: _num(c.charZ, 0),
noChar: !!c.noChar,
};
}
function _normalizeProp(raw: unknown): OfficeProp | null {
if (!raw || typeof raw !== 'object') return null;
const o = raw as Record<string, unknown>;
if (typeof o.name !== 'string') return null;
return {
id: typeof o.id === 'string' ? o.id : `obj_${Math.random().toString(36).slice(2, 8)}`,
name: o.name,
x: _num(o.x, 0),
y: _num(o.y, 0),
w: typeof o.w === 'number' ? o.w : undefined,
rot: _num(o.rot, 0),
z: _num(o.z, 0),
};
}
function _num(v: unknown, fallback: number): number {
return typeof v === 'number' && Number.isFinite(v) ? v : fallback;
}
function _pair(v: unknown): [number, number] | undefined {
if (!Array.isArray(v) || v.length !== 2) return undefined;
const a = typeof v[0] === 'number' ? v[0] : NaN;
const b = typeof v[1] === 'number' ? v[1] : NaN;
if (!Number.isFinite(a) || !Number.isFinite(b)) return undefined;
return [a, b];
}
-103
View File
@@ -1,103 +0,0 @@
export const OFFICE_BODY = `
<div class="office-app">
<header class="topbar">
<div class="brand-block">
<div class="eyebrow">ASTRA OFFICE</div>
<div class="h-title">Operations Floor</div>
</div>
<div class="topbar-center">
<div class="phase-pill" id="phasePill"><span class="phase-dot"></span><span id="status">대기 중</span></div>
<div class="agent-pill"><span class="agent-label">현재 담당</span><strong id="agent">Astra</strong></div>
</div>
<div class="topbar-actions">
<button id="editBtn" class="edit-btn" title="오피스 배치 편집 모드 토글">Customize</button>
</div>
</header>
<div id="editToolbar" class="edit-toolbar" style="display:none;">
<span class="et-hint">드래그로 이동 · <b>R</b> 회전 · <b>]</b>/<b>[</b> 레이어 · 4px snap</span>
<button id="addDeskBtn" class="add" title="책상 추가">+ 책상</button>
<button id="addPropBtn" class="add" title="가구 추가">+ 가구</button>
<button id="deleteSelBtn" class="del" title="선택 항목 삭제" disabled>삭제</button>
<button id="layerUpBtn" title="레이어 위로 (])">위로</button>
<button id="layerDownBtn" title="레이어 아래로 ([)">아래로</button>
<button id="saveBtn">저장</button>
<button id="resetBtn" title="기본 배치로 복귀">초기화</button>
<button id="cancelBtn" title="저장 안 하고 종료">취소</button>
</div>
<main class="workspace">
<aside class="side-panel team-panel">
<div class="panel-head">
<div>
<div class="panel-kicker">Team</div>
<h2>오늘의 라인업</h2>
</div>
<div class="count-badge" id="rosterCount">0</div>
</div>
<div id="rosterList" class="roster-list"></div>
</aside>
<section class="office-shell">
<div class="mission-strip">
<div>
<div class="panel-kicker">Current Mission</div>
<div class="mission-title" id="task">새 요청을 기다리고 있습니다.</div>
</div>
<div class="mission-step-wrap">
<span>현재 단계</span>
<strong id="step">대기 중</strong>
</div>
</div>
<div id="miniMap" class="mini-map" style="display:none;"></div>
<div class="office-stage-wrap">
<div class="office">
<div class="stage" id="stage">
<svg id="flowLayer" class="flow-layer" viewBox="0 0 720 585" preserveAspectRatio="none" aria-hidden="true"></svg>
<div class="wall-window w1"></div>
<div class="wall-window w2"></div>
</div>
<div id="propPanel" class="prop-panel"></div>
</div>
</div>
</section>
<aside class="side-panel mission-panel">
<div class="panel-head compact">
<div>
<div class="panel-kicker">Signal</div>
<h2>운영 브리프</h2>
</div>
</div>
<div class="brief-grid">
<section class="brief-card hero">
<span>현재 흐름</span>
<strong id="phaseLabel">대기 중</strong>
<p id="phaseNote">새로운 작업 요청을 기다리고 있습니다.</p>
</section>
<section class="brief-card">
<span>진행률</span>
<strong id="progressLabel">0%</strong>
<div class="progress"><div class="bar" id="bar"></div></div>
</section>
<section class="brief-card" id="attentionCard">
<span>주의 신호</span>
<strong id="attentionTitle">없음</strong>
<p id="attentionBody">현재 막힘 없이 진행 중입니다.</p>
</section>
</div>
</aside>
</main>
<footer class="activity-dock">
<div class="activity-head">
<div>
<div class="panel-kicker">Activity</div>
<strong>최근 실행</strong>
</div>
<div id="log" class="last-log">아직 기록된 활동이 없습니다.</div>
</div>
<div id="ticker" class="ticker" style="display:none;"><div class="tk-track" id="tickerTrack"></div></div>
</footer>
</div>
`;
@@ -1,419 +0,0 @@
export const OFFICE_CSS = `
:root{
--bg:#070A12;
--bg-soft:#0D1220;
--surface:rgba(15,21,36,.78);
--surface-strong:rgba(18,25,43,.94);
--surface-faint:rgba(255,255,255,.045);
--line:rgba(255,255,255,.09);
--line-strong:rgba(255,255,255,.16);
--text:#F5F7FC;
--muted:#9BA6BF;
--accent:#8A7CFF;
--accent-2:#46D8FF;
--success:#35D7A4;
--warning:#F5C45A;
--danger:#FF6B7A;
--shadow:0 18px 60px rgba(0,0,0,.42);
--radius-xl:24px;
--radius-lg:18px;
--radius-md:14px;
--radius-sm:10px;
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;
background:
radial-gradient(circle at 12% 0%,rgba(138,124,255,.18),transparent 28%),
radial-gradient(circle at 90% 10%,rgba(70,216,255,.12),transparent 24%),
radial-gradient(circle at 50% 100%,rgba(53,215,164,.08),transparent 32%),
linear-gradient(180deg,#070A12 0%,#0A0F1A 100%);
color:var(--text);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
overflow:hidden;
}
button,input,select{font:inherit}
.office-app{height:100vh;display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;gap:14px;padding:18px}
.topbar{
min-height:70px;
display:flex;
align-items:center;
justify-content:space-between;
gap:18px;
padding:14px 16px 14px 18px;
border:1px solid var(--line);
border-radius:var(--radius-xl);
background:linear-gradient(180deg,rgba(255,255,255,.08),rgba(255,255,255,.035));
backdrop-filter:blur(18px);
box-shadow:var(--shadow);
}
.brand-block{display:flex;flex-direction:column;gap:3px;min-width:180px}
.eyebrow,.panel-kicker{font-size:10px;line-height:1;letter-spacing:.16em;text-transform:uppercase;color:var(--muted)}
.h-title{font-size:22px;line-height:1.1;font-weight:750;letter-spacing:-.03em}
.topbar-center{display:flex;align-items:center;justify-content:center;gap:10px;flex:1;min-width:0}
.phase-pill,.agent-pill{
min-height:38px;
display:flex;
align-items:center;
gap:9px;
padding:0 14px;
border:1px solid var(--line);
border-radius:999px;
background:rgba(255,255,255,.05);
white-space:nowrap;
}
.phase-pill{font-weight:650}
.phase-pill .phase-dot{width:8px;height:8px;border-radius:50%;background:var(--accent);box-shadow:0 0 16px rgba(138,124,255,.8)}
.phase-pill[data-tone="success"] .phase-dot{background:var(--success);box-shadow:0 0 16px rgba(53,215,164,.8)}
.phase-pill[data-tone="warning"] .phase-dot{background:var(--warning);box-shadow:0 0 16px rgba(245,196,90,.8)}
.phase-pill[data-tone="danger"] .phase-dot{background:var(--danger);box-shadow:0 0 16px rgba(255,107,122,.8)}
.agent-pill{color:var(--muted)}
.agent-pill strong{color:var(--text);font-size:13px}
.agent-label{font-size:11px}
.topbar-actions{display:flex;align-items:center;justify-content:flex-end;min-width:180px}
.edit-btn{
height:38px;
border-radius:999px;
padding:0 15px;
border:1px solid rgba(138,124,255,.35);
color:var(--text);
background:linear-gradient(180deg,rgba(138,124,255,.22),rgba(138,124,255,.12));
cursor:pointer;
transition:transform .16s ease,border-color .16s ease,background .16s ease;
}
.edit-btn:hover{transform:translateY(-1px);border-color:rgba(138,124,255,.62);background:linear-gradient(180deg,rgba(138,124,255,.3),rgba(138,124,255,.16))}
.edit-toolbar{
display:flex;
align-items:center;
gap:8px;
flex-wrap:wrap;
padding:10px 12px;
border:1px solid rgba(138,124,255,.28);
border-radius:var(--radius-lg);
background:rgba(138,124,255,.12);
backdrop-filter:blur(16px);
}
.edit-toolbar .et-hint{flex:1;min-width:220px;color:#DCE2F2;font-size:12px}
.edit-toolbar button{
min-height:32px;
padding:0 11px;
border-radius:999px;
border:1px solid var(--line-strong);
color:var(--text);
background:rgba(255,255,255,.07);
cursor:pointer;
}
.edit-toolbar button:hover{background:rgba(255,255,255,.12)}
.edit-toolbar button.add{border-color:rgba(53,215,164,.4);background:rgba(53,215,164,.12)}
.edit-toolbar button.del{border-color:rgba(255,107,122,.42);background:rgba(255,107,122,.12)}
.edit-toolbar button[disabled]{opacity:.42;cursor:not-allowed}
.workspace{
min-height:0;
display:grid;
grid-template-columns:260px minmax(620px,1fr) 280px;
gap:14px;
}
.side-panel,.office-shell,.activity-dock{
border:1px solid var(--line);
border-radius:var(--radius-xl);
background:var(--surface);
backdrop-filter:blur(20px);
box-shadow:var(--shadow);
}
.side-panel{padding:16px;min-height:0;overflow:hidden}
.panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:14px}
.panel-head.compact{margin-bottom:16px}
.panel-head h2{font-size:16px;line-height:1.2;letter-spacing:-.02em;margin:6px 0 0}
.count-badge{
min-width:28px;
height:28px;
display:grid;
place-items:center;
border-radius:999px;
border:1px solid rgba(70,216,255,.25);
background:rgba(70,216,255,.12);
color:#BDEFFF;
font-size:12px;
font-weight:700;
}
.roster-list{display:flex;flex-direction:column;gap:9px;overflow:auto;padding-right:2px;max-height:calc(100vh - 220px)}
.roster-item{
display:grid;
grid-template-columns:auto minmax(0,1fr);
gap:11px;
align-items:center;
padding:11px;
border-radius:var(--radius-md);
border:1px solid transparent;
background:rgba(255,255,255,.035);
transition:border-color .16s ease,background .16s ease,transform .16s ease;
}
.roster-item[data-agent]{cursor:pointer}
.roster-item.active{border-color:rgba(138,124,255,.48);background:linear-gradient(180deg,rgba(138,124,255,.16),rgba(138,124,255,.08));transform:translateX(2px)}
.roster-item.preview{border-color:rgba(255,255,255,.2);background:rgba(255,255,255,.07)}
.roster-avatar{
width:33px;height:33px;border-radius:12px;
display:grid;place-items:center;
background:rgba(255,255,255,.08);
border:1px solid var(--line);
color:var(--role-color,var(--accent));
font-size:11px;font-weight:700;
}
.roster-copy{min-width:0;display:flex;flex-direction:column;gap:3px}
.roster-copy strong{font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.roster-meta{display:flex;align-items:center;gap:6px;color:var(--muted);font-size:11px}
.roster-status{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.28)}
.roster-item.active .roster-status{background:var(--role-color,var(--accent));box-shadow:0 0 12px var(--role-color,var(--accent))}
.office-shell{min-width:0;display:grid;grid-template-rows:auto auto minmax(0,1fr);overflow:hidden}
.office-shell[data-roster-empty="true"] .office{filter:saturate(.72) brightness(.9)}
.office-shell[data-roster-empty="true"] .stage{opacity:.86}
.office-shell[data-status="executing"] .office{box-shadow:inset 0 0 0 1px rgba(138,124,255,.12),0 0 0 1px rgba(138,124,255,.08)}
.office-shell[data-status="reviewing"] .office{box-shadow:inset 0 0 0 1px rgba(70,216,255,.14),0 0 0 1px rgba(70,216,255,.08)}
.office-shell[data-status="waiting_approval"] .office{box-shadow:inset 0 0 0 1px rgba(245,196,90,.16),0 0 0 1px rgba(245,196,90,.08)}
.office-shell[data-status="error"] .office{box-shadow:inset 0 0 0 1px rgba(255,107,122,.18),0 0 0 1px rgba(255,107,122,.08)}
.mission-strip{
min-height:72px;
display:flex;
justify-content:space-between;
align-items:center;
gap:18px;
padding:15px 18px;
border-bottom:1px solid var(--line);
}
.mission-title{margin-top:6px;font-size:16px;font-weight:650;letter-spacing:-.02em;max-width:min(560px,52vw);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mission-step-wrap{display:flex;flex-direction:column;align-items:flex-end;gap:5px;min-width:160px}
.mission-step-wrap span{font-size:11px;color:var(--muted)}
.mission-step-wrap strong{font-size:13px;font-weight:650;text-align:right;max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mini-map{display:flex;align-items:center;gap:6px;min-height:42px;padding:0 18px;border-bottom:1px solid var(--line);overflow-x:auto;scrollbar-width:none}
.mini-map::-webkit-scrollbar{display:none}
.mini-map .mm-dot{position:relative;width:10px;height:10px;border-radius:50%;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.18);flex-shrink:0;transition:all .2s ease}
.mini-map .mm-dot[data-status="done"]{background:var(--success);border-color:var(--success);box-shadow:0 0 12px rgba(53,215,164,.35)}
.mini-map .mm-dot[data-status="active"]{width:14px;height:14px;background:var(--accent);border-color:var(--accent);box-shadow:0 0 0 4px rgba(138,124,255,.16)}
.mini-map .mm-bar{flex:1;height:1px;min-width:22px;background:linear-gradient(90deg,rgba(255,255,255,.08),rgba(255,255,255,.18))}
.mini-map .mm-label{position:absolute;left:50%;top:-29px;transform:translateX(-50%);padding:4px 7px;border-radius:999px;background:rgba(6,9,16,.95);border:1px solid var(--line);font-size:10px;white-space:nowrap;color:var(--text);opacity:0;pointer-events:none;transition:opacity .14s ease;z-index:40}
.mini-map .mm-dot:hover .mm-label{opacity:1}
.mini-map .mm-counter{margin-left:6px;color:var(--muted);font-size:11px;white-space:nowrap}
.office-stage-wrap{min-height:0;padding:14px;display:flex}
.office{
position:relative;
flex:1;
min-height:420px;
overflow:hidden;
display:flex;
align-items:center;
justify-content:center;
border-radius:20px;
border:1px solid rgba(255,255,255,.08);
background:
linear-gradient(180deg,rgba(18,28,48,.98) 0 16%,transparent 16%),
radial-gradient(circle at 50% -10%,rgba(138,124,255,.24),transparent 32%),
radial-gradient(circle at 18% 100%,rgba(70,216,255,.12),transparent 28%),
linear-gradient(135deg,#31283A,#201A29 72%);
}
.office.has-art{
background:
linear-gradient(180deg,rgba(6,10,18,.06),rgba(6,10,18,.12)),
var(--office-backdrop) center center / cover no-repeat;
}
.office:before{content:'';position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,.018) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.018) 1px,transparent 1px);background-size:48px 48px;opacity:.28}
.office.has-art:before{background:linear-gradient(180deg,rgba(4,7,14,.06),transparent 28%,rgba(4,7,14,.1));opacity:1}
.office:after{content:'';position:absolute;inset:0;background:radial-gradient(circle at 50% 50%,transparent 0 42%,rgba(0,0,0,.2) 100%);pointer-events:none}
.stage{position:relative;width:720px;height:585px;margin:0;z-index:2}
.flow-layer{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:3}
.flow-route{
fill:none;
stroke:rgba(138,124,255,.34);
stroke-width:2;
stroke-linecap:round;
stroke-linejoin:round;
stroke-dasharray:5 8;
filter:drop-shadow(0 0 6px rgba(138,124,255,.25));
}
.flow-node{
fill:rgba(138,124,255,.18);
stroke:rgba(255,255,255,.34);
stroke-width:1.2;
}
.flow-node[data-status="done"]{fill:rgba(53,215,164,.34);stroke:rgba(53,215,164,.8)}
.flow-node[data-status="active"]{fill:rgba(138,124,255,.6);stroke:#D8D2FF;filter:drop-shadow(0 0 8px rgba(138,124,255,.72))}
.flow-node[data-status="pending"]{fill:rgba(255,255,255,.08);stroke:rgba(255,255,255,.22)}
.wall-window{position:absolute;top:16px;width:86px;height:42px;border:2px solid rgba(215,228,255,.35);border-radius:8px;background:linear-gradient(180deg,rgba(160,208,255,.34),rgba(110,150,210,.08));box-shadow:inset 0 0 0 1px rgba(15,20,31,.55)}
.wall-window.w1{left:84px}.wall-window.w2{left:550px}
.office.has-art .wall-window{display:none}
.obj,.desk,.char{position:absolute;image-rendering:pixelated}
.obj{filter:drop-shadow(3px 5px 0 rgba(0,0,0,.28));z-index:4}
.desk{width:112px;z-index:5;filter:drop-shadow(4px 7px 0 rgba(0,0,0,.28))}
.desk.boss{width:136px}
.label{position:absolute;left:50%;bottom:-15px;transform:translateX(-50%);font-size:10px;color:rgba(245,247,252,.8);white-space:nowrap;text-shadow:0 1px 4px rgba(0,0,0,.8)}
.char{width:56px;height:72px;z-index:7;transition:left .9s cubic-bezier(.2,.7,.2,1),top .9s cubic-bezier(.2,.7,.2,1)}
.char.walking{z-index:14}
.char img{position:absolute;left:0;bottom:0;max-width:100%;max-height:100%;image-rendering:pixelated;filter:drop-shadow(2px 3px 0 rgba(0,0,0,.42));transform-origin:center bottom}
.char.active:before{content:'';position:absolute;left:19px;top:-14px;width:18px;height:18px;border-radius:50%;background:radial-gradient(circle,var(--role-color,var(--accent)) 0 28%,rgba(255,255,255,.18) 30%,transparent 72%);filter:blur(.2px);animation:focusPulse 1.8s ease-in-out infinite}
.char.active::after{content:'';position:absolute;left:-4px;right:-4px;bottom:-7px;height:8px;border-radius:999px;background:radial-gradient(circle,var(--role-color,var(--accent)),transparent 70%);opacity:.82;filter:blur(1px)}
.char.working img{animation:workLean 1.6s ease-in-out infinite}
@keyframes focusPulse{0%,100%{transform:scale(.95);opacity:.88}50%{transform:scale(1.12);opacity:1}}
@keyframes workLean{0%,100%{transform:translateY(0)}50%{transform:translateY(-2px)}}
.char[data-agent="ceo"],.desk[data-agent="ceo"],.roster-item[data-agent="ceo"]{--role-color:#A78BFA}
.char[data-agent="planner"],.desk[data-agent="planner"],.roster-item[data-agent="planner"]{--role-color:#60A5FA}
.char[data-agent="researcher"],.desk[data-agent="researcher"],.roster-item[data-agent="researcher"]{--role-color:#35D7A4}
.char[data-agent="designer"],.desk[data-agent="designer"],.roster-item[data-agent="designer"]{--role-color:#F472B6}
.char[data-agent="developer"],.desk[data-agent="developer"],.roster-item[data-agent="developer"]{--role-color:#F5C45A}
.char[data-agent="qa"],.desk[data-agent="qa"],.roster-item[data-agent="qa"]{--role-color:#46D8FF}
.char[data-agent="inspector"],.desk[data-agent="inspector"],.roster-item[data-agent="inspector"]{--role-color:#FB923C}
.char[data-agent="support"],.desk[data-agent="support"],.roster-item[data-agent="support"]{--role-color:#94A3B8}
.char[data-agent="writer"],.desk[data-agent="writer"],.roster-item[data-agent="writer"]{--role-color:#FBBF24}
.desk::after{content:'';position:absolute;inset:-4px;border-radius:10px;border:1px solid transparent;pointer-events:none;transition:border-color .2s ease,box-shadow .2s ease}
.desk.pipeline-desk::after{border-color:rgba(255,255,255,.12)}
.desk[data-flow="done"]::after{border-color:rgba(53,215,164,.26)}
.desk[data-flow="active"]::after{border-color:rgba(138,124,255,.72);box-shadow:0 0 0 1px rgba(255,255,255,.06),0 0 20px rgba(138,124,255,.34)}
.desk[data-flow="pending"]::after{border-color:rgba(255,255,255,.16)}
.flow-badge{
position:absolute;
right:-7px;
top:-12px;
min-width:28px;
height:22px;
display:grid;
place-items:center;
padding:0 7px;
border-radius:999px;
border:1px solid rgba(255,255,255,.18);
background:rgba(8,12,22,.88);
color:#E7E2FF;
font-size:10px;
font-weight:750;
letter-spacing:.01em;
box-shadow:0 10px 22px rgba(0,0,0,.24);
}
.desk[data-flow="done"] .flow-badge{color:#B7FFE7;border-color:rgba(53,215,164,.28)}
.desk[data-flow="active"] .flow-badge{color:#F2EFFF;border-color:rgba(138,124,255,.5);background:rgba(31,24,66,.92)}
.desk.preview::after{border-color:rgba(255,255,255,.28);box-shadow:0 0 0 1px rgba(255,255,255,.04),0 0 18px rgba(255,255,255,.16)}
.char.preview::before{content:'';position:absolute;left:18px;top:-14px;width:20px;height:20px;border-radius:50%;border:1px solid rgba(255,255,255,.42);box-shadow:0 0 18px rgba(255,255,255,.18)}
.stage:has(.char.active[data-agent="ceo"]) .desk[data-agent="ceo"]::after,
.stage:has(.char.active[data-agent="planner"]) .desk[data-agent="planner"]::after,
.stage:has(.char.active[data-agent="researcher"]) .desk[data-agent="researcher"]::after,
.stage:has(.char.active[data-agent="designer"]) .desk[data-agent="designer"]::after,
.stage:has(.char.active[data-agent="developer"]) .desk[data-agent="developer"]::after,
.stage:has(.char.active[data-agent="qa"]) .desk[data-agent="qa"]::after,
.stage:has(.char.active[data-agent="inspector"]) .desk[data-agent="inspector"]::after,
.stage:has(.char.active[data-agent="support"]) .desk[data-agent="support"]::after,
.stage:has(.char.active[data-agent="writer"]) .desk[data-agent="writer"]::after{border-color:var(--role-color);box-shadow:0 0 0 1px rgba(255,255,255,.06),0 0 18px color-mix(in srgb,var(--role-color) 35%,transparent)}
.shadow{position:absolute;left:12px;bottom:0;width:28px;height:7px;background:radial-gradient(ellipse,rgba(0,0,0,.55),transparent 70%)}
.bubble{position:absolute;z-index:20;transform:translate(-50%,-100%);max-width:180px;padding:7px 10px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:rgba(10,14,24,.92);color:var(--text);font-size:11px;line-height:1.35;box-shadow:0 10px 24px rgba(0,0,0,.28);white-space:normal;animation:bubble-pop .22s cubic-bezier(.2,1.4,.6,1)}
@keyframes bubble-pop{from{transform:translate(-50%,-88%) scale(.6);opacity:0}to{transform:translate(-50%,-100%) scale(1);opacity:1}}
/* 감정 태그별 변형 — 희노애락. webtoon 느낌으로 background / 색 / 이모지 prefix. */
.bubble-joy {background:rgba(254,243,199,.97);color:#7c5d11;border-color:rgba(252,211,77,.6)}
.bubble-joy::before {content:'😊 ';opacity:.85}
.bubble-anger {background:rgba(254,226,226,.97);color:#7f1d1d;border-color:#ef4444;animation:bubble-pop .22s cubic-bezier(.2,1.4,.6,1),bubble-shake .4s ease-in-out 1}
.bubble-anger::before {content:'😠 ';opacity:.85}
.bubble-sorrow {background:rgba(219,234,254,.97);color:#1e3a8a;border-color:rgba(96,165,250,.5)}
.bubble-sorrow::before {content:'😔 ';opacity:.85}
.bubble-panic {background:rgba(254,226,226,.97);color:#9a1c1c;border-color:rgba(248,113,113,.55);animation:bubble-pop .22s cubic-bezier(.2,1.4,.6,1),bubble-shake .5s ease-in-out 1}
.bubble-panic::before {content:'😱 ';opacity:.85}
.bubble-curious {background:rgba(243,232,255,.97);color:#5b21b6;border-color:rgba(167,139,250,.45)}
.bubble-curious::before {content:'🤔 ';opacity:.85}
.bubble-firm {background:rgba(255,255,255,.98);color:#111;border-color:rgba(0,0,0,.18);font-weight:700}
.bubble-firm::before {content:'✋ ';opacity:.85}
.bubble-gratitude{background:rgba(220,252,231,.97);color:#14532d;border-color:rgba(74,222,128,.5)}
.bubble-gratitude::before{content:'🙏 ';opacity:.85}
.bubble-thought {/* default 그대로 */}
@keyframes bubble-shake{0%,100%{transform:translate(-50%,-100%) rotate(0)}25%{transform:translate(-52%,-100%) rotate(-2deg)}75%{transform:translate(-48%,-100%) rotate(2deg)}}
.brief-grid{display:flex;flex-direction:column;gap:10px}
.brief-card{
padding:14px;
border-radius:var(--radius-md);
border:1px solid var(--line);
background:rgba(255,255,255,.035);
}
.brief-card.hero{background:linear-gradient(180deg,rgba(138,124,255,.16),rgba(255,255,255,.03));border-color:rgba(138,124,255,.28)}
.brief-card span{display:block;font-size:11px;color:var(--muted);margin-bottom:6px}
.brief-card strong{display:block;font-size:17px;line-height:1.2;letter-spacing:-.02em}
.brief-card p{margin:8px 0 0;color:#D6DDF0;font-size:12px;line-height:1.5}
#attentionCard[data-tone="warning"]{border-color:rgba(245,196,90,.32);background:rgba(245,196,90,.08)}
#attentionCard[data-tone="danger"]{border-color:rgba(255,107,122,.34);background:rgba(255,107,122,.08)}
.progress{height:8px;margin-top:12px;border-radius:999px;background:rgba(255,255,255,.08);overflow:hidden}
.bar{height:100%;width:0;border-radius:inherit;background:linear-gradient(90deg,var(--accent),var(--accent-2));transition:width .22s ease}
.activity-dock{padding:14px 16px 15px;display:flex;flex-direction:column;gap:10px}
.activity-head{display:flex;align-items:flex-end;justify-content:space-between;gap:16px}
.activity-head strong{display:block;font-size:14px;margin-top:5px}
.last-log{max-width:65%;font-size:12px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ticker{position:relative;overflow:hidden}
.tk-track{display:flex;gap:8px;overflow-x:auto;scrollbar-width:none;padding-bottom:1px}
.tk-track::-webkit-scrollbar{display:none}
.tk-item{
flex-shrink:0;
display:inline-flex;
align-items:center;
gap:7px;
min-height:30px;
padding:0 11px;
border-radius:999px;
border:1px solid var(--line);
background:rgba(255,255,255,.045);
color:#DCE3F3;
font-size:11px;
}
.tk-item.tk-ok{border-color:rgba(53,215,164,.26)}
.tk-item.tk-warn{border-color:rgba(245,196,90,.28)}
.tk-item.tk-err{border-color:rgba(255,107,122,.3)}
.tk-item .tk-agent{color:#C6BEFF;font-weight:650}
.ctx-menu{position:fixed;z-index:1000;background:rgba(10,14,24,.96);border:1px solid var(--line-strong);border-radius:14px;box-shadow:0 18px 48px rgba(0,0,0,.5);padding:6px;min-width:180px;font-size:12px;color:var(--text)}
.ctx-menu-head{padding:7px 10px 8px;font-size:10px;color:var(--muted);border-bottom:1px solid var(--line);margin-bottom:4px}
.ctx-menu-head .cmh-role{color:var(--role-color,#A78BFA);font-weight:700;text-transform:uppercase}
.ctx-menu-item{display:flex;align-items:center;gap:8px;padding:8px 10px;cursor:pointer;border-radius:10px;transition:background .12s ease}
.ctx-menu-item:hover{background:rgba(138,124,255,.16)}
.ctx-menu-item.danger:hover{background:rgba(255,107,122,.14);color:#FFC3CC}
.ctx-menu-divider{height:1px;background:var(--line);margin:4px}
body[data-edit-mode="true"] .ctx-menu{display:none!important}
body:not([data-edit-mode="true"]) .char{cursor:pointer}
.ctx-detail{position:fixed;z-index:1001;background:rgba(10,14,24,.96);border:1px solid var(--line-strong);border-radius:18px;box-shadow:0 20px 56px rgba(0,0,0,.56);padding:18px;color:var(--text);min-width:320px;max-width:520px;max-height:60vh;overflow-y:auto;font-size:12px;line-height:1.5}
.ctx-detail h3{margin:0 0 10px;font-size:14px;color:var(--role-color,#A78BFA);letter-spacing:.02em}
.ctx-detail .cd-close{position:absolute;top:10px;right:12px;background:transparent;border:none;color:var(--muted);font-size:16px;cursor:pointer}
.ctx-detail dl{margin:0;display:grid;grid-template-columns:auto 1fr;gap:4px 14px}
.ctx-detail dt{color:var(--muted);font-weight:600;white-space:nowrap}
.ctx-detail dd{margin:0;color:var(--text);overflow-wrap:anywhere}
.ctx-detail .cd-logs{margin-top:10px;padding:8px 10px;background:rgba(255,255,255,.045);border-radius:12px;font-family:ui-monospace,monospace;font-size:10.5px;max-height:120px;overflow-y:auto}
.prop-panel{position:absolute;right:14px;top:14px;width:250px;background:rgba(10,14,24,.96);border:1px solid var(--line-strong);border-radius:18px;box-shadow:0 18px 48px rgba(0,0,0,.5);padding:14px;font-size:11px;color:var(--text);z-index:25;display:none}
.prop-panel.show{display:block}
.prop-panel h4{margin:0 0 10px;font-size:12px;color:#C6BEFF;letter-spacing:.04em}
.prop-panel .pp-row{margin-bottom:9px}
.prop-panel label{display:block;font-size:10px;color:var(--muted);margin-bottom:4px}
.prop-panel select,.prop-panel input{width:100%;background:rgba(255,255,255,.04);color:var(--text);border:1px solid var(--line);border-radius:10px;padding:6px 8px;font-size:11px}
.prop-panel .pp-thumbs{display:grid;grid-template-columns:repeat(4,1fr);gap:5px;margin-top:5px}
.prop-panel .pp-thumb{width:100%;aspect-ratio:1/1;background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:3px}
.prop-panel .pp-thumb img{max-width:100%;max-height:100%;image-rendering:pixelated}
.prop-panel .pp-thumb.active{border-color:rgba(138,124,255,.7);box-shadow:0 0 0 2px rgba(138,124,255,.18)}
.prop-picker{position:fixed;inset:0;background:rgba(3,5,10,.68);z-index:1100;display:flex;align-items:center;justify-content:center}
.prop-picker-box{background:rgba(10,14,24,.98);border:1px solid var(--line-strong);border-radius:20px;padding:16px;max-width:380px;max-height:80vh;overflow-y:auto;color:var(--text)}
.prop-picker-box h3{margin:0 0 12px;font-size:13px;color:#C6BEFF}
.prop-picker-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.prop-pick{background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:14px;padding:7px;cursor:pointer;text-align:center}
.prop-pick:hover{border-color:rgba(138,124,255,.6)}
.prop-pick img{max-width:60px;max-height:60px;image-rendering:pixelated}
.prop-pick .pp-name{font-size:10px;color:var(--muted);margin-top:5px;word-break:keep-all}
body[data-edit-mode="true"] .stage{background-image:linear-gradient(rgba(138,124,255,.18) 1px,transparent 1px),linear-gradient(90deg,rgba(138,124,255,.18) 1px,transparent 1px);background-size:32px 32px}
body[data-edit-mode="true"] .desk,body[data-edit-mode="true"] .char,body[data-edit-mode="true"] .obj{cursor:grab;outline:1px dashed rgba(138,124,255,.45)}
body[data-edit-mode="true"] .desk:hover,body[data-edit-mode="true"] .char:hover,body[data-edit-mode="true"] .obj:hover{outline:2px solid rgba(138,124,255,.8);z-index:30}
body[data-edit-mode="true"] .dragging{cursor:grabbing!important;opacity:.72;outline:2px solid var(--warning)!important;z-index:40}
body[data-edit-mode="true"] .selected{outline:2px solid #F472B6!important;box-shadow:0 0 0 4px rgba(244,114,182,.22);z-index:35}
body[data-edit-mode="true"] .char .shadow{display:none}
@media (max-width:1180px){
.workspace{grid-template-columns:220px minmax(560px,1fr)}
.mission-panel{display:none}
}
@media (max-width:900px){
body{overflow:auto}
.office-app{height:auto;min-height:100vh;grid-template-rows:auto auto auto auto;padding:14px}
.topbar{flex-wrap:wrap}
.topbar-center{order:3;width:100%;justify-content:flex-start}
.workspace{grid-template-columns:1fr}
.team-panel{display:none}
.mission-panel{display:block}
.office-shell{min-height:620px}
.mission-title{max-width:calc(100vw - 140px)}
}
@media (prefers-reduced-motion: reduce){
*,*::before,*::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important;scroll-behavior:auto!important}
}
`;
@@ -1,26 +0,0 @@
// Full Astra Office webview HTML composition.
// 옛 sidebarProvider.ts 의 거대한 _pixelOfficePanelHtml 을 4개 파일로 분리한 entry.
// 이번 세션은 *동작 동등 분리* 만. 다음 세션에 mini view 와 공통 presenter 도입.
import { OFFICE_CSS } from './officeStyles';
import { OFFICE_BODY } from './officeBody';
import { officeRuntimeJs } from './runtime';
export interface AstraOfficePanelAssets {
cspSource: string;
derivedBase: string;
}
export function renderAstraOfficePanelHtml(assets: AstraOfficePanelAssets): string {
return `<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${assets.cspSource} data:; style-src 'unsafe-inline'; script-src 'unsafe-inline';" />
<style>
${OFFICE_CSS}
</style></head>
<body>
${OFFICE_BODY}
${officeRuntimeJs(assets.derivedBase)}</body></html>`;
}
File diff suppressed because it is too large Load Diff
-7
View File
@@ -104,10 +104,3 @@ export {
export type { QuestionEvidence, SelfAnswer } from './alignmentResearch';
export type { RequirementContract } from './types';
export {
getStatusBubbleText, getEventBubbleText, eventBubbleType, makeBubble,
} from './pixelOfficeState';
export type {
AgentStatus, AgentEvent, AgentBubble, AgentWorkState,
PixelOfficeConfig, BubbleType,
} from './pixelOfficeState';
-286
View File
@@ -1,286 +0,0 @@
/**
* Pixel Office — Agent Work Pipeline 상태를 시각화하는 *UI Layer 전용* 모듈.
*
* ─────────────────── 설계 원칙 ───────────────────
* 1. **Agent 핵심 판단 로직을 절대 바꾸지 않는다.** Pipeline 진행, contract
* 합의, 검수 cycle, 승인 게이트 — 모두 기존 dispatcher / chatHandlers /
* SidebarChatProvider 안에서 결정된다. 이 모듈은 그 결정을 *읽고* webview용
* 상태 객체로 변환할 뿐이다.
* 2. 입력은 기존에 emit되던 이벤트 (CompanyTurnEvent + alignment phase +
* intent classifier 결과)뿐. 새로운 인터럽트 포인트를 만들지 않는다.
* 3. 출력은 두 종류 — `AgentWorkState` (현재 작업 패널)와 `AgentBubble` 큐
* (말풍선 연출). 둘 다 webview가 그대로 받아 그리기만 하면 된다.
*
* 즉 dispatcher 안의 어떤 한 줄도 "if pixelOffice ..."로 분기하지 않는다.
*/
/** Agent의 현재 단계. 사용자가 명세한 11개 상태값 전부 포함. */
export type AgentStatus =
| 'idle'
| 'intake'
| 'analyzing'
| 'need_clarification'
| 'contract_ready'
| 'planning'
| 'executing'
| 'reviewing'
| 'waiting_approval'
| 'error'
| 'done';
/** 말풍선이 어떤 카테고리에서 나왔는지 — 스타일링 / 우선순위에 활용. */
export type BubbleType = 'status' | 'event' | 'warning' | 'error' | 'success';
/** 말풍선 발생 트리거가 되는 이벤트 — 사용자가 명세한 10개 + 약간 확장. */
export type AgentEvent =
| 'missing_required_info'
| 'clarification_needed'
| 'requirement_contract_created'
| 'plan_completed'
| 'execution_started'
| 'review_failed'
| 'review_passed'
| 'risky_change_detected'
| 'approval_required'
| 'error_occurred'
| 'task_completed'
| 'stage_loop_retry';
export interface AgentWorkState {
agentId: string;
agentName: string;
status: AgentStatus;
/** 사용자 원본 요청 한 줄 — 패널 상단 "Current Task"에 표시. */
currentTask?: string;
/** 현재 stage / phase 라벨 — "기획 논의", "QA 진행" 등. */
currentStep?: string;
/** 다음 stage 라벨 (있으면) — 예측 표시용. */
nextStep?: string;
/** 짧은 보조 메시지 (예: "라운드 2/3", "검수자: 민지"). */
message?: string;
/** 진행률 0~1 — 파이프라인 모드일 때 stage index / total로 계산. */
progress?: number;
/** Requirement Contract 요약 (alignment 완료 후 채워짐). */
requirementContract?: {
goal?: string;
context?: string;
criteria?: string[];
format?: string;
openQuestions?: string[];
confidence?: 'low' | 'medium' | 'high';
};
/** 사용자에게 던지는 미해결 질문 목록 — need_clarification 상태에서 채움. */
needUserInput?: string[];
/** 승인 대기 중 항목 — waiting_approval 상태에서 채움. */
awaitingApproval?: string;
/** 짧은 최근 로그 — 사용자가 한눈에 흐름 파악. 최대 6개 ring buffer. */
recentLogs?: string[];
/**
* 파이프라인 미니 맵용 stage 리스트. `plan-ready` 시점에 채워지고 agent-start/
* agent-done 으로 상태가 갱신된다. webview는 이 리스트를 dot strip 으로 렌더.
* - status: 'done' | 'active' | 'pending'
*/
pipelineStages?: Array<{ label: string; agent?: string; status: 'done' | 'active' | 'pending' }>;
/** epoch ms — webview의 "n초 전" 표시용. */
updatedAt: number;
}
export interface AgentBubble {
id: string;
/** 어떤 캐릭터 위에 띄울지 — 단일 캐릭터 모드면 'main' 고정도 가능. */
agentId: string;
text: string;
type: BubbleType;
/** 생성 시각 epoch ms. */
createdAt: number;
/** 자동 사라짐 ms (webview가 사용). 기본값은 webview에서 결정. */
durationMs?: number;
}
/**
* 사용자가 설정으로 켜고 끌 수 있는 행동 옵션.
* webview는 broadcast마다 같이 받아서 즉시 반영.
*/
export interface PixelOfficeConfig {
enabled: boolean;
bubblesEnabled: boolean;
maxVisibleBubbles: number;
bubbleDurationMs: number;
}
// ─────────────────── 상태→말풍선 텍스트 풀 ───────────────────
// 사용자가 명세한 톤(가벼운 사무실 코미디) 유지. 무작위 선택을 위해 같은 상태에
// 여러 안을 두되 너무 길어지지 않게 4~5개로 제한.
const STATUS_BUBBLE_POOL: Record<AgentStatus, string[]> = {
idle: [
'오늘은 무슨 일을 할까?',
'주문 대기 중…',
'커피 한 잔 더 하고 시작할까.',
],
intake: [
'요청서 들어왔다.',
'한번 읽어보자.',
'오케이, 뭘 원하시는지 보자.',
],
analyzing: [
'음… 의도가 조금 모호한데?',
'맥락부터 정리해보자.',
'핵심이 뭐였더라.',
'이거 작업 범위가 어디까지지?',
],
need_clarification: [
'이건 사용자 확인이 먼저야.',
'질문 하나만 하고 가자.',
'추측으로 가면 위험해.',
'핵심 정보가 빠졌네.',
],
contract_ready: [
'좋아, 작업 조건 정리 완료.',
'이제 방향은 잡혔어.',
'계약서 도장 찍었다.',
'이제 진짜 시작.',
],
planning: [
'순서부터 잡아보자.',
'기존 기능은 건드리지 말자.',
'화이트보드 좀 빌릴게.',
'단계 나눠서 가자.',
],
executing: [
'코드 들어간다.',
'이번엔 단순하게 가자.',
'집중 모드 진입.',
'키보드 워밍업 완료.',
],
reviewing: [
'잠깐, 이건 다시 보자.',
'기존 기능 깨지는지 확인해야 해.',
'검수자 시점으로 한 번 더.',
'엣지 케이스 빠진 거 없나.',
],
waiting_approval: [
'이건 승인 없이 못 바꿔.',
'위험 작업 감지. 확인 필요!',
'사장님 결재 부탁드립니다.',
'도장 받기 전엔 멈춤.',
],
error: [
'앗, 이건 예상 못 했는데…',
'조건 하나 놓쳤네.',
'잠깐, 다시 정리.',
'엇, 이게 깨졌네.',
],
done: [
'좋아, 끝났다!',
'이번 작업 깔끔하게 완료.',
'커피 한 잔.',
'오늘치 끝!',
],
};
const EVENT_BUBBLE_POOL: Record<AgentEvent, string[]> = {
missing_required_info: [
'핵심 정보가 빠졌어.',
'이거 빠지면 추측해야 해.',
],
clarification_needed: [
'질문 하나만.',
'확실하지 않으면 먼저 물어보자.',
],
requirement_contract_created: [
'계약서 도장 찍었다.',
'이제 방향은 잡혔어.',
],
plan_completed: [
'계획 정리 끝!',
'순서대로 가자.',
],
execution_started: [
'코드 들어간다.',
'시작!',
],
review_failed: [
'조건 하나 놓쳤네. 다시 보자.',
'너무 복잡하게 가는 거 아냐?',
],
review_passed: [
'검수 통과!',
'셋 다 만족이래.',
],
risky_change_detected: [
'잠깐, 이건 승인 필요!',
'파일 삭제는 함부로 하면 안 돼.',
],
approval_required: [
'결재 부탁드립니다.',
'도장 받고 이어 갈게.',
],
error_occurred: [
'앗, 이건 예상 못 했는데…',
'엇, 이게 깨졌네.',
],
task_completed: [
'좋아, 끝났다!',
'오늘치 끝.',
],
stage_loop_retry: [
'한 번 더 가자.',
'버그 잡고 다시 시도.',
],
};
/**
* 텍스트 풀에서 하나 뽑기. 같은 결과가 연달아 나오지 않게 lastPicked를
* 받아 회피. 풀이 1개뿐이면 어쩔 수 없이 그걸 반환.
*/
export function pickBubbleText(pool: string[], lastPicked?: string): string {
if (!pool || pool.length === 0) return '';
if (pool.length === 1) return pool[0];
let candidates = pool;
if (lastPicked) candidates = pool.filter((s) => s !== lastPicked);
if (candidates.length === 0) candidates = pool;
return candidates[Math.floor(Math.random() * candidates.length)];
}
export function getStatusBubbleText(status: AgentStatus, lastPicked?: string): string {
return pickBubbleText(STATUS_BUBBLE_POOL[status] ?? [], lastPicked);
}
export function getEventBubbleText(event: AgentEvent, lastPicked?: string): string {
return pickBubbleText(EVENT_BUBBLE_POOL[event] ?? [], lastPicked);
}
/** 이벤트 → 말풍선 type 매핑. 색상/스타일을 webview가 결정할 때 사용. */
export function eventBubbleType(event: AgentEvent): BubbleType {
switch (event) {
case 'error_occurred': return 'error';
case 'review_failed':
case 'risky_change_detected':
case 'missing_required_info':
return 'warning';
case 'task_completed':
case 'review_passed':
case 'plan_completed':
case 'requirement_contract_created':
return 'success';
default: return 'event';
}
}
/** AgentBubble factory — id 자동 생성. */
export function makeBubble(opts: {
agentId: string;
text: string;
type?: BubbleType;
durationMs?: number;
}): AgentBubble {
return {
id: `b-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
agentId: opts.agentId,
text: opts.text,
type: opts.type ?? 'status',
createdAt: Date.now(),
durationMs: opts.durationMs,
};
}
+159
View File
@@ -0,0 +1,159 @@
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
/**
* NotebookLM 로컬 백엔드(Datacollect Bridge) 원클릭 실행/종료.
*
* 배경: Datacollector 의 Research(NotebookLM) 기능은 NAS 브리지로 처리할 수 없다 —
* 로그인된 로컬 Chrome 세션과 PC 의 LM Studio(127.0.0.1) 프록시가 필요해서
* Datacollector 프론트가 리서치 요청을 localhost:3002 로 하드코딩해 보낸다.
* 그동안 사용자가 터미널에서 `npm run bridge` 를 직접 실행해야 했는데, 터미널이
* 익숙지 않은 사용자를 위해 사이드바 도구 메뉴의 버튼 두 개로 감쌌다.
*
* 설계:
* - 실행은 VS Code 통합 터미널("NotebookLM Bridge")에서 `npm run bridge` 를 돌린다.
* → 맥/윈도우 셸 차이를 VS Code 가 흡수하고(별도 OS 분기 불필요), 사용자가
* 브리지 로그(인증 만료 안내 등)를 그대로 볼 수 있으며, 종료 = 터미널 dispose.
* - 프로젝트 폴더는 설정(g1nation.datacollectLocalProjectPath) 우선, 비어 있으면
* 워크스페이스 폴더·부모·형제에서 자동 탐색. 못 찾으면 폴더 선택 대화상자 제공.
* - 종료는 우리 터미널 dispose + (버튼 밖에서 띄운 프로세스 대비) 포트 점유
* 프로세스를 OS별 명령으로 best-effort 정리한다 — 이 부분만 OS 자동 감지 분기.
*/
const TERMINAL_NAME = 'NotebookLM Bridge';
const BRIDGE_PORT = 3002;
/** 자동 탐색 시 찾는 프로젝트 폴더 이름 후보 (맥/윈도우 클론 이름이 다를 수 있음). */
const PROJECT_DIR_NAMES = ['Datacollector_MAC', 'Datacollector', 'Datacollect'];
/** 이 파일이 있어야 브리지 프로젝트로 인정. */
const BRIDGE_SCRIPT_REL = path.join('scripts', 'mcp_bridge.mjs');
/**
* 브리지 프로젝트 후보 경로를 우선순위대로 나열한다 (존재 검증은 안 함 — 테스트 가능한 순수 함수).
* 우선순위: 설정값 → 각 워크스페이스 폴더 자신 → 그 부모 아래 형제 폴더들.
*/
export function candidateProjectDirs(cfgPath: string, workspaceDirs: string[]): string[] {
const out: string[] = [];
const push = (p: string) => { if (p && !out.includes(p)) out.push(p); };
if (cfgPath && cfgPath.trim()) push(cfgPath.trim());
for (const ws of workspaceDirs) {
push(ws); // 워크스페이스가 곧 Datacollector 프로젝트인 경우
const parent = path.dirname(ws);
for (const name of PROJECT_DIR_NAMES) push(path.join(parent, name));
}
return out;
}
/** 포트를 점유한 프로세스를 죽이는 OS별 셸 명령 (순수 함수 — 테스트 대상). */
export function buildPortKillCommand(platform: NodeJS.Platform, port: number): string {
if (platform === 'win32') {
// PowerShell: 해당 포트 LISTEN 프로세스를 강제 종료. (netstat 파싱보다 안전)
return `powershell -NoProfile -Command "Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }"`;
}
// macOS / Linux
return `lsof -ti :${port} | xargs kill 2>/dev/null`;
}
function findBridgeProject(): string | null {
const cfgPath = vscode.workspace.getConfiguration('g1nation').get<string>('datacollectLocalProjectPath', '') || '';
const wsDirs = (vscode.workspace.workspaceFolders || [])
.filter(f => f.uri.scheme === 'file')
.map(f => f.uri.fsPath);
for (const dir of candidateProjectDirs(cfgPath, wsDirs)) {
try {
if (fs.existsSync(path.join(dir, BRIDGE_SCRIPT_REL))) return dir;
} catch { /* 접근 불가 경로 — skip */ }
}
return null;
}
/** 브리지 생존 확인 — 어떤 HTTP 응답이든(404 포함) 살아 있는 것. */
async function isBridgeAlive(): Promise<boolean> {
try {
await fetch(`http://127.0.0.1:${BRIDGE_PORT}/`, { signal: AbortSignal.timeout(1500) });
return true;
} catch {
return false;
}
}
function findOurTerminal(): vscode.Terminal | undefined {
return vscode.window.terminals.find(t => t.name === TERMINAL_NAME);
}
export async function startNotebookLmBridge(): Promise<void> {
if (await isBridgeAlive()) {
findOurTerminal()?.show(true);
vscode.window.showInformationMessage('NotebookLM 백엔드가 이미 실행 중입니다 (포트 3002 응답 확인).');
return;
}
let projectDir = findBridgeProject();
if (!projectDir) {
// 자동 탐색 실패 — 비개발자도 해결할 수 있게 폴더 선택 대화상자를 제공한다.
const pick = await vscode.window.showErrorMessage(
'Datacollector 프로젝트 폴더를 찾지 못했습니다. 폴더를 직접 선택하면 설정에 저장되어 다음부터는 버튼만 누르면 됩니다.',
'폴더 선택'
);
if (pick !== '폴더 선택') return;
const chosen = await vscode.window.showOpenDialog({
canSelectFiles: false, canSelectFolders: true, canSelectMany: false,
openLabel: 'Datacollector 폴더 선택',
});
const dir = chosen?.[0]?.fsPath;
if (!dir) return;
if (!fs.existsSync(path.join(dir, BRIDGE_SCRIPT_REL))) {
vscode.window.showErrorMessage(`선택한 폴더에 ${BRIDGE_SCRIPT_REL} 가 없습니다 — Datacollector 프로젝트 폴더가 맞는지 확인하세요.`);
return;
}
await vscode.workspace.getConfiguration('g1nation')
.update('datacollectLocalProjectPath', dir, vscode.ConfigurationTarget.Global);
projectDir = dir;
}
// 기존 우리 터미널이 남아 있으면 재사용하지 않고 정리 후 새로 연다 (죽은 셸 방지).
findOurTerminal()?.dispose();
const terminal = vscode.window.createTerminal({ name: TERMINAL_NAME, cwd: projectDir });
terminal.show(true);
terminal.sendText('npm run bridge');
vscode.window.showInformationMessage(
'NotebookLM 백엔드를 시작했습니다 — 준비까지 몇 초 걸릴 수 있어요. (로그는 "NotebookLM Bridge" 터미널에서 확인)'
);
}
export async function stopNotebookLmBridge(): Promise<void> {
const term = findOurTerminal();
if (term) term.dispose();
// 터미널 밖(예전 수동 실행 등)에서 뜬 프로세스까지 정리 — 포트 점유 시 OS별 명령으로 kill.
await new Promise(r => setTimeout(r, 600)); // 터미널 dispose 가 프로세스를 정리할 시간
if (await isBridgeAlive()) {
try {
await execAsync(buildPortKillCommand(process.platform, BRIDGE_PORT), { timeout: 8000 });
} catch { /* 이미 죽었거나 권한 문제 — 아래 재확인으로 판정 */ }
}
if (await isBridgeAlive()) {
vscode.window.showWarningMessage('NotebookLM 백엔드가 아직 응답합니다 — 다른 프로그램이 포트 3002 를 쓰고 있을 수 있습니다.');
} else {
vscode.window.showInformationMessage('NotebookLM 백엔드를 종료했습니다.');
}
}
/** 사이드바 웹뷰 메시지 핸들러 — sidebarProvider 의 핸들러 체인에 등록된다. */
export async function handleBridgeLauncherMessage(_provider: unknown, data: any): Promise<boolean> {
switch (data?.type) {
case 'startNotebookLmBridge':
await startNotebookLmBridge();
return true;
case 'stopNotebookLmBridge':
await stopNotebookLmBridge();
return true;
default:
return false;
}
}
@@ -159,6 +159,18 @@ function _extractPathFromReportLine(line: string): string | null {
* @param projectRoot 현재 워크스페이스 루트 (cwd로 사용)
* @returns 추가 report 라인 (없으면 빈 배열 — 검증 대상 파일 없음)
*/
/**
* [실행 루프] 문법 검증 실패 라인들을 모델이 즉시 수정하도록 하는 재주입 메시지.
* agent 가 이 메시지를 internal system 으로 chatHistory 에 넣으면 자동 후속 턴이 돌아
* <edit_file> 수정 → 다음 라운드 재검증의 자가수정 루프가 성립한다 (maxAutoSteps 한도).
*/
export function buildSyntaxFixInstruction(failLines: string[]): string {
return `[Result of execution check — SYNTAX ERRORS]
${failLines.join('\n')}
위 파일이 문법 검증에 실패했다. 지금 즉시 <edit_file> 로 오류를 수정하라 (수정하면 자동으로 재검증된다). 원인이 불명확하면 먼저 <read_file> 로 해당 파일을 읽어라. 사용자에게 수동 수정을 요구하지 마라.`;
}
export async function verifyCreatedFiles(report: string[], projectRoot: string): Promise<string[]> {
const candidates: string[] = [];
for (const line of report) {
+27 -1
View File
@@ -93,6 +93,7 @@ interface SettingsState {
chunkedMaxSections: number;
polishPersonaOverride: string;
};
domainKnowledge: { general: string; math: string; coding: string; facts: string };
datacollect: {
/** 'local' | 'nas' — 어느 Bridge 인스턴스를 호출할지. */
bridgeTarget: string;
@@ -206,7 +207,9 @@ export class SettingsPanelProvider implements vscode.WebviewViewProvider {
SettingsPanelProvider.viewType,
'Astra Settings',
column,
{ enableScripts: true, localResourceRoots: [this._deps.extensionUri], retainContextWhenHidden: true }
// [메모리 개선] retainContextWhenHidden 제거 — 재표시 시 웹뷰 JS 가 'ready' 를 보내
// 상태를 다시 받아오고 활성 탭도 getState() 로 복원하므로, 숨김 동안 렌더러 상주가 불필요.
{ enableScripts: true, localResourceRoots: [this._deps.extensionUri] }
);
this._panel = panel;
this._setupWebview(panel.webview);
@@ -281,6 +284,9 @@ export class SettingsPanelProvider implements vscode.WebviewViewProvider {
case 'datacollect.update':
await this._handleDatacollectUpdate(msg);
return;
case 'domainKnowledge.update':
await this._handleDomainKnowledgeUpdate(msg);
return;
case 'google.update':
await this._handleGoogleUpdate(msg);
return;
@@ -656,6 +662,20 @@ export class SettingsPanelProvider implements vscode.WebviewViewProvider {
}
/** [단계별 지식 스코프] 도메인별 지식 폴더 설정 저장 — 필드별 부분 업데이트. */
private async _handleDomainKnowledgeUpdate(msg: any): Promise<void> {
const keys: Array<[string, string]> = [
['general', 'domainKnowledge.generalFolder'],
['math', 'domainKnowledge.mathFolder'],
['coding', 'domainKnowledge.codingFolder'],
['facts', 'domainKnowledge.factsFolder'],
];
for (const [field, cfgKey] of keys) {
if (typeof msg[field] === 'string') await this._safeConfigUpdate(cfgKey, msg[field].trim());
}
await this._refreshState();
}
private async _handleDatacollectUpdate(msg: any): Promise<void> {
if (typeof msg.bridgeTarget === 'string') {
const t = msg.bridgeTarget.trim() === 'nas' ? 'nas' : 'local';
@@ -745,6 +765,12 @@ export class SettingsPanelProvider implements vscode.WebviewViewProvider {
chunkedMaxSections: cfg.get<number>('chunkedMaxSections', 3) ?? 3,
polishPersonaOverride: cfg.get<string>('polishPersonaOverride', '') ?? '',
},
domainKnowledge: {
general: cfg.get<string>('domainKnowledge.generalFolder', '') || '',
math: cfg.get<string>('domainKnowledge.mathFolder', '') || '',
coding: cfg.get<string>('domainKnowledge.codingFolder', '') || '',
facts: cfg.get<string>('domainKnowledge.factsFolder', '') || '',
},
datacollect: {
bridgeTarget: cfg.get<string>('datacollectBridgeTarget', 'local') || 'local',
bridgeUrl: cfg.get<string>('datacollectBridgeUrl', '') || '',