fix: complete HoloLake Agent and Forgejo desktop runtime

This commit is contained in:
冰朔 2026-08-08 10:39:18 +08:00
commit 46bdd0ca73
15 changed files with 1217 additions and 638 deletions

View file

@ -452,3 +452,20 @@ xattr -cr ~/Desktop/"HoloLake Era.app"
- **SSH 密钥**~/.ssh/id_ed25519对应 SG-001
- **Grok Build 源码位置**/Volumes/JZAO/HoloLake/upstream-mirrors/grok-build-upstream.git
- **Forgejo 离线包位置**~/Desktop/光湖代码频道-Forgejo-16.0.1-完整离线包/
---
## 八、DEV-20260808-003 修复回读10:36
本节是对第四节“待修复项”的运行态回读,不改写原始开发思路。
1. `server-bundle.cjs` 已纳入正式构建,生产模式在 Electron 主进程内加载,不再递归启动 Electron。
2. Vite 资源改为相对路径,桌面 `file://` 入口改走 `127.0.0.1:3890`,空白页与 `Failed to fetch` 已消除。
3. Forgejo 已从“预留接口”变成可运行的 Git 远端适配层状态、连接、fetch、仅快进 pull、确认 push没有接入上游自动更新。
4. Agent 已登记 8 个工具,其中 `inspect_repository` 只读查看 Forgejo/Git 状态Agent 不拥有自动推送能力。
5. 模型配置入口已加入桌面 App密钥由 Electron `safeStorage` 加密保存;未配置时明确显示等待状态,不再返回模拟人格回复。
6. 本地 API 只监听 `127.0.0.1`,仅允许本机 `file://` 或 localhost 界面跨域访问。
7. 窗口顶栏已登记为 macOS 可拖动区域;按钮、搜索框保持可交互。
8. 桌面安装包已通过 Developer ID 深度签名校验和真实 UI/API 启动验收;未做 Apple 公证,因此本次是本机开发交付,不代表公开发行。
完整机器回执:`deployment/receipts/GH-HOLOLAKE-DESKTOP-0.5.0-REPAIR-20260808-001.json`

View file

