Compare commits

...
5 Commits
Author SHA1 Message Date
kimandClaude Sonnet 5.5 f088720427 tests/model-routing.test.ts: 어려운 질문만 hard_model로, provider가 맞을 때만
decideRoute가 심층분석·수학·코드설계·긴 입력 턴만 hard_model로 보내고, routing.provider가 활성 provider와 같을 때만 라우팅하는지 확인한다.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:08:04 +09:00
kimandClaude Sonnet 5.5 672443b738 scripts/resume-log.sh: 절전에서 깨어난 직후 "누가 깨웠나" 단서 기록
logind의 PrepareForSleep 신호를 듣고(루트 불필요), 잠들기 직전 깨우기 장치 카운터를 저장했다가 깨어난 직후 늘어난 장치·IRQ·이웃 테이블·커널의 깨우기 관련 줄을 ~/wake-watch/resume.log에 남긴다. 10-30 z840 WOL 문제(I210은 못 깨우고 eno1은 깨움) 분석에 쓰였다.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:08:04 +09:00
kimandClaude Sonnet 5.5 70bd05404c SCAD 뷰어: 반투명 토글 — 안쪽 부품·배선이 비치게
"반투명" 버튼과 투명도 슬라이더(20~100%). 선택은 localStorage에 기억(접근 불가여도 동작).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:08:04 +09:00
kimandClaude Sonnet 5.5 5c972b70c4 작업실에 PCB 탭 — 작업실 프로젝트에 연결된 PCB 프로젝트를 iframe으로
- PCB 프로젝트 목록(`/api/pcb/projects`)에 workshopId를 포함(project.json의 workshopId).
- 작업실 화면에 "🔌 PCB" 탭: 이 작업실 프로젝트와 workshopId가 같은 PCB 프로젝트가 있으면 그걸(`?p=`), 없으면 마지막으로 연 것을 pcb-app.html로 띄운다.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:08:04 +09:00
kimandClaude Sonnet 5.5 73f0c89a98 조립 설명서: 단계별 시점(step.view) — 단계마다 각도·확대·중심을 지정
앞면 센서 단계처럼 설명서 전체 시점으로는 안 보이는 단계를 위해 단계마다 view{rx?, rz, zoom?, center?}를 줄 수 있게 한다.
- normalizeAssembly: rz −360~360, rx 0~90, zoom 1~4(1 이하는 버림), center 3개 숫자(−1000~1000). 잘못된 값은 버린다. assemblyHash에 view가 들어가 그림 캐시가 시점 바뀌면 갱신된다.
- 렌더: 단계 view가 있으면 fitCamera로 그 각도, 확대는 카메라 거리를 zoom으로 나누고 center를 화면 가운데로(ortho라 거리=배율). 단계의 완성·이전·부품별 차이 이미지가 같은 시점을 쓴다.
- tests/workshop-assembly.test.ts: 보존·범위 제한·해시 반영·잘못된 값 폐기.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 00:08:04 +09:00
9 changed files with 153 additions and 8 deletions

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
# 절전에서 깨어난 직후 "누가 깨웠나" 단서를 기록한다. 루트 없이 logind의 PrepareForSleep 신호만 듣는다.
# 잠들기 직전에 깨우기 장치 카운터를 저장해 두고, 깨어난 직후 늘어난 장치와 IRQ·이웃 테이블을 남긴다.
LOG=/home/kim/wake-watch/resume.log
mkdir -p "$(dirname "$LOG")"
snap() {
for w in /sys/class/wakeup/wakeup*; do
[ -r "$w/name" ] || continue
echo "$(cat "$w/name")|$(cat "$w/wakeup_count" 2>/dev/null)|$(cat "$w/event_count" 2>/dev/null)|$(cat "$w/active_count" 2>/dev/null)"
done
}
PRE=""
gdbus monitor --system --dest org.freedesktop.login1 --object-path /org/freedesktop/login1 2>/dev/null |
while read -r line; do
case "$line" in
*PrepareForSleep*true*) PRE=$(snap); SLEPT=$(date +%s) ;;
*PrepareForSleep*false*)
sleep 3 # 깨어난 직후 장치가 올라오길 잠깐 기다림
{
echo "=== 깨어남 $(date '+%F %T') (잠든 시각 $( [ -n "$SLEPT" ] && date -d @"$SLEPT" '+%T' || echo ?))"
echo "wakeup_irq: $(cat /sys/power/pm_wakeup_irq 2>&1)"
irq=$(cat /sys/power/pm_wakeup_irq 2>/dev/null); [ -n "$irq" ] && grep -E "^ *$irq:" /proc/interrupts | cut -c1-160
echo "-- 늘어난 깨우기 장치 (이름: 이전→이후, wakeup_count/event/active)"
NOW=$(snap)
diff <(echo "$PRE") <(echo "$NOW") | grep '^[<>]' | sed 's/^/ /'
echo "-- 이웃 테이블(최근 접촉)"
ip -s neigh show 2>/dev/null | grep -E "REACHABLE|DELAY|PROBE" | head -8 | sed 's/^/ /'
echo "-- 커널 최근 로그(깨우기 관련)"
journalctl -k --since "-20s" --no-pager 2>/dev/null | grep -iE "wake|wol|magic|pme|usb.*(connect|new)|button" | head -6 | sed 's/^/ /'
} >> "$LOG"
;;
esac
done
+14 -1
View File
@@ -30,6 +30,8 @@ export interface AssemblyStep {
partIds: string[];
fasteners: AssemblyFastener[];
tools: string[];
/** 이 단계 그림만 다른 각도로(예: 앞면 센서 단계는 rz≈215로 앞에서 본다). 생략하면 설명서 전체 view. rx는 생략 가능 */
view?: { rx?: number; rz: number; zoom?: number; center?: [number, number, number] };
}
export interface Assembly {
/** 워크스페이스 기준 상대경로의 .scad (예: "workshop/proj_x/SCAD/rig.scad") */
@@ -113,6 +115,16 @@ export function normalizeAssembly(input: any, strict = true): { ok: true; assemb
const steps: AssemblyStep[] = [];
for (const st of rawSteps) {
const ids = (Array.isArray(st?.partIds) ? st.partIds : []).filter((x: any) => typeof x === 'string' && partIds.has(x));
const sv = st?.view;
const stepView = sv && Number.isFinite(Number(sv.rz))
? {
...(Number.isFinite(Number(sv.rx)) ? { rx: clampNum(sv.rx, 0, 90, 60) } : {}), rz: clampNum(sv.rz, -360, 360, 35),
// 확대(1~4배)와 확대 중심(mm). 확대하면 전체 bbox 중심 대신 center를 화면 가운데로 — 몸통만 크게 볼 때 쓴다
...(Number.isFinite(Number(sv.zoom)) && Number(sv.zoom) > 1 ? { zoom: clampNum(sv.zoom, 1, 4, 1) } : {}),
...(Array.isArray(sv.center) && sv.center.length === 3 && sv.center.every((v: any) => Number.isFinite(Number(v)))
? { center: sv.center.map((v: any) => clampNum(v, -1000, 1000, 0)) as [number, number, number] } : {}),
}
: undefined;
steps.push({
id: uniqueId(st?.id, 'as'),
title: str(st?.title, 120) || `단계 ${steps.length + 1}`,
@@ -121,6 +133,7 @@ export function normalizeAssembly(input: any, strict = true): { ok: true; assemb
fasteners: (Array.isArray(st?.fasteners) ? st.fasteners : []).slice(0, ASSEMBLY_LIMITS.fasteners)
.map((f: any) => ({ name: str(f?.name, 80), qty: Math.round(clampNum(f?.qty, 1, 9999, 1)) })).filter((f: AssemblyFastener) => f.name),
tools: (Array.isArray(st?.tools) ? st.tools : []).slice(0, ASSEMBLY_LIMITS.tools).map((t: any) => str(t, 60)).filter(Boolean),
...(stepView ? { view: stepView } : {}),
});
}
@@ -142,7 +155,7 @@ export function assemblyHash(assembly: Assembly, scadSource: string): string {
const spec = {
view: assembly.view, explode: assembly.explode,
parts: assembly.parts.map(p => [p.id, p.name, p.call, p.offset]),
steps: assembly.steps.map(s => [s.id, s.partIds]),
steps: assembly.steps.map(s => [s.id, s.partIds, s.view?.rx ?? null, s.view?.rz ?? null, s.view?.zoom ?? null, s.view?.center ?? null]),
};
return crypto.createHash('sha1').update(scadSource).update(JSON.stringify(spec)).digest('hex').slice(0, 16);
}
+4 -4
View File
@@ -23,17 +23,17 @@ export class PcbProjects {
return d;
}
list(): { name: string; updated: number; parts: number; nets: number; routed: boolean; gcode: boolean }[] {
list(): { name: string; updated: number; parts: number; nets: number; routed: boolean; gcode: boolean; workshopId: string }[] {
if (!fs.existsSync(this.root)) return [];
const out = [];
for (const e of fs.readdirSync(this.root, { withFileTypes: true })) {
if (!e.isDirectory() || e.name.startsWith('.')) continue;
const f = path.join(this.root, e.name, 'project.json');
if (!fs.existsSync(f)) continue;
let parts = 0, nets = 0, routed = false;
try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); parts = j.parts?.length || 0; nets = j.nets?.length || 0; routed = !!(j.routed && j.routed.traces?.length); } catch { /* 깨진 파일은 목록에서 0으로 */ }
let parts = 0, nets = 0, routed = false, workshopId = '';
try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); parts = j.parts?.length || 0; nets = j.nets?.length || 0; routed = !!(j.routed && j.routed.traces?.length); workshopId = String(j.workshopId || ''); } catch { /* 깨진 파일은 목록에서 0으로 */ }
const g = path.join(this.root, e.name, 'gcode');
out.push({ name: e.name, updated: fs.statSync(f).mtimeMs, parts, nets, routed, gcode: fs.existsSync(g) && fs.readdirSync(g).length > 0 });
out.push({ name: e.name, updated: fs.statSync(f).mtimeMs, parts, nets, routed, workshopId, gcode: fs.existsSync(g) && fs.readdirSync(g).length > 0 });
}
return out.sort((a, b) => b.updated - a.updated);
}
+12 -3
View File
@@ -359,14 +359,23 @@ async function doRender(workspace: string, projectId: string, assembly: Assembly
stepFiles.push(name);
continue;
}
const full = await renderSet(items, camA);
// 단계별 각도(step.view)가 있으면 그 각도로(앞면 부품 단계 등), 없으면 전체 view
const sv = assembly.steps[i]?.view;
let camS = sv ? fitCamera(b1.bbox, { rx: sv.rx ?? assembly.view.rx, rz: sv.rz }, { w: IMG_W, h: IMG_H }).camera : camA;
if (sv && (sv.zoom || sv.center)) { // 확대: 카메라 중심을 center로, 거리를 zoom으로 나눔(ortho라 거리=배율)
const c = camS.split(',').map(Number);
if (sv.center) { c[0] = sv.center[0]; c[1] = sv.center[1]; c[2] = sv.center[2]; }
if (sv.zoom) c[6] = Math.round((c[6] / sv.zoom) * 1000) / 1000;
camS = c.join(',');
}
const full = await renderSet(items, camS);
if (!full.ok) return full;
const base = await renderSet(before.map(part => ({ part })), camA);
const base = await renderSet(before.map(part => ({ part })), camS);
if (!base.ok) return base;
const callouts: { n: number; without: string | null }[] = [];
for (const a of added) {
if (added.length === 1) { callouts.push({ n: numberOf.get(a.id)!, without: base.png }); continue; }
const w = await renderSet([...before, ...added.filter(x => x !== a)].map(part => ({ part })), camA);
const w = await renderSet([...before, ...added.filter(x => x !== a)].map(part => ({ part })), camS);
if (!w.ok) return w;
callouts.push({ n: numberOf.get(a.id)!, without: w.png });
}
+46
View File
@@ -0,0 +1,46 @@
/**
* model-routing — 어려운 질문만 hard_model로, provider가 맞을 때만.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { getConfig } from '../src/config/config';
import { decideRoute } from '../src/gateway/chat/model-routing';
function withConfig(cfg: any, fn: () => void) {
const c: any = getConfig();
const orig = c.getConfig;
c.getConfig = () => cfg;
try { fn(); } finally { c.getConfig = orig; }
}
const base = (activeProvider: string, routing: any) => ({ llm: { provider: activeProvider }, models: { routing } });
describe('decideRoute', () => {
test('활성 provider와 routing.provider가 같으면 어려운 질문을 hard_model로', () => {
withConfig(base('anthropic', { enabled: true, provider: 'anthropic', hard_model: 'claude-sonnet-5-5' }), () => {
const r = decideRoute('이 알고리즘 시간 복잡도를 단계별로 따져줘');
assert.equal(r.model, 'claude-sonnet-5-5');
});
});
test('provider가 다르면 라우팅하지 않는다(엉뚱한 백엔드에 모델 이름 금지)', () => {
withConfig(base('anthropic', { enabled: true, provider: 'ollama', hard_model: 'kimi-k2.6:cloud' }), () => {
assert.deepEqual(decideRoute('깊이 분석해줘 이 계약서'), {});
});
});
test('routing.provider가 없는 옛 설정은 ollama로 본다', () => {
withConfig(base('ollama', { enabled: true, hard_model: 'kimi-k2.6:cloud' }), () => {
assert.equal(decideRoute('행렬 고유값 구하는 법').model, 'kimi-k2.6:cloud');
});
withConfig(base('google', { enabled: true, hard_model: 'kimi-k2.6:cloud' }), () => {
assert.deepEqual(decideRoute('행렬 고유값 구하는 법'), {});
});
});
test('실시간 조회 턴·이미지 턴·꺼짐 상태는 제외', () => {
withConfig(base('anthropic', { enabled: true, provider: 'anthropic', hard_model: 'claude-sonnet-5-5' }), () => {
assert.deepEqual(decideRoute('깊이 분석해줘', { skip: true }), {});
assert.deepEqual(decideRoute('깊이 분석해줘', { hasImages: true }), {});
});
withConfig(base('anthropic', { enabled: false, provider: 'anthropic', hard_model: 'claude-sonnet-5-5' }), () => {
assert.deepEqual(decideRoute('깊이 분석해줘'), {});
});
});
});
+18
View File
@@ -66,6 +66,24 @@ describe('명세 정규화', () => {
assert.equal(r.assembly.view.rz, 35);
}
});
test('단계별 view(앞면 센서 단계 등) 보존·범위 제한·해시 반영, 잘못된 값은 버림', () => {
const base = spec();
const withView = normalizeAssembly({ ...base, steps: [{ title: 'a', partIds: ['base'], view: { rz: 215 } }, { title: 'b', partIds: ['base'], view: { rx: 500, rz: -999 } }, { title: 'c', partIds: ['base'], view: { rz: 'x' } }, { title: 'd', partIds: ['base'] }] });
assert.ok(withView.ok);
if (!withView.ok) return;
const st = withView.assembly.steps;
assert.deepEqual(st[0].view, { rz: 215 });
assert.deepEqual(st[1].view, { rx: 90, rz: -360 });
assert.equal(st[2].view, undefined);
assert.equal(st[3].view, undefined);
const without = normalizeAssembly({ ...base, steps: [{ title: 'a', partIds: ['base'] }] });
assert.ok(without.ok);
if (without.ok) {
const h1 = assemblyHash({ ...withView.assembly, steps: [st[0]] }, 'x');
const h2 = assemblyHash(without.assembly, 'x');
assert.notEqual(h1, h2); // 각도가 바뀌면 그림이 오래된 것으로 판정
}
});
test('strict는 잘못된 call 거부, lenient(대시보드 저장)는 미완성 행을 보존', () => {
const bad = { ...spec(), parts: [{ id: 'x', name: '', call: '' }] };
assert.equal(normalizeAssembly(bad).ok, false);
+6
View File
@@ -23,6 +23,7 @@ button.on{background:var(--on);color:#fff;border-color:var(--on)}
<div id="bar">
<b id="ttl">SCAD</b><span id="sz" style="color:var(--muted)"></span><span class="sp"></span>
<button id="bw" onclick="toggleWire()">와이어</button>
<button id="bg" onclick="toggleGlass()" title="안쪽 부품·배선이 비치게 모델을 반투명으로">반투명</button><input id="go" type="range" min="20" max="100" step="5" value="65" oninput="setGlass(this.value)" title="불투명도(%)" style="width:70px;vertical-align:middle;display:none">
<button onclick="resetView()">시점 초기화</button>
<button id="bs" onclick="toggleSpin()">자동 회전</button>
<a class="b" id="src" target="_blank" rel="noopener">&lt;/&gt; 소스</a>
@@ -65,6 +66,10 @@ function resetView(){
camera.near=Math.max(0.01,dist/1000);camera.far=dist*20;camera.updateProjectionMatrix();
controls.target.copy(c);controls.update();
}
let glass=false, glassOp=0.65;
function applyGlass(){ if(!mesh)return; const m=mesh.material; const tr=glass&&glassOp<0.995; m.transparent=tr; m.opacity=tr?glassOp:1; m.depthWrite=!tr; m.needsUpdate=true; mesh.children.forEach(ch=>{ if(ch.isLineSegments){ ch.material.opacity=glass?0.08:0.35; ch.material.needsUpdate=true; } }); document.getElementById('bg').classList.toggle('on',glass); const g=document.getElementById('go'); g.style.display=glass?'':'none'; g.value=Math.round(glassOp*100); }
function toggleGlass(){ glass=!glass; try{localStorage.setItem('scadViewerGlass',glass?'1':'0');}catch(e){} applyGlass(); }
function setGlass(v){ glassOp=Math.min(1,Math.max(0.2,Number(v)/100)); try{localStorage.setItem('scadViewerGlassOp',String(glassOp));}catch(e){} applyGlass(); }
function toggleWire(){wire=!wire;if(mesh)mesh.material.wireframe=wire;document.getElementById('bw').classList.toggle('on',wire);}
function toggleSpin(){controls.autoRotate=!controls.autoRotate;controls.autoRotateSpeed=2.5;document.getElementById('bs').classList.toggle('on',controls.autoRotate);}
async function load(){
@@ -97,6 +102,7 @@ async function load(){
const bb=geo.boundingBox, size=new THREE.Vector3(); bb.getSize(size);
mesh=new THREE.Mesh(geo,new THREE.MeshStandardMaterial({color:geo.hasColors?0xffffff:0x6aa5e8,vertexColors:!!geo.hasColors,metalness:0.1,roughness:0.55,side:THREE.DoubleSide,flatShading:false}));
scene.add(mesh);
try{glass=localStorage.getItem('scadViewerGlass')==='1'; const o=Number(localStorage.getItem('scadViewerGlassOp')); if(o>=0.2&&o<=1)glassOp=o;}catch(e){} applyGlass(); // 반투명 선택은 기억
const edges=new THREE.LineSegments(new THREE.EdgesGeometry(geo,35),new THREE.LineBasicMaterial({color:0x1d3552,transparent:true,opacity:0.35}));
mesh.add(edges);
const ctr=new THREE.Vector3(); bb.getCenter(ctr);
+3
View File
@@ -53,6 +53,7 @@
<div class="rb-main">
<div class="rb-tabs">
<button class="rb-tab-btn active" data-tab="parts" onclick="switchTab('parts')">부품</button>
<button class="rb-tab-btn" data-tab="pcb" onclick="switchTab('pcb')">🔌 PCB</button>
<button class="rb-tab-btn" data-tab="tasks" onclick="switchTab('tasks')">작업</button>
<button class="rb-tab-btn" data-tab="assembly" onclick="switchTab('assembly')">조립</button>
<button class="rb-tab-btn" data-tab="equip" onclick="switchTab('equip')">장비</button>
@@ -92,6 +93,8 @@
<div class="rb-pane" id="pane-assembly"></div>
<div class="rb-pane" id="pane-pcb"></div>
<div class="rb-pane" id="pane-equip">
<div class="rb-equip-grid">
<div class="rb-equip-card">
+15
View File
@@ -463,6 +463,20 @@ function showSaveIndicator(msg){
saveTimer=setTimeout(()=>{el.textContent='';},2000);
}
// PCB 탭: PCB 앱을 iframe으로 띄운다. 이 작업실 프로젝트에 연결된(workshopId) PCB 프로젝트가 있으면 그걸, 없으면 마지막으로 연 것을 연다.
let pcbPaneFor='';
async function loadPcbPane(){
const pane=document.getElementById('pane-pcb'),proj=currentProject();
if(!pane||!proj||pcbPaneFor===proj.id)return;
let q='';
try{
const r=await fetch('/api/pcb/projects',{headers:authH()});
if(r.ok){const m=((await r.json()).projects||[]).find(x=>x.workshopId===proj.id);if(m)q='?p='+encodeURIComponent(m.name);}
}catch(e){}
pcbPaneFor=proj.id;
pane.innerHTML='<iframe src="/html/pcb-app.html'+q+'" style="width:100%;height:calc(100vh - 140px);border:0" title="PCB"></iframe>';
}
// ── Tabs ──────────────────────────────────────────────────────────────────────
function switchTab(tab){
document.querySelectorAll('.rb-tab-btn').forEach(b=>b.classList.toggle('active',b.dataset.tab===tab));
@@ -473,6 +487,7 @@ function switchTab(tab){
else if(typeof stopEquipTimers==='function')stopEquipTimers();
if(tab==='files')loadFiles();
if(tab==='assembly')refreshAssemblyPane(true);
if(tab==='pcb')loadPcbPane();
// 콘솔 탭(지연 로딩 workshop-console.js): 열 때 터미널 준비, 나갈 때는 세션을 유지한 채 숨김
if(tab==='console')withLazyModule('console','pane-console',()=>openConsole());
else if(typeof closeConsoleTab==='function')closeConsoleTab();