@ -59,6 +59,15 @@ export interface DiffResult {
hunks: { oldStart: number; newStart: number; lines: string[] }[];
}
export interface RepositoryStatus {
branch: string;
head: string;
clean: boolean;
ahead: number;
behind: number;
remote: { name: string; url: string } | null;
}
// ─── Git 引擎 ───
export class GitEngine {
@ -94,6 +103,69 @@ export class GitEngine {
await fs.mkdir(this.docsDir, { recursive: true });
}
// ─── Forgejo 远端仓库 ───
/** 返回本地 Git 与 Forgejo 远端的真实连接状态,不探测或修改网络。 */
async getRepositoryStatus(remoteName = 'origin'): Promise<RepositoryStatus> {
this.assertRemoteName(remoteName);
const [status, remotes, head] = await Promise.all([
this.git.status(),
this.git.getRemotes(true),
this.git.revparse(['HEAD']).catch(() => ''),
]);
const remote = remotes.find(item => item.name === remoteName);
return {
branch: status.current || '未命名分支',
head: head.trim(),
clean: status.isClean(),
ahead: status.ahead,
behind: status.behind,
remote: remote ? { name: remote.name, url: this.redactRemoteUrl(remote.refs.fetch) } : null,
};
}
/** 配置 Forgejo Git 远端。认证交给系统钥匙串或 SSH不保存凭据。 */
async configureRemote(url: string, remoteName = 'origin'): Promise<RepositoryStatus> {
this.assertRemoteName(remoteName);
const safeUrl = this.validateRemoteUrl(url);
const remotes = await this.git.getRemotes(true);
if (remotes.some(item => item.name === remoteName)) {
await this.git.remote(['set-url', remoteName, safeUrl]);
} else {
await this.git.addRemote(remoteName, safeUrl);
}
return this.getRepositoryStatus(remoteName);
}
async fetchRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
this.assertRemoteName(remoteName);
await this.requireRemote(remoteName);
await this.git.fetch(remoteName, ['--prune']);
return this.getRepositoryStatus(remoteName);
}
/** 只允许快进拉取,避免客户端静默制造合并提交。 */
async pullRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
this.assertRemoteName(remoteName);
await this.requireRemote(remoteName);
const status = await this.git.status();
if (!status.current) throw new Error('当前没有可拉取的分支');
if (!status.isClean()) throw new Error('本地有未提交变更,请先保存或提交后再拉取');
await this.git.pull(remoteName, status.current, { '--ff-only': null });
return this.getRepositoryStatus(remoteName);
}
/** 推送只能由显式 UI 操作调用Agent 不注册此写操作。 */
async pushRemote(remoteName = 'origin'): Promise<RepositoryStatus> {
this.assertRemoteName(remoteName);
await this.requireRemote(remoteName);
const status = await this.git.status();
if (!status.current) throw new Error('当前没有可推送的分支');
if (!status.isClean()) throw new Error('本地有未提交变更,请先保存后再推送');
await this.git.push(remoteName, status.current, ['--set-upstream']);
return this.getRepositoryStatus(remoteName);
}
// ─── 文档 CRUD ───
/** 读取文档 */
@ -360,8 +432,44 @@ export class GitEngine {
// ─── 辅助 ───
private resolvePath(docPath: string): string {
// 安全检查:防止路径穿越
const normalized = path.normalize(docPath).replace(/^(\.\.\/?)+/, '');
return path.join(this.docsDir, normalized);
const normalized = path.normalize(docPath);
const resolved = path.resolve(this.docsDir, normalized);
const prefix = `${path.resolve(this.docsDir)}${path.sep}`;
if (!resolved.startsWith(prefix) || !normalized.endsWith('.md')) {
throw new Error('文档路径无效,只允许知识库 docs 目录内的 Markdown 文件');
}
return resolved;
}
private assertRemoteName(name: string): void {
if (!/^[A-Za-z0-9._-]{1,64}$/.test(name)) throw new Error('远端名称无效');
}
private validateRemoteUrl(value: string): string {
const url = value.trim();
if (!url) throw new Error('Forgejo 仓库地址不能为空');
if (/^https?:\/\//i.test(url)) {
const parsed = new URL(url);
if (parsed.username || parsed.password) throw new Error('仓库地址不能包含账号或密钥,请使用系统钥匙串');
return parsed.toString().replace(/\/$/, '');
}
if (/^(ssh:\/\/|git@)[^\s]+$/i.test(url)) return url;
throw new Error('仅支持 HTTPS 或 SSH Forgejo 仓库地址');
}
private redactRemoteUrl(value: string): string {
try {
const parsed = new URL(value);
parsed.username = '';
parsed.password = '';
return parsed.toString().replace(/\/$/, '');
} catch {
return value.replace(/\/\/[^/@]+@/, '//***@');
}
}
private async requireRemote(name: string): Promise<void> {
const remotes = await this.git.getRemotes();
if (!remotes.includes(name)) throw new Error('尚未配置 Forgejo 仓库地址');
}
}

View file

@ -25,7 +25,12 @@ const REPO_PATH = process.env.KB_REPO_PATH || path.resolve(_dirname, '../kb-data
const app = express();
const engine = new GitEngine(REPO_PATH);
app.use(cors());
app.use(cors({
origin(origin, callback) {
const allowed = !origin || origin === 'null' || /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin);
callback(allowed ? null : new Error('仅允许 HoloLake 本机界面访问'), allowed);
},
}));
app.use(express.json({ limit: '10mb' }));
// Express v5 的 {*param} 返回数组,工具函数统一转字符串
@ -178,6 +183,55 @@ app.get('/api/search', async (req, res) => {
}
});
// ─── ForgejoGit 远端引擎) ───
app.get('/api/forgejo/status', async (_req, res) => {
try {
res.json({ ok: true, status: await engine.getRepositoryStatus() });
} catch (err: any) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.put('/api/forgejo/remote', async (req, res) => {
try {
const { url } = req.body;
if (!url || typeof url !== 'string') {
return res.status(400).json({ ok: false, error: 'url 必填且为字符串' });
}
res.json({ ok: true, status: await engine.configureRemote(url) });
} catch (err: any) {
res.status(400).json({ ok: false, error: err.message });
}
});
app.post('/api/forgejo/fetch', async (_req, res) => {
try {
res.json({ ok: true, status: await engine.fetchRemote() });
} catch (err: any) {
res.status(502).json({ ok: false, error: err.message });
}
});
app.post('/api/forgejo/pull', async (_req, res) => {
try {
res.json({ ok: true, status: await engine.pullRemote() });
} catch (err: any) {
res.status(409).json({ ok: false, error: err.message });
}
});
app.post('/api/forgejo/push', async (req, res) => {
try {
if (req.body?.confirm !== true) {
return res.status(428).json({ ok: false, error: '推送需要用户明确确认' });
}
res.json({ ok: true, status: await engine.pushRemote() });
} catch (err: any) {
res.status(409).json({ ok: false, error: err.message });
}
});
// ─── Agent人格体 ───
let personaAgent: PersonaAgent | null = null;
@ -194,6 +248,7 @@ function getAgent(): PersonaAgent {
app.get('/api/agent/status', (_req, res) => {
const agent = getAgent();
const def = agent.getDefinition();
const runtime = agent.getRuntimeStatus();
res.json({
ok: true,
persona: {
@ -204,6 +259,9 @@ app.get('/api/agent/status', (_req, res) => {
permissionMode: def.permissionMode,
},
conversationLength: agent.getConversation().length,
configured: runtime.configured,
operational: runtime.operational,
tools: runtime.toolNames,
engine: 'git',
repo: REPO_PATH,
});
@ -247,9 +305,10 @@ async function start() {
await engine.init();
// 初始化人格体
getAgent();
app.listen(PORT, () => {
app.listen(PORT, '127.0.0.1', () => {
console.log(`光湖知识库 API 已启动: http://localhost:${PORT}`);
console.log(`人格体已激活: ${personaAgent?.getDefinition().name}`);
const runtime = personaAgent?.getRuntimeStatus();
console.log(`人格体运行状态: ${runtime?.operational ? '已接入模型' : '等待模型配置'}`);
console.log(`仓库路径: ${REPO_PATH}`);
});
}
@ -260,4 +319,3 @@ start().catch(err => {
});
export default app;

View file

@ -141,6 +141,14 @@ export class PersonaAgent {
// ─── 内置工具注册 ───
private registerBuiltinTools(): void {
// 读取 Git/Forgejo 状态;同步写操作必须由用户在界面中明确确认。
this.tools.register({
name: 'inspect_repository',
description: '查看知识库本地 Git 与 Forgejo 远端的连接和同步状态(只读)',
parameters: {},
execute: async () => JSON.stringify(await this.git.getRepositoryStatus(), null, 2),
});
// 读取知识库文档
this.tools.register({
name: 'read_document',
@ -366,13 +374,10 @@ ${toolsList}
private async callLLM(messages: Message[]): Promise<{ content: string; toolCalls?: ToolCall[] }> {
const apiKey = process.env.OPENAI_API_KEY || process.env.HOLOLAKE_LLM_KEY || '';
const baseUrl = process.env.HOLOLAKE_LLM_BASE || 'https://api.openai.com/v1';
const model = this.definition.model || 'gpt-4o';
const model = process.env.HOLOLAKE_LLM_MODEL || this.definition.model || 'gpt-4o';
if (!apiKey) {
// 没有 API Key 时返回模拟回复(开发模式)
return {
content: `[${this.definition.name}] 收到你的消息。当前为离线模式,请配置 HOLOLAKE_LLM_KEY 环境变量启用 AI 能力。\n\n你说的: "${messages[messages.length - 1]?.content}"`,
};
throw new Error('Agent 尚未配置模型。请先在运行环境中设置 HOLOLAKE_LLM_KEY当前不会伪装成已运行。');
}
try {
@ -384,11 +389,28 @@ ${toolsList}
},
body: JSON.stringify({
model,
messages: messages.map(m => ({
role: m.role,
content: m.content,
...(m.toolCalls ? { tool_calls: m.toolCalls } : {}),
})),
messages: messages.map(m => {
if (m.role === 'assistant' && m.toolCalls?.length) {
return {
role: 'assistant',
content: m.content || null,
tool_calls: m.toolCalls.map(call => ({
id: call.id,
type: 'function',
function: { name: call.name, arguments: JSON.stringify(call.arguments) },
})),
};
}
if (m.role === 'tool' && m.toolResults?.[0]) {
return {
role: 'tool',
content: m.content,
tool_call_id: m.toolResults[0].id,
name: m.toolResults[0].name,
};
}
return { role: m.role, content: m.content };
}),
tools: this.tools.toSchema(),
temperature: this.definition.temperature,
max_tokens: this.definition.maxTokens,
@ -396,6 +418,9 @@ ${toolsList}
});
const data = await res.json() as any;
if (!res.ok) {
throw new Error(data?.error?.message || `模型服务返回 HTTP ${res.status}`);
}
const choice = data.choices?.[0]?.message;
if (!choice) {
@ -413,7 +438,7 @@ ${toolsList}
toolCalls,
};
} catch (err: any) {
return { content: `AI 调用失败: ${err.message}` };
throw new Error(`AI 调用失败: ${err.message}`);
}
}
@ -428,7 +453,19 @@ ${toolsList}
}
getDefinition(): PersonaDefinition {
return { ...this.definition };
return {
...this.definition,
model: process.env.HOLOLAKE_LLM_MODEL || this.definition.model,
};
}
getRuntimeStatus(): { configured: boolean; operational: boolean; toolNames: string[] } {
const configured = Boolean(process.env.OPENAI_API_KEY || process.env.HOLOLAKE_LLM_KEY);
return {
configured,
operational: configured,
toolNames: this.tools.list().map(tool => tool.name),
};
}
}
@ -442,6 +479,7 @@ export function createDefaultPersona(git: GitEngine): PersonaAgent {
role: '知识库管理者 — 负责文档的创建、整理、搜索和版本管理',
systemPromptBase: '你是光湖知识库的人格体,一个活的知识管理 AI Agent。',
tools: [
'inspect_repository',
'read_document',
'create_document',
'update_document',
@ -458,4 +496,3 @@ export function createDefaultPersona(git: GitEngine): PersonaAgent {
git
);
}

View file

@ -9,6 +9,7 @@ import AgentChat from './components/AgentChat';
type View = 'editor' | 'history';
export default function App() {
const agentApiBase = window.location.protocol === 'file:' ? 'http://127.0.0.1:3890' : '';
const [tree, setTree] = useState<DocTreeNode[]>([]);
const [currentDoc, setCurrentDoc] = useState<DocContent | null>(null);
const [currentPath, setCurrentPath] = useState<string>('');
@ -181,7 +182,7 @@ export default function App() {
{/* Agent 面板 */}
{agentPanelOpen && (
<aside className="kb-agent-panel">
<AgentChat apiBase="" onDocSelect={openDoc} />
<AgentChat apiBase={agentApiBase} onDocSelect={openDoc} />
</aside>
)}
</div>

View file

@ -3,7 +3,9 @@
* Agent UI
*/
const BASE = '/api';
const BASE = typeof window !== 'undefined' && window.location.protocol === 'file:'
? 'http://127.0.0.1:3890/api'
: '/api';
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {

View file

@ -21,6 +21,18 @@ interface AgentStatus {
role: string;
model: string;
conversationLength: number;
configured: boolean;
operational: boolean;
tools: string[];
}
interface RepositoryStatus {
branch: string;
head: string;
clean: boolean;
ahead: number;
behind: number;
remote: { name: string; url: string } | null;
}
interface Props {
@ -33,11 +45,22 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const [status, setStatus] = useState<AgentStatus | null>(null);
const [repoStatus, setRepoStatus] = useState<RepositoryStatus | null>(null);
const [remoteUrl, setRemoteUrl] = useState('');
const [syncMessage, setSyncMessage] = useState('');
const [syncing, setSyncing] = useState(false);
const [configOpen, setConfigOpen] = useState(false);
const [modelBaseUrl, setModelBaseUrl] = useState('https://api.openai.com/v1');
const [modelName, setModelName] = useState('gpt-4o');
const [modelKey, setModelKey] = useState('');
const [configMessage, setConfigMessage] = useState('');
const bottomRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
fetchStatus();
fetchRepositoryStatus();
loadModelConfig();
}, []);
useEffect(() => {
@ -54,11 +77,74 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
role: data.persona.role,
model: data.persona.model,
conversationLength: data.conversationLength,
configured: data.configured,
operational: data.operational,
tools: data.tools || [],
});
}
} catch {}
}
async function loadModelConfig() {
const bridge = (window as any).hololake?.agent;
if (!bridge) return;
try {
const config = await bridge.getConfig();
setModelBaseUrl(config.baseUrl || 'https://api.openai.com/v1');
setModelName(config.model || 'gpt-4o');
} catch {}
}
async function saveModelConfig() {
const bridge = (window as any).hololake?.agent;
if (!bridge) {
setConfigMessage('模型安全配置只在桌面 App 中提供');
return;
}
try {
await bridge.saveConfig({ baseUrl: modelBaseUrl, model: modelName, apiKey: modelKey || undefined });
setModelKey('');
setConfigMessage('已保存到 macOS 加密存储');
await fetchStatus();
} catch (err: any) {
setConfigMessage(err.message);
}
}
async function fetchRepositoryStatus() {
try {
const res = await fetch(`${apiBase}/api/forgejo/status`);
const data = await res.json();
if (data.ok) {
setRepoStatus(data.status);
if (data.status.remote?.url) setRemoteUrl(data.status.remote.url);
}
} catch {}
}
async function runForgejoAction(action: 'configure' | 'fetch' | 'pull' | 'push') {
if (syncing) return;
if (action === 'push' && !confirm('确认把当前知识库提交推送到已配置的 Forgejo 仓库?')) return;
setSyncing(true);
setSyncMessage('');
try {
const endpoint = action === 'configure' ? 'remote' : action;
const res = await fetch(`${apiBase}/api/forgejo/${endpoint}`, {
method: action === 'configure' ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(action === 'configure' ? { url: remoteUrl } : { confirm: action === 'push' }),
});
const data = await res.json();
if (!data.ok) throw new Error(data.error || '操作失败');
setRepoStatus(data.status);
setSyncMessage(action === 'configure' ? 'Forgejo 已连接' : `${action} 已完成`);
} catch (err: any) {
setSyncMessage(err.message);
} finally {
setSyncing(false);
}
}
async function sendMessage() {
const text = input.trim();
if (!text || sending) return;
@ -135,19 +221,61 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
</div>
<div className="agent-actions">
<span className="agent-model">{status?.model || 'offline'}</span>
<button className="btn-config" onClick={() => setConfigOpen(!configOpen)} title="配置模型"></button>
<button className="btn-clear" onClick={clearConversation} title="清空对话">
</button>
</div>
</div>
<div className="runtime-status">
<div className="runtime-row">
<span className={`runtime-dot ${status?.operational ? 'online' : 'waiting'}`} />
<span>{status?.operational ? 'Agent 已接入模型' : 'Agent 等待模型配置'}</span>
<span className="runtime-tools">{status?.tools?.length || 0} </span>
</div>
{configOpen && (
<div className="model-config">
<input value={modelBaseUrl} onChange={e => setModelBaseUrl(e.target.value)} placeholder="模型服务地址" />
<input value={modelName} onChange={e => setModelName(e.target.value)} placeholder="模型名称" />
<input type="password" value={modelKey} onChange={e => setModelKey(e.target.value)} placeholder={status?.configured ? '留空则保留现有密钥' : '模型密钥'} />
<button onClick={saveModelConfig}></button>
{configMessage && <div className="forgejo-message">{configMessage}</div>}
</div>
)}
<div className="forgejo-status">
<div className="forgejo-title">
<strong>Forgejo </strong>
<span>{repoStatus?.remote ? `${repoStatus.branch} · ${repoStatus.head.slice(0, 7)}` : '尚未连接远端'}</span>
</div>
<input
className="forgejo-url"
value={remoteUrl}
onChange={e => setRemoteUrl(e.target.value)}
placeholder="HTTPS 或 SSH Forgejo 仓库地址"
/>
<div className="forgejo-actions">
<button onClick={() => runForgejoAction('configure')} disabled={syncing || !remoteUrl.trim()}></button>
<button onClick={() => runForgejoAction('fetch')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('pull')} disabled={syncing || !repoStatus?.remote}></button>
<button onClick={() => runForgejoAction('push')} disabled={syncing || !repoStatus?.remote}></button>
</div>
{repoStatus?.remote && (
<div className="forgejo-detail">
{repoStatus.clean ? '本地已提交' : '本地有未提交内容'} · {repoStatus.ahead} / {repoStatus.behind}
</div>
)}
{syncMessage && <div className="forgejo-message">{syncMessage}</div>}
</div>
</div>
{/* 对话区域 */}
<div className="agent-messages">
{messages.length === 0 && (
<div className="agent-welcome">
<div className="welcome-icon">🌊</div>
<h2></h2>
<p> AI Agent Git </p>
<p>{status?.operational ? '我是知识库的 AI Agent可以调用工具管理文档。' : '知识库功能已运行Agent 需要配置模型后才会回应,不会用模拟回复冒充。'}</p>
<p className="welcome-hint"></p>
<div className="welcome-suggestions">
<button onClick={() => { setInput('帮我列出所有文档'); inputRef.current?.focus(); }}>
@ -232,18 +360,18 @@ export default function AgentChat({ apiBase, onDocSelect }: Props) {
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
rows={1}
disabled={sending}
disabled={sending || !status?.operational}
/>
<button
className="btn-send"
onClick={sendMessage}
disabled={sending || !input.trim()}
disabled={sending || !input.trim() || !status?.operational}
>
{sending ? '⏳' : '↑'}
</button>
</div>
<div className="agent-hint">
Enter · Shift+Enter · Agent
{status?.operational ? 'Enter 发送 · 写操作由本地 Git 留痕 · Forgejo 推送需确认' : 'Agent 尚未接入模型;知识库与 Forgejo 功能仍可独立使用'}
</div>
</div>
</div>

View file

@ -45,6 +45,7 @@ body {
}
.kb-header {
-webkit-app-region: drag;
height: var(--kb-header-height);
display: flex;
align-items: center;
@ -55,6 +56,12 @@ body {
flex-shrink: 0;
}
.kb-header button,
.kb-header input,
.kb-header a {
-webkit-app-region: no-drag;
}
.kb-header-left {
display: flex;
align-items: center;
@ -838,7 +845,8 @@ body {
font-family: var(--kb-font-mono);
}
.btn-clear {
.btn-clear,
.btn-config {
background: none;
border: none;
color: var(--kb-text-muted);
@ -849,11 +857,108 @@ body {
transition: all 0.15s;
}
.btn-clear:hover {
.btn-clear:hover,
.btn-config:hover {
background: var(--kb-bg-tertiary);
color: var(--kb-danger);
}
.model-config {
display: grid;
grid-template-columns: 1fr 92px;
gap: 6px;
margin-top: 9px;
padding: 9px;
border: 1px solid var(--kb-border);
border-radius: 8px;
background: var(--kb-bg);
}
.model-config input {
min-width: 0;
border: 1px solid var(--kb-border);
border-radius: 5px;
padding: 6px 7px;
background: var(--kb-bg-secondary);
color: var(--kb-text);
font-size: 10px;
}
.model-config input:first-child,
.model-config input[type="password"],
.model-config .forgejo-message { grid-column: 1 / -1; }
.model-config button {
border: 1px solid var(--kb-accent);
border-radius: 5px;
background: rgba(88, 166, 255, .12);
color: var(--kb-text);
cursor: pointer;
}
.runtime-status {
padding: 10px 14px;
border-bottom: 1px solid var(--kb-border);
background: var(--kb-bg-secondary);
font-size: 11px;
}
.runtime-row,
.forgejo-title,
.forgejo-actions {
display: flex;
align-items: center;
gap: 7px;
}
.runtime-dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.runtime-dot.online { background: #3fb950; box-shadow: 0 0 7px rgba(63, 185, 80, .55); }
.runtime-dot.waiting { background: #d29922; }
.runtime-tools { margin-left: auto; color: var(--kb-text-muted); }
.forgejo-status {
margin-top: 9px;
padding: 9px;
border: 1px solid var(--kb-border);
border-radius: 8px;
background: var(--kb-bg);
}
.forgejo-title { justify-content: space-between; margin-bottom: 7px; }
.forgejo-title span,
.forgejo-detail { color: var(--kb-text-muted); }
.forgejo-url {
width: 100%;
box-sizing: border-box;
border: 1px solid var(--kb-border);
border-radius: 6px;
padding: 7px 8px;
background: var(--kb-bg-secondary);
color: var(--kb-text);
font-size: 11px;
}
.forgejo-actions { margin-top: 7px; }
.forgejo-actions button {
flex: 1;
border: 1px solid var(--kb-border);
border-radius: 5px;
padding: 5px 3px;
background: var(--kb-bg-tertiary);
color: var(--kb-text);
cursor: pointer;
font-size: 10px;
}
.forgejo-actions button:disabled { opacity: .4; cursor: not-allowed; }
.forgejo-detail { margin-top: 6px; }
.forgejo-message { margin-top: 5px; color: var(--kb-accent); word-break: break-word; }
/* ─── 对话区域 ─── */
.agent-messages {

View file

@ -13,9 +13,10 @@
* ~/Library/Application Support/HoloLake Era/data/
*/
import { app, BrowserWindow, shell, dialog } from 'electron';
import { app, BrowserWindow, shell, dialog, ipcMain, safeStorage } from 'electron';
import path from 'path';
import { spawn, ChildProcess } from 'child_process';
import fs from 'fs';
// ─── 配置 ───
@ -26,6 +27,31 @@ const CLIENT_PORT = 5180;
// 数据目录macOS 标准位置
const DATA_DIR = path.join(app.getPath('userData'), 'data');
const KB_REPO_PATH = path.join(DATA_DIR, 'knowledge-base');
const MODEL_CONFIG_PATH = path.join(app.getPath('userData'), 'model-config.json');
interface ModelConfigFile {
baseUrl: string;
model: string;
encryptedKey?: string;
}
function readModelConfig(): ModelConfigFile {
try {
return JSON.parse(fs.readFileSync(MODEL_CONFIG_PATH, 'utf8')) as ModelConfigFile;
} catch {
return { baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o' };
}
}
function applyModelConfig(): ModelConfigFile {
const config = readModelConfig();
process.env.HOLOLAKE_LLM_BASE = config.baseUrl;
process.env.HOLOLAKE_LLM_MODEL = config.model;
if (config.encryptedKey && safeStorage.isEncryptionAvailable()) {
process.env.HOLOLAKE_LLM_KEY = safeStorage.decryptString(Buffer.from(config.encryptedKey, 'base64'));
}
return config;
}
// ─── 后端服务器 ───
@ -73,7 +99,7 @@ function startServer(): Promise<void> {
try {
process.env.KB_PORT = String(SERVER_PORT);
process.env.KB_REPO_PATH = KB_REPO_PATH;
const serverBundle = path.join(__dirname, 'server-bundle.js');
const serverBundle = path.join(__dirname, 'server-bundle.cjs');
require(serverBundle);
console.log(`[KB Server] 内嵌启动,端口 ${SERVER_PORT}`);
resolve();
@ -106,7 +132,7 @@ function createWindow(): void {
trafficLightPosition: { x: 16, y: 16 },
backgroundColor: '#0d1117',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
},
@ -130,10 +156,37 @@ function createWindow(): void {
});
}
ipcMain.handle('get-data-path', () => DATA_DIR);
ipcMain.handle('agent:get-config', () => {
const config = readModelConfig();
return {
baseUrl: config.baseUrl,
model: config.model,
configured: Boolean(config.encryptedKey && safeStorage.isEncryptionAvailable()),
};
});
ipcMain.handle('agent:save-config', (_event, input: { baseUrl: string; model: string; apiKey?: string }) => {
const baseUrl = String(input.baseUrl || '').trim().replace(/\/$/, '');
const model = String(input.model || '').trim();
if (!/^https:\/\//i.test(baseUrl)) throw new Error('模型服务地址必须使用 HTTPS');
if (!model) throw new Error('模型名称不能为空');
if (!safeStorage.isEncryptionAvailable()) throw new Error('macOS 加密存储当前不可用');
const previous = readModelConfig();
const encryptedKey = input.apiKey
? safeStorage.encryptString(String(input.apiKey)).toString('base64')
: previous.encryptedKey;
if (!encryptedKey) throw new Error('请填写模型密钥');
fs.mkdirSync(path.dirname(MODEL_CONFIG_PATH), { recursive: true });
fs.writeFileSync(MODEL_CONFIG_PATH, JSON.stringify({ baseUrl, model, encryptedKey }), { mode: 0o600 });
applyModelConfig();
return { baseUrl, model, configured: true };
});
// ─── 应用生命周期 ───
app.whenReady().then(async () => {
try {
applyModelConfig();
await startServer();
createWindow();
} catch (err) {

View file

@ -16,11 +16,11 @@ contextBridge.exposeInMainWorld('hololake', {
// 数据目录
getDataPath: () => ipcRenderer.invoke('get-data-path'),
// Forgejo 远程仓库管理(预留接口)
forgejo: {
getRemotes: () => ipcRenderer.invoke('forgejo:get-remotes'),
addRemote: (url: string) => ipcRenderer.invoke('forgejo:add-remote', url),
push: () => ipcRenderer.invoke('forgejo:push'),
pull: () => ipcRenderer.invoke('forgejo:pull'),
agent: {
getConfig: () => ipcRenderer.invoke('agent:get-config'),
saveConfig: (config: { baseUrl: string; model: string; apiKey?: string }) =>
ipcRenderer.invoke('agent:save-config', config),
},
// Forgejo 通过本地知识库 API 管理;此桥只保留非敏感应用信息。
});

View file

@ -23,3 +23,9 @@
# - 不接 Forgejo 上游自动更新
# - 光湖团队评估 Forgejo 新版功能后,拆出有用部分自行集成
# - Forgejo 的 Git 引擎逐渐适配光湖协议HLDP/GLS
#
# 2026-08-08 运行实现:
# - GitEngine 已实现状态、配置 remote、fetch、仅快进 pull、显式确认 push
# - 桌面 UI 已提供连接与同步状态;认证继续使用本机钥匙串或 SSH
# - Agent 只获得只读 inspect_repository 工具,不拥有自动 push 权限
# - 本地 API 仅监听 127.0.0.1,不向局域网暴露

File diff suppressed because it is too large Load diff

View file

@ -2,30 +2,32 @@
"name": "hololake-desktop",
"version": "0.5.0",
"description": "HoloLake Era 桌面版 — Git 驱动的知识库管理",
"main": "dist-electron/main.js",
"main": "dist-electron/main.cjs",
"type": "module",
"scripts": {
"dev": "concurrently \"npm run dev:server\" \"npm run dev:client\"",
"dev:server": "tsx watch ../guanghu-knowledge-base/server/index.ts",
"dev:client": "vite",
"dev:electron": "electron .",
"build": "vite build && tsc -p tsconfig.electron.json",
"build:electron": "esbuild electron/main.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist-electron/main.cjs && esbuild electron/preload.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist-electron/preload.cjs",
"build:server": "NODE_PATH=./node_modules esbuild ../guanghu-knowledge-base/server/index.ts --bundle --platform=node --format=cjs --outfile=dist-electron/server-bundle.cjs",
"build": "vite build && npm run build:electron && npm run build:server",
"pack": "npm run build && electron-builder --mac --dir",
"dist": "npm run build && electron-builder --mac",
"preview": "vite preview"
},
"dependencies": {
"express": "^5.1.0",
"cors": "^2.8.5",
"simple-git": "^3.27.0",
"diff": "^9.0.0",
"express": "^5.1.0",
"gray-matter": "^4.0.3",
"marked": "^15.0.0",
"diff": "^7.0.0"
"simple-git": "^3.27.0"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/cors": "^2.8.17",
"@types/diff": "^6.0.0",
"@types/express": "^5.0.0",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
@ -33,6 +35,7 @@
"concurrently": "^9.1.0",
"electron": "^35.0.0",
"electron-builder": "^26.0.0",
"esbuild": "^0.25.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tsx": "^4.19.0",
@ -47,10 +50,15 @@
"icon": "forgejo/icon.icns",
"identity": "bei sun (825A9L3G7Q)",
"target": [
{ "target": "dmg", "arch": ["arm64"] }
{
"target": "dmg",
"arch": [
"arm64"
]
}
]
},
"asar": false,
"asar": true,
"files": [
"dist/**/*",
"dist-electron/**/*",

View file

@ -3,11 +3,17 @@ import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
base: './',
plugins: [react()],
resolve: {
alias: {
// 复用知识库前端组件
'@': path.resolve(__dirname, '../guanghu-knowledge-base/src'),
'react/jsx-runtime': path.resolve(__dirname, 'node_modules/react/jsx-runtime.js'),
'react-dom/client': path.resolve(__dirname, 'node_modules/react-dom/client.js'),
'react-dom': path.resolve(__dirname, 'node_modules/react-dom/index.js'),
'react': path.resolve(__dirname, 'node_modules/react/index.js'),
'marked': path.resolve(__dirname, 'node_modules/marked/lib/marked.esm.js'),
},
},
root: path.resolve(__dirname, '../guanghu-knowledge-base'),