Реверснутый zcode с своими фишками и плагинами
Реверснутая ade zcode без z ai, с массовой загрузкой ключей, умным апи роутингом, плагином для командной разработки
Реверснутая ade zcode без z ai, с массовой загрузкой ключей, умным апи роутингом, плагином для командной разработки
Принят владельцем вручную, без ИИ. Усилие оценено по объёму правки (9861 строк) — очки вклада начисляются как за large.
| +добавлено | // Перед стартом: согласовать профиль с каталогом, в котором лежит сборка. |
| +добавлено | // |
| +добавлено | // 1. setting.json: без providerFamilyDomain ZCode открывает штатный экран входа Z.ai, |
| +добавлено | // вырезанный в форке, — окно остаётся пустым. Поле теряется, когда настройки не |
| +добавлено | // проходят схему и ZCode перезаписывает файл умолчаниями. |
| +добавлено | // 2. CLI-конфиг: команды хуков уведомлений и известные маркетплейсы записаны путями |
| +добавлено | // каталога разработки. В установке они должны вести в её собственные hooks и |
| +добавлено | // marketplace, иначе тосты и кнопка «Команда» не работают. |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| +добавлено | const HOME = path.join(APP, 'home'); |
| +добавлено | const cli = path.join(HOME, '.zcode', 'cli'); |
| +добавлено | |
| +добавлено | const readJson = (file) => { |
| +добавлено | try { |
| +добавлено | return JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | } catch (error) { |
| +добавлено | if (error.code !== 'ENOENT') console.error('[ensure-settings]', file, error.message); |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const writeJson = (file, value) => { |
| +добавлено | const tmp = `${file}.${process.pid}.tmp`; |
| +добавлено | fs.writeFileSync(tmp, JSON.stringify(value, null, 2)); |
| +добавлено | if (fs.existsSync(file)) fs.rmSync(file, { force: true }); |
| +добавлено | fs.renameSync(tmp, file); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const isInside = (target, root) => { |
| +добавлено | const rel = path.relative(path.resolve(root), path.resolve(target)); |
| +добавлено | return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- настройки |
| +добавлено | |
| +добавлено | const settingsFile = path.join(HOME, '.zcode', 'v2', 'setting.json'); |
| +добавлено | const settings = readJson(settingsFile); |
| +добавлено | if (settings && !settings.providerFamilyDomain) { |
| +добавлено | settings.providerFamilyDomain = 'zai'; |
| +добавлено | settings.providerFamilyDomainMigrated = true; |
| +добавлено | settings.providerFamilyDomainUpdatedAt = Date.now(); |
| +добавлено | writeJson(settingsFile, settings); |
| +добавлено | console.log('[ensure-settings] providerFamilyDomain restored'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- хуки |
| +добавлено | |
| +добавлено | const notify = (arg) => `node "${path.join(APP, 'hooks', 'notify.mjs')}" ${arg}`.replace(/\\/g, '/'); |
| +добавлено | const events = { Stop: 'stop', SessionStart: 'session_start', PostToolUseFailure: 'tool_error' }; |
| +добавлено | const cliFile = path.join(cli, 'config.json'); |
| +добавлено | const config = readJson(cliFile); |
| +добавлено | if (config?.hooks?.events) { |
| +добавлено | let changed = false; |
| +добавлено | for (const [event, arg] of Object.entries(events)) { |
| +добавлено | for (const group of config.hooks.events[event] ?? []) { |
| +добавлено | for (const hook of group.hooks ?? []) { |
| +добавлено | if (typeof hook.command !== 'string' || !/hooks[\\/]notify\.mjs/.test(hook.command)) continue; |
| +добавлено | const next = notify(arg); |
| +добавлено | if (hook.command !== next) { |
| +добавлено | hook.command = next; |
| +добавлено | changed = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (changed) { |
| +добавлено | writeJson(cliFile, config); |
| +добавлено | console.log('[ensure-settings] hook paths rebound to', APP); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- маркетплейс |
| +добавлено | |
| +добавлено | const localMarket = path.join(APP, 'marketplace').replace(/\\/g, '/'); |
| +добавлено | const knownFile = path.join(cli, 'plugins', 'known_marketplaces.json'); |
| +добавлено | const known = readJson(knownFile); |
| +добавлено | if (known?.marketplaces) { |
| +добавлено | let changed = false; |
| +добавлено | for (const m of known.marketplaces) { |
| +добавлено | if (m.id !== 'local-marketplace' || m.source?.source !== 'directory') continue; |
| +добавлено | if (m.source.path !== localMarket) { |
| +добавлено | m.source.path = localMarket; |
| +добавлено | changed = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (changed) { |
| +добавлено | writeJson(knownFile, known); |
| +добавлено | console.log('[ensure-settings] local-marketplace ->', localMarket); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const installedFile = path.join(cli, 'plugins', 'installed_plugins.json'); |
| +добавлено | const installed = readJson(installedFile); |
| +добавлено | if (installed?.plugins) { |
| +добавлено | const pluginRoot = path.join(cli, 'plugins'); |
| +добавлено | const cacheRoot = path.join(pluginRoot, 'cache'); |
| +добавлено | const marketSrc = path.join(APP, 'marketplace', 'plugins'); |
| +добавлено | let changed = false; |
| +добавлено | for (const p of installed.plugins) { |
| +добавлено | if (typeof p.installPath === 'string') { |
| +добавлено | const rest = p.installPath.split(/[\\/]plugins[\\/]cache[\\/]/).pop(); |
| +добавлено | if (rest && !isInside(p.installPath, cacheRoot)) { |
| +добавлено | p.installPath = path.join(cacheRoot, rest); |
| +добавлено | changed = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (p.source?.source === 'directory' && p.marketplace === 'local-marketplace') { |
| +добавлено | const next = path.join(marketSrc, p.name); |
| +добавлено | if (p.source.path !== next) { |
| +добавлено | p.source.path = next; |
| +добавлено | changed = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (changed) { |
| +добавлено | writeJson(installedFile, installed); |
| +добавлено | console.log('[ensure-settings] installed_plugins paths rebound to', APP); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // notify.mjs — приёмник уведомлений от терминальных воркеров ZCode. |
| +добавлено | // Воркер вызывает: node notify.mjs <событие> [--task "имя"] [--detail "текст"] |
| +добавлено | // Событие показывается тостом Windows. |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawn } from 'node:child_process'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const ROOT = path.dirname(fileURLToPath(import.meta.url)); |
| +добавлено | |
| +добавлено | const EVENT_LABELS = { |
| +добавлено | stop: 'Воркер закончил', |
| +добавлено | session_start: 'Воркер запущен', |
| +добавлено | user_prompt: 'Воркер получил задачу', |
| +добавлено | tool_error: 'Ошибка инструмента', |
| +добавлено | error: 'Воркер упал', |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function parseArgs(argv) { |
| +добавлено | const out = { event: argv[0] ?? 'stop', task: '', detail: '', cwd: process.cwd() }; |
| +добавлено | for (let i = 1; i < argv.length; i++) { |
| +добавлено | const a = argv[i]; |
| +добавлено | if (a === '--task') out.task = argv[++i] ?? ''; |
| +добавлено | else if (a === '--detail') out.detail = argv[++i] ?? ''; |
| +добавлено | else if (a === '--cwd') out.cwd = argv[++i] ?? out.cwd; |
| +добавлено | else if (!out.detail) out.detail = a; |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Читает stdin, если хук передал JSON на входе. */ |
| +добавлено | async function readStdin() { |
| +добавлено | if (process.stdin.isTTY) return ''; |
| +добавлено | return await new Promise((resolve) => { |
| +добавлено | let buf = ''; |
| +добавлено | const done = () => resolve(buf); |
| +добавлено | process.stdin.setEncoding('utf8'); |
| +добавлено | process.stdin.on('data', (c) => (buf += c)); |
| +добавлено | process.stdin.on('end', done); |
| +добавлено | process.stdin.on('error', done); |
| +добавлено | setTimeout(done, 1500).unref?.(); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function pick(obj, keys) { |
| +добавлено | for (const k of keys) { |
| +добавлено | const v = obj?.[k]; |
| +добавлено | if (typeof v === 'string' && v.trim()) return v.trim(); |
| +добавлено | } |
| +добавлено | return ''; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function toast(title, body) { |
| +добавлено | const esc = (s) => String(s).replace(/'/g, "''"); |
| +добавлено | const ps = ` |
| +добавлено | [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null |
| +добавлено | $xml = @" |
| +добавлено | <toast><visual><binding template="ToastGeneric"><text>${esc(title)}</text><text>${esc(body)}</text></binding></visual></toast> |
| +добавлено | "@ |
| +добавлено | $doc = New-Object Windows.Data.Xml.Dom.XmlDocument |
| +добавлено | $doc.LoadXml($xml) |
| +добавлено | $t = [Windows.UI.Notifications.ToastNotification]::new($doc) |
| +добавлено | [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('ZCode Router').Show($t) |
| +добавлено | `; |
| +добавлено | try { |
| +добавлено | const p = spawn('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps], { |
| +добавлено | detached: true, |
| +добавлено | stdio: 'ignore', |
| +добавлено | windowsHide: true, |
| +добавлено | }); |
| +добавлено | p.unref(); |
| +добавлено | } catch { |
| +добавлено | /* тост — необязательная часть */ |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function main() { |
| +добавлено | const args = parseArgs(process.argv.slice(2)); |
| +добавлено | const raw = await readStdin(); |
| +добавлено | let payload = {}; |
| +добавлено | if (raw.trim()) { |
| +добавлено | try { |
| +добавлено | payload = JSON.parse(raw); |
| +добавлено | } catch { |
| +добавлено | payload = { raw: raw.trim().slice(0, 500) }; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const task = |
| +добавлено | args.task || |
| +добавлено | pick(payload, ['taskName', 'task', 'title', 'sessionName']) || |
| +добавлено | path.basename(args.cwd || process.cwd()); |
| +добавлено | const detail = |
| +добавлено | args.detail || |
| +добавлено | pick(payload, ['summary', 'message', 'lastMessage', 'reason']) || |
| +добавлено | ''; |
| +добавлено | |
| +добавлено | const event = String(args.event || payload.event || 'stop').toLowerCase(); |
| +добавлено | const label = EVENT_LABELS[event] ?? `Событие: ${event}`; |
| +добавлено | |
| +добавлено | if (event === 'stop' || event === 'error' || event === 'tool_error') { |
| +добавлено | toast(label, detail ? `${task} — ${detail}` : task); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Хук печатает короткий статус: он попадает в интерфейс ZCode. |
| +добавлено | process.stdout.write(`${label}: ${task}\n`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | main().catch((err) => { |
| +добавлено | process.stderr.write(`notify failed: ${err?.message ?? err}\n`); |
| +добавлено | process.exitCode = 0; |
| +добавлено | }); |
| +добавлено | { |
| +добавлено | "name": "local-marketplace", |
| +добавлено | "description": "Личный маркетплейс плагинов ZCode", |
| +добавлено | "plugins": [ |
| +добавлено | { |
| +добавлено | "name": "my-helper", |
| +добавлено | "description": "Пример локального плагина со скиллом hello.", |
| +добавлено | "version": "0.1.0", |
| +добавлено | "author": { |
| +добавлено | "name": "isaog" |
| +добавлено | }, |
| +добавлено | "source": { |
| +добавлено | "source": "directory", |
| +добавлено | "path": "./plugins/my-helper" |
| +добавлено | } |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | "name": "aura-team", |
| +добавлено | "displayName": "Aura Team", |
| +добавлено | "description": "Aura Team: команда, канбан-задачи, общие ключи, файлы и git. ИИ видит и ведёт задачи команды.", |
| +добавлено | "version": "1.0.0", |
| +добавлено | "author": { |
| +добавлено | "name": "isaog" |
| +добавлено | }, |
| +добавлено | "category": "productivity", |
| +добавлено | "source": { |
| +добавлено | "source": "directory", |
| +добавлено | "path": "./plugins/aura-team" |
| +добавлено | } |
| +добавлено | } |
| +добавлено | ] |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "mcpServers": { |
| +добавлено | "aura-team": { |
| +добавлено | "command": "node", |
| +добавлено | "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/mcp-server.mjs"] |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "name": "aura-team", |
| +добавлено | "version": "1.0.0", |
| +добавлено | "description": "Aura Team: команда, канбан-задачи, общие ключи, файлы и git. ИИ видит и ведёт задачи команды.", |
| +добавлено | "author": { |
| +добавлено | "name": "isaog" |
| +добавлено | }, |
| +добавлено | "license": "MIT", |
| +добавлено | "skills": "skills", |
| +добавлено | "hooks": "./hooks/hooks.json", |
| +добавлено | "mcpServers": "./.mcp.json" |
| +добавлено | } |
| +добавлено | { |
| +добавлено | "hooks": { |
| +добавлено | "SessionStart": [ |
| +добавлено | { |
| +добавлено | "hooks": [ |
| +добавлено | { |
| +добавлено | "type": "command", |
| +добавлено | "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"", |
| +добавлено | "async": false, |
| +добавлено | "timeoutMs": 4000 |
| +добавлено | } |
| +добавлено | ] |
| +добавлено | } |
| +добавлено | ] |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // Общий клиент локального сервиса Aura Team для MCP-сервера и хука SessionStart. |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | |
| +добавлено | export const SERVICE_DOWN = 'Aura Team сервис не запущен — откройте форк ZCode (Aura Team service is not running).'; |
| +добавлено | export const NOT_SIGNED_IN = 'Вы не вошли в Aura Team — войдите в панели Team в ZCode (not signed in).'; |
| +добавлено | export const NO_TEAM = 'Команда не выбрана — выберите команду в панели Team (no team selected).'; |
| +добавлено | |
| +добавлено | export function agentFilePath() { |
| +добавлено | const env = (process.env.ZTEAM_AGENT_FILE ?? '').trim(); |
| +добавлено | return env || path.join(os.homedir(), '.zcode', 'aura-team', 'agent.json'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function readAgent() { |
| +добавлено | try { |
| +добавлено | const doc = JSON.parse(fs.readFileSync(agentFilePath(), 'utf8')); |
| +добавлено | if (doc && Number.isInteger(doc.port) && typeof doc.token === 'string') return doc; |
| +добавлено | } catch { /* нет файла */ } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class ServiceError extends Error { |
| +добавлено | constructor(message, code, status) { |
| +добавлено | super(message); |
| +добавлено | this.code = code; |
| +добавлено | this.status = status; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function friendly(status, message) { |
| +добавлено | if (status === 401 && /not signed in|refresh/i.test(message)) return new ServiceError(NOT_SIGNED_IN, 'not_signed_in', status); |
| +добавлено | if (status === 401) return new ServiceError(NOT_SIGNED_IN, 'not_signed_in', status); |
| +добавлено | if (status === 400 && /no team selected/i.test(message)) return new ServiceError(NO_TEAM, 'no_team', status); |
| +добавлено | return new ServiceError(message, 'error', status); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function post(pathname, body, { timeoutMs = 15_000 } = {}) { |
| +добавлено | const agent = readAgent(); |
| +добавлено | if (!agent) throw new ServiceError(SERVICE_DOWN, 'service_down'); |
| +добавлено | let res; |
| +добавлено | try { |
| +добавлено | res = await fetch(`http://127.0.0.1:${agent.port}${pathname}`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', 'x-zteam-agent': agent.token }, |
| +добавлено | body: JSON.stringify(body ?? {}), |
| +добавлено | signal: AbortSignal.timeout(timeoutMs), |
| +добавлено | }); |
| +добавлено | } catch { |
| +добавлено | throw new ServiceError(SERVICE_DOWN, 'service_down'); |
| +добавлено | } |
| +добавлено | let json = null; |
| +добавлено | try { json = await res.json(); } catch { /* не JSON */ } |
| +добавлено | if (!res.ok) { |
| +добавлено | if (res.status === 401 && /agent token/i.test(json?.error ?? '')) { |
| +добавлено | throw new ServiceError('Токен агента не принят — перезапустите форк ZCode (agent token rejected).', 'bad_token', 401); |
| +добавлено | } |
| +добавлено | throw friendly(res.status, json?.error ?? `HTTP ${res.status}`); |
| +добавлено | } |
| +добавлено | return json; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function agentRpc(method, params = {}, opts) { |
| +добавлено | const r = await post('/agent/rpc', { method, params }, opts); |
| +добавлено | return r?.result; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const STATUS_RU = { todo: 'к выполнению', doing: 'в работе', review: 'проверка', done: 'готово' }; |
| +добавлено | |
| +добавлено | export function taskLine(t) { |
| +добавлено | const parts = [`[${t.status}] #${t.shortId} «${t.title}»`]; |
| +добавлено | const meta = []; |
| +добавлено | if (t.assigneeName) meta.push(`@${t.assigneeName}`); |
| +добавлено | if (t.priority && t.priority !== 'normal') meta.push(t.priority); |
| +добавлено | if (t.dueAt) meta.push(`до ${String(t.dueAt).slice(0, 10)}`); |
| +добавлено | if (t.labels?.length) meta.push(t.labels.map((l) => `#${l}`).join(' ')); |
| +добавлено | return meta.length ? `${parts[0]} — ${meta.join(' · ')}` : parts[0]; |
| +добавлено | } |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // MCP-сервер плагина aura-team: stdio, JSON-RPC 2.0 построчно, без зависимостей. |
| +добавлено | // Инструменты ходят в локальный сервис Aura Team (/agent/rpc) с токеном из agent.json. |
| +добавлено | |
| +добавлено | import { createInterface } from 'node:readline'; |
| +добавлено | import { agentRpc, taskLine, ServiceError, STATUS_RU } from './client.mjs'; |
| +добавлено | |
| +добавлено | const SERVER_INFO = { name: 'aura-team', version: '1.0.0' }; |
| +добавлено | const STATUS_ENUM = ['todo', 'doing', 'review', 'done']; |
| +добавлено | const PRIORITY_ENUM = ['low', 'normal', 'high', 'urgent']; |
| +добавлено | |
| +добавлено | const teamIdProp = { teamId: { type: 'string', description: 'ID команды; по умолчанию — выбранная в панели. Team id (defaults to the selected team).' } }; |
| +добавлено | const taskIdProp = { taskId: { type: 'string', description: 'ID задачи или префикс ≥6 символов (можно с #). Task id or ≥6-char prefix, e.g. "#1a2b3c4d".' } }; |
| +добавлено | |
| +добавлено | const taskFields = { |
| +добавлено | title: { type: 'string', description: 'Заголовок. Title.' }, |
| +добавлено | description: { type: 'string', description: 'Описание (markdown). Description.' }, |
| +добавлено | status: { type: 'string', enum: STATUS_ENUM, description: 'Колонка: todo / doing / review / done.' }, |
| +добавлено | priority: { type: 'string', enum: PRIORITY_ENUM, description: 'Приоритет. Priority.' }, |
| +добавлено | labels: { type: 'array', items: { type: 'string' }, maxItems: 8, description: 'Метки (до 8). Labels.' }, |
| +добавлено | assignee: { type: 'string', description: 'Исполнитель: имя, email или id участника. Assignee display name / email / id.' }, |
| +добавлено | dueAt: { type: ['string', 'null'], description: 'Дедлайн ISO-8601 (например 2026-11-20) или null. Due date.' }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }; |
| +добавлено | const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }; |
| +добавлено | |
| +добавлено | const tools = [ |
| +добавлено | { |
| +добавлено | name: 'team_whoami', |
| +добавлено | description: 'Кто я в Aura Team: пользователь, выбранная команда, роль, список команд. Who am I: user, selected team, role.', |
| +добавлено | inputSchema: { type: 'object', properties: { ...teamIdProp }, additionalProperties: false }, |
| +добавлено | annotations: { title: 'Aura Team: кто я', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const r = await agentRpc('whoami', a); |
| +добавлено | const lines = [ |
| +добавлено | `Пользователь: ${r.user?.displayName ?? '—'} <${r.user?.email ?? '—'}>`, |
| +добавлено | r.teamId ? `Команда: «${r.teamName}» (${r.role}) · id ${r.teamId}` : 'Команда не выбрана.', |
| +добавлено | ]; |
| +добавлено | if (r.teams?.length > 1) lines.push(`Все команды: ${r.teams.map((t) => `«${t.name}» (${t.role})`).join(', ')}`); |
| +добавлено | if (r.workspace) lines.push(`Рабочая папка: ${r.workspace}`); |
| +добавлено | return { text: lines.join('\n'), data: r }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_members', |
| +добавлено | description: 'Участники команды: имя, email, роль, онлайн. Team members with roles and online status.', |
| +добавлено | inputSchema: { type: 'object', properties: { ...teamIdProp }, additionalProperties: false }, |
| +добавлено | annotations: { title: 'Aura Team: участники', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const r = await agentRpc('members', a); |
| +добавлено | const text = r.length |
| +добавлено | ? r.map((m) => `${m.online ? '●' : '○'} ${m.displayName} <${m.email}> — ${m.role}`).join('\n') |
| +добавлено | : 'В команде нет участников.'; |
| +добавлено | return { text, data: { members: r } }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_board', |
| +добавлено | description: 'Канбан-доска команды (все задачи или одна колонка). Team kanban board, optionally filtered by status.', |
| +добавлено | inputSchema: { |
| +добавлено | type: 'object', |
| +добавлено | properties: { ...teamIdProp, status: { type: 'string', enum: STATUS_ENUM, description: 'Только эта колонка. Filter by status.' } }, |
| +добавлено | additionalProperties: false, |
| +добавлено | }, |
| +добавлено | annotations: { title: 'Aura Team: доска', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const r = await agentRpc('board', a); |
| +добавлено | if (!r.tasks.length) return { text: a.status ? `В колонке «${STATUS_RU[a.status]}» задач нет.` : 'На доске нет задач.', data: r }; |
| +добавлено | const groups = STATUS_ENUM.filter((s) => !a.status || s === a.status).map((s) => { |
| +добавлено | const list = r.tasks.filter((t) => t.status === s); |
| +добавлено | return list.length ? `## ${STATUS_RU[s]} (${list.length})\n${list.map(taskLine).join('\n')}` : null; |
| +добавлено | }).filter(Boolean); |
| +добавлено | return { text: groups.join('\n\n'), data: r }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_my_tasks', |
| +добавлено | description: 'Мои открытые задачи в выбранной команде. My open tasks in the selected team.', |
| +добавлено | inputSchema: { |
| +добавлено | type: 'object', |
| +добавлено | properties: { ...teamIdProp, includeDone: { type: 'boolean', description: 'Включить завершённые. Include done tasks.' } }, |
| +добавлено | additionalProperties: false, |
| +добавлено | }, |
| +добавлено | annotations: { title: 'Aura Team: мои задачи', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const r = await agentRpc('myTasks', a); |
| +добавлено | const head = `Команда «${r.teamName ?? r.teamId}»: ${r.tasks.length ? `ваших открытых задач — ${r.tasks.length}` : 'у вас нет открытых задач'}.`; |
| +добавлено | return { text: [head, ...r.tasks.map(taskLine)].join('\n'), data: r }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_get_task', |
| +добавлено | description: 'Полная карточка задачи: описание, история изменений, связанные коммиты. Full task details with history and linked commits.', |
| +добавлено | inputSchema: { type: 'object', properties: { ...teamIdProp, ...taskIdProp }, required: ['taskId'], additionalProperties: false }, |
| +добавлено | annotations: { title: 'Aura Team: задача', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const t = await agentRpc('getTask', a); |
| +добавлено | const lines = [taskLine(t), `id: ${t.id}`]; |
| +добавлено | if (t.description) lines.push('', t.description); |
| +добавлено | if (t.commits?.length) lines.push('', 'Коммиты:', ...t.commits.map((c) => `- ${String(c.hash).slice(0, 10)} ${c.author ?? ''} ${c.repositoryUrl ?? ''}`.trim())); |
| +добавлено | if (t.history?.length) { |
| +добавлено | lines.push('', 'История:'); |
| +добавлено | for (const h of t.history.slice(0, 10)) lines.push(`- ${String(h.createdAt).slice(0, 16).replace('T', ' ')} ${h.userName}: ${h.action}${h.details?.status ? ` → ${h.details.status}` : ''}`); |
| +добавлено | } |
| +добавлено | return { text: lines.join('\n'), data: t }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_create_task', |
| +добавлено | description: 'Создать задачу на доске команды (исполнитель по умолчанию — я). Create a task; assignee defaults to me.', |
| +добавлено | inputSchema: { type: 'object', properties: { ...teamIdProp, ...taskFields }, required: ['title'], additionalProperties: false }, |
| +добавлено | annotations: { title: 'Aura Team: создать задачу', ...WRITE }, |
| +добавлено | run: async (a) => { |
| +добавлено | const t = await agentRpc('createTask', a); |
| +добавлено | return { text: `Создана задача ${taskLine(t)}\nСсылайтесь на неё как #${t.shortId}.`, data: t }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_update_task', |
| +добавлено | description: 'Изменить задачу: статус, приоритет, заголовок, описание, метки, исполнителя, дедлайн. Update task fields.', |
| +добавлено | inputSchema: { |
| +добавлено | type: 'object', |
| +добавлено | properties: { ...teamIdProp, ...taskIdProp, ...taskFields, assignee: { type: ['string', 'null'], description: 'Исполнитель (имя/email/id) или null — снять. Assignee or null to unassign.' } }, |
| +добавлено | required: ['taskId'], |
| +добавлено | additionalProperties: false, |
| +добавлено | }, |
| +добавлено | annotations: { title: 'Aura Team: изменить задачу', ...WRITE, idempotentHint: true }, |
| +добавлено | run: async (a) => { |
| +добавлено | const t = await agentRpc('updateTask', a); |
| +добавлено | return { text: `Обновлено: ${taskLine(t)}`, data: t }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_move_task', |
| +добавлено | description: 'Переместить задачу в колонку: doing — взял в работу, review — готово к проверке, done — завершено. Move a task to a column.', |
| +добавлено | inputSchema: { |
| +добавлено | type: 'object', |
| +добавлено | properties: { ...teamIdProp, ...taskIdProp, status: { type: 'string', enum: STATUS_ENUM } }, |
| +добавлено | required: ['taskId', 'status'], |
| +добавлено | additionalProperties: false, |
| +добавлено | }, |
| +добавлено | annotations: { title: 'Aura Team: переместить задачу', ...WRITE, idempotentHint: true }, |
| +добавлено | run: async (a) => { |
| +добавлено | const t = await agentRpc('moveTask', a); |
| +добавлено | return { text: `#${t.shortId} → ${STATUS_RU[t.status] ?? t.status}: «${t.title}»`, data: t }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | name: 'team_activity', |
| +добавлено | description: 'Лента событий команды (последние действия). Recent team activity feed.', |
| +добавлено | inputSchema: { |
| +добавлено | type: 'object', |
| +добавлено | properties: { ...teamIdProp, limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Сколько событий (по умолчанию 20).' } }, |
| +добавлено | additionalProperties: false, |
| +добавлено | }, |
| +добавлено | annotations: { title: 'Aura Team: лента', ...READ }, |
| +добавлено | run: async (a) => { |
| +добавлено | const r = await agentRpc('activity', a); |
| +добавлено | const text = r.length |
| +добавлено | ? r.map((e) => `${String(e.createdAt).slice(0, 16).replace('T', ' ')} ${e.userName}: ${e.action}${e.taskTitle ? ` «${e.taskTitle}»` : ''}`).join('\n') |
| +добавлено | : 'Событий пока нет.'; |
| +добавлено | return { text, data: { events: r } }; |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | const byName = new Map(tools.map((t) => [t.name, t])); |
| +добавлено | |
| +добавлено | function write(msg) { |
| +добавлено | process.stdout.write(`${JSON.stringify(msg)}\n`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function callTool(params) { |
| +добавлено | const tool = byName.get(params?.name); |
| +добавлено | if (!tool) return { content: [{ type: 'text', text: `Неизвестный инструмент: ${params?.name}` }], isError: true }; |
| +добавлено | const args = params.arguments && typeof params.arguments === 'object' ? params.arguments : {}; |
| +добавлено | try { |
| +добавлено | const { text, data } = await tool.run(args); |
| +добавлено | return { |
| +добавлено | content: [{ type: 'text', text }], |
| +добавлено | structuredContent: data && typeof data === 'object' && !Array.isArray(data) ? data : { result: data }, |
| +добавлено | }; |
| +добавлено | } catch (err) { |
| +добавлено | const text = err instanceof ServiceError ? err.message : `Ошибка Aura Team: ${err?.message ?? err}`; |
| +добавлено | return { content: [{ type: 'text', text }], isError: true }; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function handle(msg) { |
| +добавлено | const { id, method, params } = msg; |
| +добавлено | const isRequest = id !== undefined && id !== null; |
| +добавлено | try { |
| +добавлено | switch (method) { |
| +добавлено | case 'initialize': |
| +добавлено | return isRequest && write({ |
| +добавлено | jsonrpc: '2.0', id, |
| +добавлено | result: { |
| +добавлено | protocolVersion: params?.protocolVersion ?? '2025-06-18', |
| +добавлено | capabilities: { tools: { listChanged: false } }, |
| +добавлено | serverInfo: SERVER_INFO, |
| +добавлено | instructions: 'Aura Team: задачи команды (канбан). Ссылайтесь на задачи как #<shortId>; берёте в работу — team_move_task doing, закончили — review; добавляйте #<shortId> в сообщение коммита.', |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | case 'notifications/initialized': |
| +добавлено | case 'notifications/cancelled': |
| +добавлено | return undefined; |
| +добавлено | case 'ping': |
| +добавлено | return isRequest && write({ jsonrpc: '2.0', id, result: {} }); |
| +добавлено | case 'tools/list': |
| +добавлено | return isRequest && write({ |
| +добавлено | jsonrpc: '2.0', id, |
| +добавлено | result: { tools: tools.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, annotations })) }, |
| +добавлено | }); |
| +добавлено | case 'tools/call': |
| +добавлено | return isRequest && write({ jsonrpc: '2.0', id, result: await callTool(params) }); |
| +добавлено | default: |
| +добавлено | return isRequest && write({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } }); |
| +добавлено | } |
| +добавлено | } catch (err) { |
| +добавлено | if (isRequest) write({ jsonrpc: '2.0', id, error: { code: -32603, message: String(err?.message ?? err) } }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const rl = createInterface({ input: process.stdin, crlfDelay: Infinity }); |
| +добавлено | const inflight = new Set(); |
| +добавлено | rl.on('line', (line) => { |
| +добавлено | const s = line.trim(); |
| +добавлено | if (!s) return; |
| +добавлено | let msg; |
| +добавлено | try { |
| +добавлено | msg = JSON.parse(s); |
| +добавлено | } catch { |
| +добавлено | write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const batch = Array.isArray(msg) ? msg : [msg]; |
| +добавлено | for (const m of batch) { |
| +добавлено | const p = handle(m).finally(() => inflight.delete(p)); |
| +добавлено | inflight.add(p); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | rl.on('close', async () => { |
| +добавлено | await Promise.allSettled([...inflight]); |
| +добавлено | process.exit(0); |
| +добавлено | }); |
| +добавлено | #!/usr/bin/env node |
| +добавлено | // Хук SessionStart плагина aura-team: сообщает сервису cwd сессии и подкладывает агенту |
| +добавлено | // короткий список моих задач. Никогда не роняет сессию: всегда exit 0, общий таймаут 3 с. |
| +добавлено | // |
| +добавлено | // ZCode разбирает stdout хука только как JSON (HookJSONOutput); обычный текст игнорируется. |
| +добавлено | // Поэтому контекст отдаётся как hookSpecificOutput.additionalContext. |
| +добавлено | |
| +добавлено | import { post, agentRpc, taskLine } from './client.mjs'; |
| +добавлено | |
| +добавлено | const hardStop = setTimeout(() => process.exit(0), 3000); |
| +добавлено | hardStop.unref(); |
| +добавлено | |
| +добавлено | function readStdin(ms = 800) { |
| +добавлено | return new Promise((resolve) => { |
| +добавлено | if (process.stdin.isTTY) return resolve(''); |
| +добавлено | let data = ''; |
| +добавлено | const done = () => { process.stdin.pause(); resolve(data); }; |
| +добавлено | const t = setTimeout(done, ms); |
| +добавлено | process.stdin.setEncoding('utf8'); |
| +добавлено | process.stdin.on('data', (c) => { data += c; if (data.length > 1_000_000) { clearTimeout(t); done(); } }); |
| +добавлено | process.stdin.on('end', () => { clearTimeout(t); done(); }); |
| +добавлено | process.stdin.on('error', () => { clearTimeout(t); done(); }); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function main() { |
| +добавлено | let input = {}; |
| +добавлено | try { input = JSON.parse((await readStdin()) || '{}'); } catch { input = {}; } |
| +добавлено | const cwd = input.cwd || process.env.ZCODE_PROJECT_DIR || process.env.CLAUDE_PROJECT_DIR || process.cwd(); |
| +добавлено | const sessionId = input.session_id || input.sessionId || process.env.ZCODE_SESSION_ID || undefined; |
| +добавлено | |
| +добавлено | let ctx; |
| +добавлено | try { |
| +добавлено | ctx = await post('/ide/context', { cwd, event: input.hook_event_name || 'SessionStart', sessionId }, { timeoutMs: 1200 }); |
| +добавлено | } catch { |
| +добавлено | return; // сервис не запущен — молчим |
| +добавлено | } |
| +добавлено | if (!ctx?.signedIn || !ctx?.teamId) return; |
| +добавлено | |
| +добавлено | let r; |
| +добавлено | try { |
| +добавлено | r = await agentRpc('myTasks', {}, { timeoutMs: 1600 }); |
| +добавлено | } catch { |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const tasks = r?.tasks ?? []; |
| +добавлено | const team = r?.teamName ?? r?.teamId; |
| +добавлено | const lines = []; |
| +добавлено | if (tasks.length === 0) { |
| +добавлено | lines.push(`Aura Team · команда «${team}»: у вас нет открытых задач.`); |
| +добавлено | } else { |
| +добавлено | const order = { doing: 0, review: 1, todo: 2 }; |
| +добавлено | const sorted = [...tasks].sort((a, b) => (order[a.status] ?? 3) - (order[b.status] ?? 3)); |
| +добавлено | lines.push(`Aura Team · команда «${team}»: у вас ${tasks.length} ${plural(tasks.length, 'открытая задача', 'открытые задачи', 'открытых задач')}:`); |
| +добавлено | for (const t of sorted.slice(0, 8)) lines.push(`- ${taskLine(t)}`); |
| +добавлено | if (tasks.length > 8) lines.push(`- …и ещё ${tasks.length - 8} (инструмент team_my_tasks)`); |
| +добавлено | } |
| +добавлено | lines.push('Задачи — через инструменты aura-team (team_*); начали работу — team_move_task doing, закончили — review; в коммите указывайте #<shortId>.'); |
| +добавлено | // ZCode обрезает вывод хука (hooks.maxOutputBytes, по умолчанию 4096) — держим запас. |
| +добавлено | let out = lines.slice(0, 12); |
| +добавлено | const render = () => JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: out.join('\n') } }); |
| +добавлено | while (Buffer.byteLength(render()) > 3500 && out.length > 2) out.splice(out.length - 2, 1); |
| +добавлено | process.stdout.write(`${render()}\n`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function plural(n, one, few, many) { |
| +добавлено | const m10 = n % 10; |
| +добавлено | const m100 = n % 100; |
| +добавлено | if (m10 === 1 && m100 !== 11) return one; |
| +добавлено | if (m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14)) return few; |
| +добавлено | return many; |
| +добавлено | } |
| +добавлено | |
| +добавлено | main().catch(() => {}).finally(() => process.exit(0)); |
| +добавлено | --- |
| +добавлено | name: aura-team |
| +добавлено | description: Задачи команды Aura Team (канбан). Используй, когда пользователь говорит о задачах, канбане, доске, команде, «задачах команды», «моих задачах», исполнителях, дедлайнах или просит взять/закрыть задачу. |
| +добавлено | --- |
| +добавлено | |
| +добавлено | # Aura Team |
| +добавлено | |
| +добавлено | Задачи команды живут на канбан-доске Aura Team. Работай с ними через MCP-инструменты `aura-team`: |
| +добавлено | |
| +добавлено | - `team_my_tasks` — мои открытые задачи; `team_board` — вся доска (фильтр `status`); `team_get_task` — карточка с историей и коммитами. |
| +добавлено | - `team_create_task`, `team_update_task`, `team_move_task` — создать, изменить, переместить. Удалять задачи нельзя. |
| +добавлено | - `team_members`, `team_whoami`, `team_activity` — участники, кто я, лента. |
| +добавлено | |
| +добавлено | Правила: |
| +добавлено | |
| +добавлено | 1. Ссылайся на задачи как `#<shortId>` (первые 8 символов id), например `#1a2b3c4d`. |
| +добавлено | 2. Начинаешь работу над задачей — `team_move_task` в `doing`. Закончил — в `review` (не в `done`: закрывает человек после проверки). |
| +добавлено | 3. В сообщение коммита добавляй `#<shortId>` — коммит привяжется к задаче. |
| +добавлено | 4. Нашёл новую работу вне задач — предложи `team_create_task`, не создавай молча пачками. |
| +добавлено | 5. Если инструмент ответил, что сервис не запущен или вход не выполнен, — скажи об этом одной строкой и продолжай без доски. |
| +добавлено | { |
| +добавлено | "name": "my-helper", |
| +добавлено | "version": "0.1.0", |
| +добавлено | "description": "Мой локальный плагин: пример для собственного маркетплейса.", |
| +добавлено | "author": { "name": "isaog" }, |
| +добавлено | "license": "MIT", |
| +добавлено | "skills": "skills" |
| +добавлено | } |
| +добавлено | --- |
| +добавлено | name: hello |
| +добавлено | description: Приветствие из локального маркетплейса. Используй, когда просят проверить, что плагин установлен. |
| +добавлено | --- |
| +добавлено | |
| +добавлено | # Hello |
| +добавлено | |
| +добавлено | Ответь одной строкой: «локальный плагин работает». |
| +добавлено | provider: generic |
| +добавлено | useMultipleRangeRequest: false |
| +добавлено | url: http://127.0.0.1:9 |
| +добавлено | updaterCacheDirName: '@zcodedesktop-updater' |
| +добавлено | { |
| +добавлено | "feedback_url": "https://zhipu-ai.feishu.cn/share/base/form/shrcnrXlh93cJIUFYBFndnnL7pe", |
| +добавлено | "feedback_use_external_form": false, |
| +добавлено | "community_urls": { |
| +добавлено | "zh-CN": "https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=47ag983c-8fcb-4d6d-814b-5395193a712c&qr_code=true", |
| +добавлено | "en-US": "https://discord.gg/z9aBcQXZQ3" |
| +добавлено | } |
| +добавлено | } |
| +добавлено | {"schemaVersion":1,"revision":1033,"config":{"providerConfigRules":{"templateRules":[{"templateId":"moonshot-kimi","templateNameMap":{"zh-CN":"Kimi","en-US":"Kimi"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.kimi.com/console/api-keys"},"api":{"type":"anthropic-messages","baseUrl":"https://api.moonshot.cn/anthropic"},"builtinModelIds":["kimi-k3","kimi-k2.7-code","kimi-k2.6","kimi-k2.7-code-highspeed","k3","k3-256k"],"logo":{"type":"builtin","key":"moonshot-kimi"}}},{"templateId":"minimax","templateNameMap":{"zh-CN":"MiniMax","en-US":"MiniMax"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.minimaxi.com/console/access?tab=api-keys"},"api":{"type":"anthropic-messages","baseUrl":"https://api.minimaxi.com/anthropic"},"builtinModelIds":["MiniMax-M3","MiniMax-M2.7","MiniMax-M2.7-highspeed","MiniMax-M2.5","MiniMax-M2.5-highspeed","MiniMax-M2.1","MiniMax-M2.1-highspeed","MiniMax-M2"],"logo":{"type":"builtin","key":"minimax"}}},{"templateId":"deepseek","templateNameMap":{"zh-CN":"DeepSeek","en-US":"DeepSeek"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.deepseek.com/api_keys"},"api":{"type":"anthropic-messages","baseUrl":"https://api.deepseek.com/anthropic"},"builtinModelIds":["deepseek-flash","deepseek-v4-pro"],"logo":{"type":"builtin","key":"deepseek"}}},{"templateId":"qwen-alibaba-model-studio-cn","templateNameMap":{"zh-CN":"阿里云百炼(中国)","en-US":"Alibaba Cloud (China)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://bailian.console.aliyun.com/cn-beijing?tab=model"},"api":{"type":"anthropic-messages","baseUrl":"https://dashscope.aliyuncs.com/apps/anthropic"},"builtinModelIds":["qwen3.8-max","qwen3.8-flash","qwen3.7-max","qwen3.7-plus","qwen3.7-flash","qwen3.6-plus","qwen3.6-flash","qwen3.5-plus","qwen3.5-flash","qwen3-max","qwen-plus","qwen-flash","qwen3-vl-plus"],"logo":{"type":"builtin","key":"alibaba-model-studio"}}},{"templateId":"qwen-alibaba-model-studio-intl","templateNameMap":{"zh-CN":"阿里云百炼(国际)","en-US":"Alibaba Cloud (Global)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://modelstudio.console.aliyun.com/ap-southeast-1?tab=dashboard"},"api":{"type":"openai-chat-completions","baseUrl":"https://dashscope-intl.aliyuncs.com/compatible-mode/v1"},"builtinModelIds":["qwen3.8-max","qwen3.8-flash","qwen3.8-omni-flash","qwen3.7-max","qwen3.7-plus","qwen3.7-flash","qwen3.6-plus","qwen3.6-flash","qwen3.5-plus","qwen3.5-flash","qwen3-max","qwen-plus","qwen-flash","qwen3-vl-plus"],"logo":{"type":"builtin","key":"alibaba-model-studio"}}},{"templateId":"xiaomi-mimo","templateNameMap":{"zh-CN":"Xiaomi MiMo API","en-US":"Xiaomi MiMo API"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.xiaomimimo.com/"},"api":{"type":"anthropic-messages","baseUrl":"https://api.xiaomimimo.com/anthropic"},"builtinModelIds":["mimo-v2.6-pro","mimo-v2.6-flash","mimo-v2.5-pro","mimo-v2.5"],"logo":{"type":"builtin","key":"xiaomi-mimo"}}},{"templateId":"xiaomi-mimo-token-plan","templateNameMap":{"zh-CN":"Xiaomi MiMo Token Plan","en-US":"Xiaomi MiMo Token Plan"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.xiaomimimo.com/"},"api":{"type":"anthropic-messages","baseUrl":"https://token-plan-cn.xiaomimimo.com/anthropic"},"builtinModelIds":["mimo-v2.6-pro","mimo-v2.6-flash"],"logo":{"type":"builtin","key":"xiaomi-mimo"}}},{"templateId":"openai","templateNameMap":{"zh-CN":"OpenAI","en-US":"OpenAI"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://platform.openai.com/api-keys"},"api":{"type":"openai-responses","baseUrl":"https://api.openai.com/v1"},"builtinModelIds":["gpt-6-astra","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.6","gpt-5.4","gpt-5.4-pro","gpt-5.4-mini","gpt-5.4-nano","gpt-5.3-codex"],"logo":{"type":"builtin","key":"openai"}}},{"templateId":"anthropic","templateNameMap":{"zh-CN":"Anthropic","en-US":"Anthropic"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://console.anthropic.com/settings/keys"},"api":{"type":"anthropic-messages","baseUrl":"https://api.anthropic.com/v1"},"builtinModelIds":["claude-fable-5-1","claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],"logo":{"type":"builtin","key":"anthropic"}}},{"templateId":"xai","templateNameMap":{"zh-CN":"xAI","en-US":"xAI"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://console.x.ai"},"api":{"type":"openai-responses","baseUrl":"https://api.x.ai/v1"},"builtinModelIds":["grok-4.6","grok-build-0.1","grok-4.3"],"logo":{"type":"builtin","key":"xai"}}},{"templateId":"openrouter","templateNameMap":{"zh-CN":"OpenRouter","en-US":"OpenRouter"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://openrouter.ai/keys"},"api":{"type":"anthropic-messages","baseUrl":"https://openrouter.ai/api"},"builtinModelIds":["anthropic/claude-fable-5.1","openai/gpt-6-astra","openai/gpt-5.6-sol","anthropic/claude-opus-5","deepseek/deepseek-v4-pro","moonshotai/kimi-k3","z-ai/glm-5.3","qwen/qwen3.8-max","minimax/minimax-m3","xiaomi/mimo-v2.5-pro","x-ai/grok-4.6","deepseek/deepseek-v4.1-flash","qwen/qwen3.8-max-0902","openai/gpt-5.6-terra","openai/gpt-5.6-luna","openai/gpt-5.6","openai/gpt-5.4","openai/gpt-5.4-pro","openai/gpt-5.4-mini","openai/gpt-5.4-nano","openai/gpt-5.3-codex","anthropic/claude-sonnet-5","anthropic/claude-haiku-4.5","anthropic/claude-opus-4.8","anthropic/claude-opus-4.7","anthropic/claude-opus-4.6","anthropic/claude-opus-4.5","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet-4.5","deepseek/deepseek-v4-flash","moonshotai/kimi-k2.7-code","moonshotai/kimi-k2.6","moonshotai/kimi-k2.5","z-ai/glm-5.3-flash","z-ai/glm-5.2","z-ai/glm-5.1","z-ai/glm-5v-turbo","z-ai/glm-5","z-ai/glm-5-turbo","z-ai/glm-4.7","z-ai/glm-4.7-flash","z-ai/glm-4.6","z-ai/glm-4.6v","z-ai/glm-4.5-air","z-ai/glm-4.5","qwen/qwen3.8-flash","qwen/qwen3.7-max","qwen/qwen3.7-plus","qwen/qwen3.7-flash","qwen/qwen3.6-plus","qwen/qwen3.6-flash","qwen/qwen3.5-plus-20260420","qwen/qwen3-vl-plus","qwen/qwen3-vl-flash","minimax/minimax-m2.7","minimax/minimax-m2.5","xiaomi/mimo-v2.5","x-ai/grok-build-0.1","x-ai/grok-4.3"],"logo":{"type":"builtin","key":"openrouter"}}},{"templateId":"opencode-go-chat","templateNameMap":{"zh-CN":"OpenCode Go (Chat)","en-US":"OpenCode Go (Chat)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"openai-chat-completions","baseUrl":"https://opencode.ai/zen/go/v1"},"builtinModelIds":["glm-5.3-flash","glm-5.3","kimi-k3","kimi-k2.7-code","deepseek-v4.1-flash","deepseek-v4-pro","mimo-v2.5","mimo-v2.5-pro","glm-5.2","glm-5.1","kimi-k2.6","deepseek-v4-flash","deepseek-v4-flash-vision-exp","hy4-preview","hy3"],"logo":{"type":"builtin","key":"opencode"}}},{"templateId":"opencode-go-messages","templateNameMap":{"zh-CN":"OpenCode Go (Anthropic)","en-US":"OpenCode Go (Anthropic)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"anthropic-messages","baseUrl":"https://opencode.ai/zen/go/v1"},"builtinModelIds":["minimax-m3","qwen3.8-max","qwen3.8-flash","minimax-m2.7","minimax-m2.5","qwen3.7-max","qwen3.7-plus","qwen3.6-plus"],"logo":{"type":"builtin","key":"opencode"}}},{"templateId":"opencode-go-responses","templateNameMap":{"zh-CN":"OpenCode Go (Responses)","en-US":"OpenCode Go (Responses)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"openai-responses","baseUrl":"https://opencode.ai/zen/go/v1"},"builtinModelIds":["gpt-5.6-luna","grok-4.6"],"logo":{"type":"builtin","key":"opencode"}}},{"templateId":"opencode-zen-responses","templateNameMap":{"zh-CN":"OpenCode Zen (Responses)","en-US":"OpenCode Zen (Responses)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"openai-responses","baseUrl":"https://opencode.ai/zen/v1"},"builtinModelIds":["gpt-6-astra","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.5","gpt-5.5-pro","gpt-5.4","gpt-5.4-pro","gpt-5.4-mini","gpt-5.4-nano","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.2","gpt-5.1"],"logo":{"type":"builtin","key":"opencode"}}},{"templateId":"opencode-zen-messages","templateNameMap":{"zh-CN":"OpenCode Zen (Anthropic)","en-US":"OpenCode Zen (Anthropic)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"anthropic-messages","baseUrl":"https://opencode.ai/zen/v1"},"builtinModelIds":["claude-fable-5-1","claude-fable-5","qwen3.7-max","qwen3.6-plus","qwen3.5-plus","claude-opus-5","claude-sonnet-5","claude-haiku-4-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-opus-4-5","claude-sonnet-4-6","claude-sonnet-4-5","qwen3.7-plus"],"logo":{"type":"builtin","key":"opencode"}}},{"templateId":"opencode-zen-chat","templateNameMap":{"zh-CN":"OpenCode Zen (Chat)","en-US":"OpenCode Zen (Chat)"},"config":{"access":{"type":"api-key","apiKeyManagementUrl":"https://opencode.ai/auth"},"api":{"type":"openai-chat-completions","baseUrl":"https://opencode.ai/zen/v1"},"builtinModelIds":["kimi-k3","minimax-m3","deepseek-v4-pro","glm-5.2","big-pickle","mimo-v2.5-free","hy3-free","ling-3.0-flash-fin-free","nemotron-3-ultra-free","muse-spark-1.2-contributor-free","minimax-m2.7","deepseek-v4-flash","glm-5.1","nemotron-3.5-lightning-free"],"logo":{"type":"builtin","key":"opencode"}}}],"providerRules":[]},"modelConfigRules":{"modelRules":[{"modelMatch":".*","config":{"enabled":true,"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsAudio":false,"supportsPdf":false},"outputFormat":{"supportsText":true},"supportsToolCall":true,"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false,"supportsMidConversationSystem":false,"requiresMfjsToolSchema":false},"optionSpecs":{"maxOutputTokens":{"max":128000},"reasoningLevel":{"values":["disabled","enabled"],"map":"{}"}}}},{"modelMatch":".*glm-5.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":64000}}}},{"modelMatch":".*GLM-5\\.2.*","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","high","max"]},"maxOutputTokens":{"max":128000}}}},{"modelMatch":".*GLM-5-Turbo.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":64000}}}},{"modelMatch":".*glm-5\\.3.*","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"]},"maxOutputTokens":{"max":128000}}}},{"modelMatch":".*glm-5\\.3-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true,"supportsPdf":true}}}},{"modelMatch":".*glm-5\\.1.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":64000}}}},{"modelMatch":".*glm-5\\.1-highspeed.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":64000}}}},{"modelMatch":".*glm-5v-turbo.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*glm-4\\.7.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*glm-4\\.7-flash.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*glm-4\\.7-flashx.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*glm-4\\.6.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*glm-4\\.5.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":98304}}}},{"modelMatch":".*glm-4\\.5-air.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":98304}}}},{"modelMatch":".*glm-4\\.6v.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*glm-4\\.6v-flash.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*glm-4\\.6v-flashx.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*glm-4\\.1v-thinking-flash.*","config":{"properties":{"contextWindow":65536,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*glm-4\\.1v-thinking-flashx.*","config":{"properties":{"contextWindow":65536,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*glm-4-flashx-250414.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":16384}}}},{"modelMatch":".*glm-4-flash-250414.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":16384}}}},{"modelMatch":".*glm-4v-flash.*","config":{"properties":{"contextWindow":16384,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":1024}}}},{"modelMatch":".*codegeex-4.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*charglm-4.*","config":{"properties":{"contextWindow":8192,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":4096}}}},{"modelMatch":".*emohaa.*","config":{"properties":{"contextWindow":8192,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":4096}}}},{"modelMatch":".*gpt-5\\.6.*","config":{"properties":{"contextWindow":1050000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["none","low","medium","high","xhigh","max"]}}}},{"modelMatch":".*gpt-5\\.3-codex.*","config":{"properties":{"contextWindow":400000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh"]}}}},{"modelMatch":".*gpt-6-astra.*","config":{"properties":{"contextWindow":1050000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh","max"]}}}},{"modelMatch":".*gpt-5\\.4.*","config":{"properties":{"contextWindow":1050000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["none","low","medium","high","xhigh"]}}}},{"modelMatch":".*gpt-5\\.4-pro.*","config":{"properties":{"contextWindow":1050000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["medium","high","xhigh"]}}}},{"modelMatch":".*gpt-5\\.4-mini.*","config":{"properties":{"contextWindow":400000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["none","low","medium","high","xhigh"]}}}},{"modelMatch":".*gpt-5\\.4-nano.*","config":{"properties":{"contextWindow":400000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["none","low","medium","high","xhigh"]}}}},{"modelMatch":".*claude-(?:fable|opus|sonnet)-5.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh","max"]}}}},{"modelMatch":".*claude-haiku-4[.-]5.*","config":{"properties":{"contextWindow":200000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"maxOutputTokens":{"max":64000}}}},{"modelMatch":".*claude-(?:fable|mythos)-5[.-]1.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh","max"]}}}},{"modelMatch":".*grok-4\\.6.*","config":{"properties":{"contextWindow":500000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":false},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh"]}}}},{"modelMatch":".*grok-build-0\\.1.*","config":{"properties":{"contextWindow":256000,"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":false},"supportsJsonSchemaOutput":true}}},{"modelMatch":".*grok-4\\.3.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":false,"supportsAudio":false,"supportsPdf":false},"supportsJsonSchemaOutput":true}}},{"modelMatch":".*kimi-k3.*","config":{"properties":{"contextWindow":1048576,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*k3.*","config":{"properties":{"contextWindow":1048576,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*k3-256k.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*kimi-k2\\.7-code.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"reasoningLevel":{"values":["enabled"]},"maxOutputTokens":{"max":98304}}}},{"modelMatch":".*kimi-k2\\.6.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":98304}}}},{"modelMatch":".*kimi-k2\\.5.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":98304}}}},{"modelMatch":".*moonshot-v1-8k.*","config":{"properties":{"contextWindow":8192,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*moonshot-v1-32k.*","config":{"properties":{"contextWindow":32768,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*moonshot-v1-128k.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*moonshot-v1-8k-vision-preview.*","config":{"properties":{"contextWindow":8192,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*moonshot-v1-32k-vision-preview.*","config":{"properties":{"contextWindow":32768,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*moonshot-v1-128k-vision-preview.*","config":{"properties":{"contextWindow":131072,"inputFormat":{"supportsImage":true,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M3.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*MiniMax-M2\\.7.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2\\.7-highspeed.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2\\.5.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2\\.5-highspeed.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2\\.1.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*MiniMax-M2\\.1-highspeed.*","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":32000}}}},{"modelMatch":".*deepseek-v4-flash.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","low","high","max"]},"maxOutputTokens":{"max":384000}}}},{"modelMatch":".*deepseek-v4-pro.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","low","high","max"]},"maxOutputTokens":{"max":384000}}}},{"modelMatch":".*deepseek-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":false},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","low","high","max"]},"maxOutputTokens":{"max":384000}}}},{"modelMatch":".*deepseek-v4[.-]1-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":false},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","low","high","max"]},"maxOutputTokens":{"max":384000}}}},{"modelMatch":".*qwen3\\.8-(?:max|flash).*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["low","medium","xhigh"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*qwen3\\.5-plus.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen3\\.5-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen3-max.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen-plus.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*qwen-flash.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*qwen3-vl-plus.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":32768}}}},{"modelMatch":".*qwen3\\.7-max.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*qwen3\\.7-plus.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*qwen3\\.7-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*qwen3\\.6-plus.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen3\\.6-flash.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen3\\.7-max-2026-06-08.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}}}},{"modelMatch":".*qwen3\\.8-omni-flash.*","config":{"properties":{"contextWindow":65536,"inputFormat":{"supportsImage":true,"supportsVideo":true,"supportsAudio":true},"supportsJsonSchemaOutput":false},"optionSpecs":{"reasoningLevel":{"values":["none","minimal","low","medium","high","xhigh","max"]},"maxOutputTokens":{"max":16384}}}},{"modelMatch":".*mimo-v2\\.6-(?:pro|flash).*","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsImage":true,"supportsVideo":true,"supportsAudio":true}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*mimo-v2\\.5.*","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true,"supportsAudio":true}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*mimo-v2\\.5-pro.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false,"supportsAudio":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*mimo-v2-pro.*","config":{"properties":{"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*mimo-v2-omni.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":true,"supportsVideo":true}},"optionSpecs":{"maxOutputTokens":{"max":131072}}}},{"modelMatch":".*mimo-v2-flash.*","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsImage":false,"supportsVideo":false}},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}}],"modelApiRules":[{"modelMatch":".*claude-(?:opus-(?:4[.-]8|5)|(?:fable|mythos)-5(?:[.-]1)?).*","apiTypeMatch":"anthropic-messages","config":{"properties":{"supportsMidConversationSystem":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel == \"enabled\" ? \"high\" : reasoningLevel\n }\n }"},"maxOutputTokens":{"map":"{'max_tokens': maxOutputTokens}"}}}},{"modelMatch":".*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"disabled\" || reasoningLevel == \"none\" ? \"disabled\" : \"enabled\"\n },\n \"enable_thinking\": reasoningLevel != \"disabled\" && reasoningLevel != \"none\",\n \"reasoning_effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel == \"enabled\" ? \"high\" : reasoningLevel,\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel == \"enabled\" ? \"high\" : reasoningLevel\n }\n}"},"maxOutputTokens":{"map":"{'max_completion_tokens': maxOutputTokens}"}}}},{"modelMatch":".*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel == \"enabled\" ? \"high\" : reasoningLevel\n }\n}"},"maxOutputTokens":{"map":"{'max_output_tokens': maxOutputTokens}"}}}},{"modelMatch":".*(?:ox-alpha|glm-x-preview-f|x-preview-f-free).*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*(?:ox-alpha|glm-x-preview-f|x-preview-f-free).*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*glm-5.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*GLM-5\\.2.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}}},{"modelMatch":".*GLM-5-Turbo.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-5\\.3.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*glm-5\\.1.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-5\\.1-highspeed.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-5v-turbo.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.7.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.7-flashx.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.7-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.6(?!v).*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.5.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*glm-4\\.5-air.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*gpt-5\\.6.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*gpt-5\\.3-codex.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*claude-(?:fable|opus|sonnet)-5.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*grok-4\\.6.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*kimi-k3.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*kimi-k3.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*k3.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*k3.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*k3-256k.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*k3-256k.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*kimi-k2\\.7-code.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"disabled\" ? \"disabled\" : \"enabled\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.7-code.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"disabled\" ? \"disabled\" : \"enabled\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.7-code.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : \"high\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.6.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.6.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.5.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*kimi-k2\\.5.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*deepseek-v4-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}}},{"modelMatch":".*deepseek-v4-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"reasoning_effort\": reasoningLevel\n }"}}}},{"modelMatch":".*deepseek-v4-pro.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}}},{"modelMatch":".*deepseek-v4-pro.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"reasoning_effort\": reasoningLevel\n }"}}}},{"modelMatch":".*qwen3\\.8-(?:max|flash).*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*qwen3\\.8-(?:max|flash).*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*qwen3\\.8-(?:max|flash).*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*qwen3\\.5-plus.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen3\\.5-plus.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*qwen3\\.5-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen3\\.5-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*qwen-plus.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen-plus.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*qwen-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*qwen3-vl-plus.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen3-vl-plus.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*mimo-v2\\.6-(?:pro|flash).*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2\\.5.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2\\.5.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2\\.5-pro.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2\\.5-pro.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*mimo-v2-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*gpt-6-astra.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*claude-(?:fable|mythos)-5[.-]1.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*deepseek-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}}},{"modelMatch":".*deepseek-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"reasoning_effort\": reasoningLevel\n }"}}}},{"modelMatch":".*gpt-5\\.4.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*gpt-5\\.4.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*deepseek-v4[.-]1-flash.*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}}},{"modelMatch":".*deepseek-v4[.-]1-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"enabled\"\n },\n \"reasoning_effort\": reasoningLevel\n }"}}}},{"modelMatch":".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash)).*","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"enabled\" ? \"enabled\" : \"disabled\"\n }\n}"}}}},{"modelMatch":".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash)).*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"enable_thinking\": reasoningLevel == \"enabled\"}"}}}},{"modelMatch":".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash)).*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : \"high\"\n }\n}"}}}},{"modelMatch":".*qwen3\\.8-omni-flash.*","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\"reasoning_effort\": reasoningLevel}"}}}},{"modelMatch":".*qwen3\\.8-omni-flash.*","apiTypeMatch":"openai-responses","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"}}}}],"providerSiteRules":[{"modelMatch":"glm-5\\.3-flash","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":true,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":131072,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"glm-5\\.3","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":131072,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"glm-5\\.2","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":131072,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"glm-5\\.1","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":202752,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":32768,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"kimi-k3","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1048576,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":131072,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"kimi-k2\\.7-code","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":262144,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"kimi-k2\\.6","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":262144,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":65536,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"deepseek-v4\\.1-flash","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":384000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"deepseek-v4-pro","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":384000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"deepseek-v4-flash","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":384000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"deepseek-v4-flash-vision-exp","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","high","max"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":384000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"mimo-v2\\.5","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":true},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":128000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"mimo-v2\\.5-pro","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1048576,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":128000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"hy4-preview","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1024000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["none","high"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":64000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"hy3","apiTypeMatch":"openai-chat-completions","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":256000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["none","low","high"],"map":"{\"reasoning_effort\": reasoningLevel}"},"maxOutputTokens":{"max":128000,"map":"{\"max_tokens\": maxOutputTokens}"}}}},{"modelMatch":"minimax-m3","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"],"map":"{\n \"thinking\": {\n \"type\": reasoningLevel == \"disabled\" ? \"disabled\" : \"adaptive\"\n }\n}"},"maxOutputTokens":{"max":131072}}}},{"modelMatch":"minimax-m2\\.7","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":131072}}}},{"modelMatch":"minimax-m2\\.5","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":204800,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["enabled"],"map":"{}"},"maxOutputTokens":{"max":65536}}}},{"modelMatch":"qwen3\\.8-max","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","medium","xhigh"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":"qwen3\\.8-flash","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","medium","xhigh"]},"maxOutputTokens":{"max":131072}}}},{"modelMatch":"qwen3\\.7-max","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":false,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":"qwen3\\.7-plus","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":"qwen3\\.6-plus","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1000000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":true,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":false,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["disabled","enabled"]},"maxOutputTokens":{"max":65536}}}},{"modelMatch":"gpt-5\\.6-luna","apiTypeMatch":"openai-responses","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":1050000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":false,"supportsPdf":true,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["none","low","medium","high","xhigh","max"],"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"},"maxOutputTokens":{"max":128000}}}},{"modelMatch":"grok-4\\.6","apiTypeMatch":"openai-responses","baseUrlMatch":"https://opencode\\.ai/zen/go/v1/?","config":{"properties":{"contextWindow":500000,"inputFormat":{"supportsText":true,"supportsImage":true,"supportsVideo":false,"supportsPdf":false,"supportsAudio":false},"supportsJsonSchemaOutput":true,"supportsNativeWebSearch":false},"optionSpecs":{"reasoningLevel":{"values":["low","medium","high","xhigh"],"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n}"},"maxOutputTokens":{"max":500000}}}},{"modelMatch":".*(?:glm-|deepseek-|kimi-k2|qwen|mimo-).*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\" || reasoningLevel == \"none\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"output_config\": {\n \"effort\": reasoningLevel == \"enabled\" ? \"high\" : reasoningLevel\n }\n }"}}}},{"modelMatch":".*","baseUrlMatch":"https://api\\.z\\.ai/api/anthropic/?","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}}}},{"modelMatch":".*","baseUrlMatch":"https://open\\.bigmodel\\.cn/api/anthropic/?","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}}}},{"modelMatch":".*","baseUrlMatch":"https://zcode\\.z\\.ai/api/v1/zcode-plan/anthropic/?","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}}}},{"modelMatch":".*","baseUrlMatch":"https://zcode\\.z\\.ai/api/v1/highspeed/anthropic/?","config":{"properties":{"inputFormat":{"supportsImage":true,"supportsVideo":true}}}},{"modelMatch":".*claude-.*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"(?:https://api\\.anthropic\\.com/v1)","config":{"properties":{"supportsNativeWebSearch":true}}},{"modelMatch":".*(?:kimi-k3|k3|k3-256k)(?:[.\\-:/\\[].*)?","apiTypeMatch":"anthropic-messages","baseUrlMatch":"(?:https://api\\.moonshot\\.cn/anthropic)","config":{"properties":{"requiresMfjsToolSchema":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"(?:https://api\\.deepseek\\.com/anthropic)","config":{"properties":{"supportsNativeWebSearch":true,"supportsMidConversationSystem":true}}},{"modelMatch":".*gpt-5\\.(?:6(?:-(?:sol|terra|luna))?|3-codex)(?:[.\\-:/\\[].*)?","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://api\\.z\\.ai/api/anthropic/?","config":{"properties":{"supportsNativeWebSearch":true,"supportsMidConversationSystem":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://open\\.bigmodel\\.cn/api/anthropic/?","config":{"properties":{"supportsNativeWebSearch":true,"supportsMidConversationSystem":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://zcode\\.z\\.ai/api/v1/zcode-plan/anthropic/?","config":{"properties":{"supportsNativeWebSearch":true,"supportsMidConversationSystem":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://zcode\\.z\\.ai/api/v1/off-peak/anthropic/?","config":{"properties":{"supportsNativeWebSearch":false,"supportsMidConversationSystem":true}}},{"modelMatch":".*","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://zcode\\.z\\.ai/api/v1/highspeed/anthropic/?","config":{"properties":{"supportsNativeWebSearch":true,"supportsMidConversationSystem":true}}},{"modelMatch":"deepseek-v4-flash","apiTypeMatch":"openai-responses","baseUrlMatch":"https://api\\.deepseek\\.com(?:/.*)?","config":{"properties":{"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel\n }\n}"}}}},{"modelMatch":"deepseek-v4-pro","apiTypeMatch":"openai-responses","baseUrlMatch":"https://api\\.deepseek\\.com(?:/.*)?","config":{"properties":{"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel\n }\n}"}}}},{"modelMatch":"deepseek-flash","apiTypeMatch":"openai-responses","baseUrlMatch":"https://api\\.deepseek\\.com(?:/.*)?","config":{"properties":{"supportsJsonSchemaOutput":true},"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"effort\": reasoningLevel == \"disabled\" ? \"none\" : reasoningLevel\n }\n}"}}}},{"modelMatch":"deepseek-v4-flash(?:-vision-exp)?","baseUrlMatch":"https://api\\.deepseek\\.com(?:/.*)?","apiTypeMatch":".*","config":{"properties":{"inputFormat":{"supportsImage":true}}}},{"modelMatch":".*gpt-6-astra(?:[.\\-:/\\[].*)?","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n}"}}}},{"modelMatch":".*gpt-5\\.4(?:-(?:pro|mini|nano))?(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":"anthropic-messages","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"none\"\n ? {\n \"thinking\": {\n \"type\": \"disabled\"\n }\n }\n : {\n \"output_config\": {\n \"effort\": reasoningLevel\n }\n }"}}},"baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?"},{"modelMatch":".*deepseek-v4[.-]1-flash(?:[.\\-:/\\[].*)?","apiTypeMatch":".*","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"properties":{"contextWindow":1048576,"supportsJsonSchemaOutput":true}}},{"modelMatch":".*deepseek-v4[.-]1-flash(?:[.\\-:/\\[].*)?","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"reasoningLevel == \"disabled\"\n ? {\n \"reasoning\": {\n \"enabled\": false\n }\n }\n : {\n \"reasoning\": {\n \"effort\": reasoningLevel\n }\n }"}}},"baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?"},{"modelMatch":".*qwen3\\.(?:7-(?:max|plus|flash)|6-(?:plus|flash))(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":"openai-chat-completions","config":{"optionSpecs":{"reasoningLevel":{"map":"{\n \"reasoning\": {\n \"enabled\": reasoningLevel == \"enabled\"\n }\n}"}}},"baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?"},{"modelMatch":".*qwen3\\.7-flash(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":".*","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"optionSpecs":{"maxOutputTokens":{"max":65536}}}},{"modelMatch":".*qwen3\\.7-plus(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":".*","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"properties":{"inputFormat":{"supportsVideo":false}}}},{"modelMatch":".*qwen3\\.7-(?:max|plus|flash)(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://dashscope\\.aliyuncs\\.com/apps/anthropic/?","config":{"properties":{"supportsJsonSchemaOutput":true}}},{"modelMatch":".*qwen3\\.7-(?:max|plus|flash)(?:-20\\d{2}(?:-?\\d{2}){2})?(?:[:/\\[].*)?","apiTypeMatch":"anthropic-messages","baseUrlMatch":"https://dashscope-intl\\.aliyuncs\\.com/apps/anthropic/?","config":{"properties":{"supportsJsonSchemaOutput":true}}},{"modelMatch":"qwen/qwen3\\.8-max-0902","apiTypeMatch":".*","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"optionSpecs":{"reasoningLevel":{"values":["minimal","low","medium","high","xhigh"]}}}},{"modelMatch":"qwen/qwen3\\.6-(?:plus|flash)","apiTypeMatch":".*","baseUrlMatch":"https://openrouter\\.ai/api(?:/v1)?/?","config":{"properties":{"supportsJsonSchemaOutput":true}}}],"templateModelRules":[{"templateId":"opencode-go-chat","modelId":"glm-5.3-flash","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"glm-5.3","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"glm-5.2","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"glm-5.1","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"kimi-k3","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"kimi-k2.7-code","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"kimi-k2.6","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"deepseek-v4.1-flash","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"deepseek-v4-pro","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"deepseek-v4-flash","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"deepseek-v4-flash-vision-exp","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"mimo-v2.5","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"mimo-v2.5-pro","config":{"enabled":true}},{"templateId":"opencode-go-chat","modelId":"hy4-preview","config":{"enabled":false}},{"templateId":"opencode-go-chat","modelId":"hy3","config":{"enabled":false}},{"templateId":"opencode-go-messages","modelId":"minimax-m3","config":{"enabled":true}},{"templateId":"opencode-go-messages","modelId":"minimax-m2.7","config":{"enabled":false}},{"templateId":"opencode-go-messages","modelId":"minimax-m2.5","config":{"enabled":false}},{"templateId":"opencode-go-messages","modelId":"qwen3.8-max","config":{"enabled":true}},{"templateId":"opencode-go-messages","modelId":"qwen3.8-flash","config":{"enabled":true}},{"templateId":"opencode-go-messages","modelId":"qwen3.7-max","config":{"enabled":false}},{"templateId":"opencode-go-messages","modelId":"qwen3.7-plus","config":{"enabled":false}},{"templateId":"opencode-go-messages","modelId":"qwen3.6-plus","config":{"enabled":false}},{"templateId":"opencode-go-responses","modelId":"gpt-5.6-luna","config":{"enabled":true}},{"templateId":"opencode-go-responses","modelId":"grok-4.6","config":{"enabled":true}},{"modelId":"kimi-k3","templateId":"moonshot-kimi","config":{"enabled":true}},{"modelId":"kimi-k2.7-code","templateId":"moonshot-kimi","config":{"enabled":true}},{"modelId":"kimi-k2.6","templateId":"moonshot-kimi","config":{"enabled":true}},{"modelId":"k3","templateId":"moonshot-kimi","config":{"enabled":false}},{"modelId":"k3-256k","templateId":"moonshot-kimi","config":{"enabled":false}},{"modelId":"MiniMax-M2.7","templateId":"minimax","config":{"enabled":true}},{"modelId":"MiniMax-M2.7-highspeed","templateId":"minimax","config":{"enabled":true}},{"modelId":"MiniMax-M3","templateId":"minimax","config":{"enabled":true}},{"modelId":"MiniMax-M2.5","templateId":"minimax","config":{"enabled":false}},{"modelId":"MiniMax-M2.5-highspeed","templateId":"minimax","config":{"enabled":false}},{"modelId":"MiniMax-M2.1","templateId":"minimax","config":{"enabled":false}},{"modelId":"MiniMax-M2.1-highspeed","templateId":"minimax","config":{"enabled":false}},{"modelId":"MiniMax-M2","templateId":"minimax","config":{"enabled":false}},{"modelId":"deepseek-v4-pro","templateId":"deepseek","config":{"enabled":true}},{"modelId":"qwen3.8-max","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":true}},{"modelId":"qwen3.8-flash","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":true}},{"modelId":"qwen3.5-plus","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen3.5-flash","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen3-max","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen-plus","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen-flash","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen3-vl-plus","templateId":"qwen-alibaba-model-studio-cn","config":{"enabled":false}},{"modelId":"qwen3.8-max","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":true}},{"modelId":"qwen3.8-flash","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":true}},{"modelId":"qwen3.5-plus","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"qwen3.5-flash","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"qwen3-max","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"qwen-plus","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"qwen-flash","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"qwen3-vl-plus","templateId":"qwen-alibaba-model-studio-intl","config":{"enabled":false}},{"modelId":"mimo-v2.6-pro","templateId":"xiaomi-mimo","config":{"enabled":true}},{"modelId":"mimo-v2.6-flash","templateId":"xiaomi-mimo","config":{"enabled":true}},{"modelId":"mimo-v2.6-pro","templateId":"xiaomi-mimo-token-plan","config":{"enabled":true}},{"modelId":"mimo-v2.6-flash","templateId":"xiaomi-mimo-token-plan","config":{"enabled":true}},{"modelId":"mimo-v2.5-pro","templateId":"xiaomi-mimo","config":{"enabled":true}},{"modelId":"mimo-v2.5","templateId":"xiaomi-mimo","config":{"enabled":true}},{"modelId":"gpt-5.6-sol","templateId":"openai","config":{"enabled":true}},{"modelId":"gpt-5.6-terra","templateId":"openai","config":{"enabled":true}},{"modelId":"gpt-5.6-luna","templateId":"openai","config":{"enabled":true}},{"modelId":"gpt-5.6","templateId":"openai","config":{"enabled":false}},{"modelId":"gpt-5.3-codex","templateId":"openai","config":{"enabled":false}},{"modelId":"claude-fable-5","templateId":"anthropic","config":{"enabled":true}},{"modelId":"claude-opus-5","templateId":"anthropic","config":{"enabled":true}},{"modelId":"claude-sonnet-5","templateId":"anthropic","config":{"enabled":true}},{"modelId":"claude-haiku-4-5-20251001","templateId":"anthropic","config":{"enabled":true}},{"modelId":"grok-4.6","templateId":"xai","config":{"enabled":true}},{"modelId":"grok-build-0.1","templateId":"xai","config":{"enabled":true}},{"modelId":"grok-4.3","templateId":"xai","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.6-sol","config":{"enabled":true}},{"templateId":"openrouter","modelId":"openai/gpt-5.6-terra","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.6-luna","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.3-codex","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-opus-5","config":{"enabled":true}},{"templateId":"openrouter","modelId":"anthropic/claude-sonnet-5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-haiku-4.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"deepseek/deepseek-v4-pro","config":{"enabled":true}},{"templateId":"openrouter","modelId":"deepseek/deepseek-v4-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"moonshotai/kimi-k3","config":{"enabled":true}},{"templateId":"openrouter","modelId":"moonshotai/kimi-k2.7-code","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5.3","config":{"enabled":true}},{"templateId":"openrouter","modelId":"z-ai/glm-5.3-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5.2","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.8-max","config":{"enabled":true}},{"templateId":"openrouter","modelId":"qwen/qwen3.8-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"minimax/minimax-m3","config":{"enabled":true}},{"templateId":"openrouter","modelId":"xiaomi/mimo-v2.5-pro","config":{"enabled":true}},{"templateId":"openrouter","modelId":"xiaomi/mimo-v2.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"x-ai/grok-4.6","config":{"enabled":true}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.6-sol","config":{"enabled":true}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.6-terra","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.6-luna","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.5","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.5-pro","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.4","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.4-pro","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.4-mini","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.4-nano","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.3-codex","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.3-codex-spark","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.2","config":{"enabled":false}},{"templateId":"opencode-zen-responses","modelId":"gpt-5.1","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-fable-5","config":{"enabled":true}},{"templateId":"opencode-zen-messages","modelId":"claude-opus-5","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-sonnet-5","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-haiku-4-5","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-opus-4-8","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-opus-4-7","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-opus-4-6","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-opus-4-5","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-sonnet-4-6","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"claude-sonnet-4-5","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"qwen3.7-max","config":{"enabled":true}},{"templateId":"opencode-zen-messages","modelId":"qwen3.7-plus","config":{"enabled":false}},{"templateId":"opencode-zen-messages","modelId":"qwen3.6-plus","config":{"enabled":true}},{"templateId":"opencode-zen-messages","modelId":"qwen3.5-plus","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"kimi-k3","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"minimax-m3","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"minimax-m2.7","config":{"enabled":false}},{"templateId":"opencode-zen-chat","modelId":"deepseek-v4-pro","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"deepseek-v4-flash","config":{"enabled":false}},{"templateId":"opencode-zen-chat","modelId":"glm-5.2","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"glm-5.1","config":{"enabled":false}},{"templateId":"opencode-zen-chat","modelId":"big-pickle","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"mimo-v2.5-free","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"hy3-free","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"ling-3.0-flash-fin-free","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"nemotron-3-ultra-free","config":{"enabled":true}},{"templateId":"opencode-zen-chat","modelId":"nemotron-3.5-lightning-free","config":{"enabled":false}},{"templateId":"opencode-zen-chat","modelId":"muse-spark-1.2-contributor-free","config":{"enabled":true}},{"templateId":"openrouter","modelId":"openai/gpt-5.6","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-opus-4.8","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-opus-4.7","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-opus-4.6","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-opus-4.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-sonnet-4.6","config":{"enabled":false}},{"templateId":"openrouter","modelId":"anthropic/claude-sonnet-4.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"moonshotai/kimi-k2.6","config":{"enabled":false}},{"templateId":"openrouter","modelId":"moonshotai/kimi-k2.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5.1","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5v-turbo","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-5-turbo","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.7","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.7-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.6","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.6v","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.5-air","config":{"enabled":false}},{"templateId":"openrouter","modelId":"z-ai/glm-4.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.7-max","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.7-plus","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.7-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.6-plus","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.6-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.5-plus-20260420","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3-vl-plus","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3-vl-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"minimax/minimax-m2.7","config":{"enabled":false}},{"templateId":"openrouter","modelId":"minimax/minimax-m2.5","config":{"enabled":false}},{"templateId":"openrouter","modelId":"x-ai/grok-build-0.1","config":{"enabled":false}},{"templateId":"openrouter","modelId":"x-ai/grok-4.3","config":{"enabled":false}},{"templateId":"openai","modelId":"gpt-6-astra","config":{"enabled":true}},{"templateId":"opencode-zen-responses","modelId":"gpt-6-astra","config":{"enabled":true}},{"templateId":"anthropic","modelId":"claude-fable-5-1","config":{"enabled":true}},{"templateId":"opencode-zen-messages","modelId":"claude-fable-5-1","config":{"enabled":true}},{"templateId":"openrouter","modelId":"openai/gpt-6-astra","config":{"enabled":true}},{"templateId":"openrouter","modelId":"anthropic/claude-fable-5.1","config":{"enabled":true}},{"templateId":"deepseek","modelId":"deepseek-flash","config":{"enabled":true}},{"templateId":"openai","modelId":"gpt-5.4","config":{"enabled":false}},{"templateId":"openai","modelId":"gpt-5.4-pro","config":{"enabled":false}},{"templateId":"openai","modelId":"gpt-5.4-mini","config":{"enabled":false}},{"templateId":"openai","modelId":"gpt-5.4-nano","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.4","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.4-pro","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.4-mini","config":{"enabled":false}},{"templateId":"openrouter","modelId":"openai/gpt-5.4-nano","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-cn","modelId":"qwen3.7-max","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-cn","modelId":"qwen3.7-plus","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-cn","modelId":"qwen3.7-flash","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-cn","modelId":"qwen3.6-plus","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-cn","modelId":"qwen3.6-flash","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.7-max","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.7-plus","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.7-flash","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.6-plus","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.6-flash","config":{"enabled":false}},{"templateId":"qwen-alibaba-model-studio-intl","modelId":"qwen3.8-omni-flash","config":{"enabled":false}},{"templateId":"moonshot-kimi","modelId":"kimi-k2.7-code-highspeed","config":{"enabled":false}},{"templateId":"openrouter","modelId":"deepseek/deepseek-v4.1-flash","config":{"enabled":false}},{"templateId":"openrouter","modelId":"qwen/qwen3.8-max-0902","config":{"enabled":false}}],"builtinProviderModelRules":[]}}} |
| +добавлено | 'use strict'; |
| +добавлено | // Починка истории диалога перед отправкой провайдеру. |
| +добавлено | // Обрыв во время вызова инструмента (стоп, таймаут, сеть) оставляет в сессии |
| +добавлено | // tool_call без результата или пустое сообщение — провайдер отвечает 400 на каждый |
| +добавлено | // следующий запрос, и сессия «умирает». Здесь история приводится к валидной схеме: |
| +добавлено | // недостающим вызовам подставляется результат-заглушка, сиротские результаты и |
| +добавлено | // пустые сообщения убираются. Сохранённая сессия не меняется — только тело запроса. |
| +добавлено | // Форматы: openai-chat-completions (messages), anthropic-messages (messages + блоки), |
| +добавлено | // openai-responses (input: function_call / function_call_output). |
| +добавлено | |
| +добавлено | const STUB = 'Tool call was interrupted before it returned a result (cancelled, timed out or connection lost). Treat it as not executed.'; |
| +добавлено | const EMPTY_TOOL_OUTPUT = '(no output)'; |
| +добавлено | |
| +добавлено | const isBlank = (v) => typeof v === 'string' && v.trim() === ''; |
| +добавлено | |
| +добавлено | function cleanParts(content) { |
| +добавлено | // пустые текстовые части в массиве контента |
| +добавлено | if (!Array.isArray(content)) return content; |
| +добавлено | return content.filter((p) => !(p && (p.type === 'text' || p.type === 'input_text' || p.type === 'output_text') && isBlank(p.text ?? ''))); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function contentEmpty(content) { |
| +добавлено | if (content == null) return true; |
| +добавлено | if (typeof content === 'string') return isBlank(content); |
| +добавлено | if (Array.isArray(content)) return content.length === 0; |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- openai chat |
| +добавлено | |
| +добавлено | function fixChat(messages, stats) { |
| +добавлено | const out = []; |
| +добавлено | let i = 0; |
| +добавлено | while (i < messages.length) { |
| +добавлено | const m = messages[i]; |
| +добавлено | if (!m || typeof m !== 'object') { |
| +добавлено | i++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (m.role === 'tool') { |
| +добавлено | // tool вне блока своего assistant — сирота |
| +добавлено | stats.orphanResults++; |
| +добавлено | i++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (Array.isArray(m.content)) m.content = cleanParts(m.content); |
| +добавлено | |
| +добавлено | if (m.role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length) { |
| +добавлено | const calls = m.tool_calls.filter((c) => c && c.id); |
| +добавлено | if (calls.length !== m.tool_calls.length) stats.brokenCalls += m.tool_calls.length - calls.length; |
| +добавлено | if (!calls.length) { |
| +добавлено | delete m.tool_calls; |
| +добавлено | } else { |
| +добавлено | m.tool_calls = calls; |
| +добавлено | if (contentEmpty(m.content)) m.content = null; |
| +добавлено | out.push(m); |
| +добавлено | i++; |
| +добавлено | const want = new Set(calls.map((c) => c.id)); |
| +добавлено | const seen = new Set(); |
| +добавлено | while (i < messages.length && messages[i]?.role === 'tool') { |
| +добавлено | const t = messages[i++]; |
| +добавлено | if (!want.has(t.tool_call_id) || seen.has(t.tool_call_id)) { |
| +добавлено | stats.orphanResults++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | seen.add(t.tool_call_id); |
| +добавлено | if (contentEmpty(Array.isArray(t.content) ? cleanParts(t.content) : t.content)) { |
| +добавлено | t.content = EMPTY_TOOL_OUTPUT; |
| +добавлено | stats.emptyResults++; |
| +добавлено | } |
| +добавлено | out.push(t); |
| +добавлено | } |
| +добавлено | for (const c of calls) { |
| +добавлено | if (seen.has(c.id)) continue; |
| +добавлено | out.push({ role: 'tool', tool_call_id: c.id, content: STUB }); |
| +добавлено | stats.stubbed++; |
| +добавлено | } |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (m.role !== 'system' && m.role !== 'developer' && contentEmpty(m.content)) { |
| +добавлено | stats.emptyMessages++; |
| +добавлено | i++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | out.push(m); |
| +добавлено | i++; |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- anthropic |
| +добавлено | |
| +добавлено | function fixAnthropic(messages, stats) { |
| +добавлено | const out = []; |
| +добавлено | for (let i = 0; i < messages.length; i++) { |
| +добавлено | const m = messages[i]; |
| +добавлено | if (!m || typeof m !== 'object') continue; |
| +добавлено | if (typeof m.content === 'string') { |
| +добавлено | if (isBlank(m.content)) { |
| +добавлено | stats.emptyMessages++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | out.push(m); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (!Array.isArray(m.content)) { |
| +добавлено | out.push(m); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | m.content = cleanParts(m.content); |
| +добавлено | |
| +добавлено | // результаты в user должны отвечать на tool_use предыдущего assistant |
| +добавлено | if (m.role === 'user') { |
| +добавлено | const prev = out[out.length - 1]; |
| +добавлено | const open = new Set( |
| +добавлено | prev?.role === 'assistant' && Array.isArray(prev.content) |
| +добавлено | ? prev.content.filter((b) => b?.type === 'tool_use' && b.id).map((b) => b.id) |
| +добавлено | : [], |
| +добавлено | ); |
| +добавлено | const seen = new Set(); |
| +добавлено | m.content = m.content.filter((b) => { |
| +добавлено | if (b?.type !== 'tool_result') return true; |
| +добавлено | if (!open.has(b.tool_use_id) || seen.has(b.tool_use_id)) { |
| +добавлено | stats.orphanResults++; |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | seen.add(b.tool_use_id); |
| +добавлено | if (contentEmpty(Array.isArray(b.content) ? cleanParts(b.content) : b.content)) { |
| +добавлено | b.content = EMPTY_TOOL_OUTPUT; |
| +добавлено | stats.emptyResults++; |
| +добавлено | } |
| +добавлено | return true; |
| +добавлено | }); |
| +добавлено | const missing = [...open].filter((id) => !seen.has(id)); |
| +добавлено | if (missing.length) { |
| +добавлено | // результаты обязаны стоять в начале user-сообщения |
| +добавлено | m.content = [...missing.map((id) => stubBlock(id)), ...m.content]; |
| +добавлено | stats.stubbed += missing.length; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (!m.content.length) { |
| +добавлено | stats.emptyMessages++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | out.push(m); |
| +добавлено | |
| +добавлено | // assistant с tool_use, за которым не идёт user — вставить user с заглушками |
| +добавлено | if (m.role === 'assistant') { |
| +добавлено | const ids = m.content.filter((b) => b?.type === 'tool_use' && b.id).map((b) => b.id); |
| +добавлено | const next = messages[i + 1]; |
| +добавлено | if (ids.length && !(next && next.role === 'user')) { |
| +добавлено | out.push({ role: 'user', content: ids.map((id) => stubBlock(id)) }); |
| +добавлено | stats.stubbed += ids.length; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function stubBlock(id) { |
| +добавлено | return { type: 'tool_result', tool_use_id: id, is_error: true, content: STUB }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- openai responses |
| +добавлено | |
| +добавлено | function fixResponses(input, stats) { |
| +добавлено | const outputs = new Set(input.filter((x) => x?.type === 'function_call_output').map((x) => x.call_id)); |
| +добавлено | const calls = new Set(input.filter((x) => x?.type === 'function_call').map((x) => x.call_id)); |
| +добавлено | const out = []; |
| +добавлено | const seen = new Set(); |
| +добавлено | for (const x of input) { |
| +добавлено | if (x?.type === 'function_call_output') { |
| +добавлено | if (!calls.has(x.call_id) || seen.has(x.call_id)) { |
| +добавлено | stats.orphanResults++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | seen.add(x.call_id); |
| +добавлено | if (isBlank(typeof x.output === 'string' ? x.output : 'x')) { |
| +добавлено | x.output = EMPTY_TOOL_OUTPUT; |
| +добавлено | stats.emptyResults++; |
| +добавлено | } |
| +добавлено | out.push(x); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (x?.type === 'message' && contentEmpty(cleanParts(x.content))) { |
| +добавлено | stats.emptyMessages++; |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | out.push(x); |
| +добавлено | if (x?.type === 'function_call' && x.call_id && !outputs.has(x.call_id)) { |
| +добавлено | out.push({ type: 'function_call_output', call_id: x.call_id, output: STUB }); |
| +добавлено | seen.add(x.call_id); |
| +добавлено | stats.stubbed++; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вход |
| +добавлено | |
| +добавлено | /** Возвращает { payload, stats } если что-то поправлено, иначе null. Исходный объект не трогает. */ |
| +добавлено | function sanitizePayload(payload) { |
| +добавлено | if (!payload || typeof payload !== 'object') return null; |
| +добавлено | const hasMessages = Array.isArray(payload.messages); |
| +добавлено | const hasInput = Array.isArray(payload.input); |
| +добавлено | if (!hasMessages && !hasInput) return null; |
| +добавлено | const copy = structuredClone(payload); |
| +добавлено | const stats = { stubbed: 0, orphanResults: 0, emptyResults: 0, emptyMessages: 0, brokenCalls: 0 }; |
| +добавлено | if (hasMessages) { |
| +добавлено | const anthropic = typeof copy.system !== 'undefined' || copy.messages.some((m) => Array.isArray(m?.content) && m.content.some((b) => b?.type === 'tool_use' || b?.type === 'tool_result')); |
| +добавлено | copy.messages = anthropic && !copy.messages.some((m) => m?.role === 'tool' || Array.isArray(m?.tool_calls)) |
| +добавлено | ? fixAnthropic(copy.messages, stats) |
| +добавлено | : fixChat(copy.messages, stats); |
| +добавлено | } else { |
| +добавлено | copy.input = fixResponses(copy.input, stats); |
| +добавлено | } |
| +добавлено | const total = Object.values(stats).reduce((a, b) => a + b, 0); |
| +добавлено | return total ? { payload: copy, stats } : null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | module.exports = { sanitizePayload, STUB }; |
| +добавлено | 'use strict'; |
| +добавлено | // Пул ключей и умный роутинг для кастомных провайдеров ZCode. |
| +добавлено | // Подключается из zcode.cjs: транспорт провайдера оборачивается wrap(providerId, fetch). |
| +добавлено | // Конфиг пишет desktop (Settings → Model settings): ~/.zcode/v2/key_pool.json. |
| +добавлено | // Состояние (кулдауны, использование, журнал) — ~/.zcode/v2/key_pool_runtime.json. |
| +добавлено | |
| +добавлено | const fs = require('node:fs'); |
| +добавлено | const path = require('node:path'); |
| +добавлено | const os = require('node:os'); |
| +добавлено | const crypto = require('node:crypto'); |
| +добавлено | |
| +добавлено | let sanitizer = null; |
| +добавлено | try { |
| +добавлено | sanitizer = require('./history-sanitizer.cjs'); |
| +добавлено | } catch { |
| +добавлено | sanitizer = null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const ROUTING_TIERS = ['high', 'medium-high', 'medium', 'low-medium', 'low']; |
| +добавлено | const UNCENSORED = 'uncensored'; |
| +добавлено | const UNSET = 'unset'; |
| +добавлено | const TIERS = [...ROUTING_TIERS, UNCENSORED, UNSET]; |
| +добавлено | |
| +добавлено | const COOLDOWN_AUTH_MS = 10 * 60_000; |
| +добавлено | const COOLDOWN_BALANCE_MS = 10 * 60_000; |
| +добавлено | const COOLDOWN_RATE_MS = 30_000; |
| +добавлено | const MODEL_FAIL_MEMORY_MS = 60_000; |
| +добавлено | const CHECK_TRUST_MS = 30 * 60_000; |
| +добавлено | const PROBE_QUERY_SOURCE = 'provider_settings_connectivity'; |
| +добавлено | const PROBE_PROMPT = 'You are ZCode connectivity probe.'; |
| +добавлено | |
| +добавлено | // Файлы пула лежат рядом с provider_config.json, который реально читает CLI. |
| +добавлено | const providerConfigPath = () => |
| +добавлено | (process.env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE || '').trim() || |
| +добавлено | path.join((process.env.ZCODE_DATA_BASE_DIR || '').trim() || os.homedir(), '.zcode', 'v2', 'provider_config.json'); |
| +добавлено | const dataDir = () => path.dirname(providerConfigPath()); |
| +добавлено | const poolPath = () => path.join(dataDir(), 'key_pool.json'); |
| +добавлено | const checksPath = () => path.join(dataDir(), 'key_pool_checks.json'); |
| +добавлено | const runtimePath = () => path.join(dataDir(), 'key_pool_runtime.json'); |
| +добавлено | |
| +добавлено | const fingerprint = (key) => crypto.createHash('sha256').update(String(key)).digest('hex').slice(0, 12); |
| +добавлено | const now = () => Date.now(); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- файлы с кэшем по mtime |
| +добавлено | |
| +добавлено | const fileCache = new Map(); |
| +добавлено | function readJson(file, fallback) { |
| +добавлено | const hit = fileCache.get(file); |
| +добавлено | if (hit && now() - hit.at < 800) return hit.value; |
| +добавлено | let value = fallback; |
| +добавлено | try { |
| +добавлено | const st = fs.statSync(file); |
| +добавлено | if (hit && hit.mtime === st.mtimeMs) { |
| +добавлено | hit.at = now(); |
| +добавлено | return hit.value; |
| +добавлено | } |
| +добавлено | value = JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | fileCache.set(file, { at: now(), mtime: st.mtimeMs, value }); |
| +добавлено | } catch { |
| +добавлено | fileCache.set(file, { at: now(), mtime: -1, value }); |
| +добавлено | } |
| +добавлено | return value; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function poolConfig() { |
| +добавлено | const raw = readJson(poolPath(), {}); |
| +добавлено | return { |
| +добавлено | autoRouting: raw.autoRouting !== false, |
| +добавлено | providers: raw.providers && typeof raw.providers === 'object' ? raw.providers : {}, |
| +добавлено | cooldownResetAt: raw.cooldownResetAt && typeof raw.cooldownResetAt === 'object' ? raw.cooldownResetAt : {}, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function providerDoc() { |
| +добавлено | const doc = readJson(providerConfigPath(), {}); |
| +добавлено | const cfg = doc?.config ?? {}; |
| +добавлено | const rules = cfg.providerConfigRules?.providerRules ?? []; |
| +добавлено | const modelRules = [ |
| +добавлено | ...(cfg.modelConfigRules?.providerModelRules ?? []), |
| +добавлено | ...(cfg.modelConfigRules?.manualProviderModelRules ?? []), |
| +добавлено | ]; |
| +добавлено | const order = Array.isArray(cfg.providerOrder) ? cfg.providerOrder : []; |
| +добавлено | const providers = rules |
| +добавлено | .filter((r) => r && r.providerId && r.config?.api?.baseUrl && r.config?.access?.type === 'api-key') |
| +добавлено | .map((r) => ({ |
| +добавлено | id: r.providerId, |
| +добавлено | name: r.providerName || r.providerId, |
| +добавлено | enabled: r.enabled !== false, |
| +добавлено | apiType: r.config.api.type || 'anthropic-messages', |
| +добавлено | baseUrl: r.config.api.baseUrl, |
| +добавлено | headers: r.config.api.headers || {}, |
| +добавлено | primaryKey: (r.config.access.apiKey || '').trim(), |
| +добавлено | models: [...(r.config.modelOrder?.length ? r.config.modelOrder : r.config.personalModelIds ?? [])], |
| +добавлено | })); |
| +добавлено | providers.sort((a, b) => { |
| +добавлено | const ia = order.indexOf(a.id); |
| +добавлено | const ib = order.indexOf(b.id); |
| +добавлено | return (ia < 0 ? 1e9 : ia) - (ib < 0 ? 1e9 : ib); |
| +добавлено | }); |
| +добавлено | const modelInfo = (providerId, modelId) => { |
| +добавлено | const rule = modelRules.find((m) => m.providerId === providerId && m.modelId === modelId); |
| +добавлено | return { |
| +добавлено | enabled: rule?.config?.enabled !== false, |
| +добавлено | supportsImage: rule?.config?.properties?.inputFormat?.supportsImage, |
| +добавлено | }; |
| +добавлено | }; |
| +добавлено | return { providers, modelInfo }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function tierOf(pool, providerId, modelId) { |
| +добавлено | const t = pool.providers[providerId]?.tiers?.[modelId]; |
| +добавлено | return TIERS.includes(t) ? t : UNSET; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function keysOf(pool, provider) { |
| +добавлено | const extra = Array.isArray(pool.providers[provider.id]?.keys) ? pool.providers[provider.id].keys : []; |
| +добавлено | const all = [provider.primaryKey, ...extra].map((k) => String(k || '').trim()).filter(Boolean); |
| +добавлено | return [...new Set(all)]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- состояние |
| +добавлено | |
| +добавлено | const state = { |
| +добавлено | keys: {}, // fp -> { until, reason, status, at, uses, fails } |
| +добавлено | usage: {}, // `${pid}/${model}` -> { count, ok, fail, lastAt, lastStatus } |
| +добавлено | modelFails: {}, // `${pid}/${model}` -> at |
| +добавлено | events: [], // новые сверху |
| +добавлено | cursor: {}, // pid -> индекс следующего ключа |
| +добавлено | }; |
| +добавлено | let loaded = false; |
| +добавлено | let saveTimer = null; |
| +добавлено | |
| +добавлено | function loadState() { |
| +добавлено | if (loaded) return; |
| +добавлено | loaded = true; |
| +добавлено | try { |
| +добавлено | const raw = JSON.parse(fs.readFileSync(runtimePath(), 'utf8')); |
| +добавлено | if (raw.keys) state.keys = raw.keys; |
| +добавлено | if (raw.usage) state.usage = raw.usage; |
| +добавлено | if (Array.isArray(raw.events)) state.events = raw.events.slice(0, 60); |
| +добавлено | } catch { |
| +добавлено | /* первый запуск */ |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function saveState() { |
| +добавлено | if (saveTimer) return; |
| +добавлено | saveTimer = setTimeout(() => { |
| +добавлено | saveTimer = null; |
| +добавлено | try { |
| +добавлено | // другой процесс CLI мог записать свои события — сливаем, а не затираем |
| +добавлено | let disk = {}; |
| +добавлено | try { |
| +добавлено | disk = JSON.parse(fs.readFileSync(runtimePath(), 'utf8')); |
| +добавлено | } catch {} |
| +добавлено | const events = [...state.events, ...(Array.isArray(disk.events) ? disk.events : [])]; |
| +добавлено | const seen = new Set(); |
| +добавлено | const merged = events |
| +добавлено | .filter((e) => (seen.has(e.id) ? false : (seen.add(e.id), true))) |
| +добавлено | .sort((a, b) => b.at - a.at) |
| +добавлено | .slice(0, 60); |
| +добавлено | state.events = merged; |
| +добавлено | const keys = { ...(disk.keys ?? {}), ...state.keys }; |
| +добавлено | const usage = { ...(disk.usage ?? {}), ...state.usage }; |
| +добавлено | const tmp = `${runtimePath()}.${process.pid}.tmp`; |
| +добавлено | fs.mkdirSync(dataDir(), { recursive: true }); |
| +добавлено | fs.writeFileSync(tmp, JSON.stringify({ updatedAt: now(), keys, usage, events: merged }, null, 1)); |
| +добавлено | fs.renameSync(tmp, runtimePath()); |
| +добавлено | } catch { |
| +добавлено | /* состояние — вспомогательное */ |
| +добавлено | } |
| +добавлено | }, 500); |
| +добавлено | saveTimer.unref?.(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | let eventSeq = 0; |
| +добавлено | function pushEvent(e) { |
| +добавлено | state.events.unshift({ id: `${process.pid}-${now()}-${++eventSeq}`, at: now(), ...e }); |
| +добавлено | if (state.events.length > 60) state.events.length = 60; |
| +добавлено | saveState(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function keyCooling(pool, providerId, fp) { |
| +добавлено | const k = state.keys[fp]; |
| +добавлено | if (!k || !k.until || k.until <= now()) return false; |
| +добавлено | const resetAt = Number(pool.cooldownResetAt[providerId] || 0); |
| +добавлено | return k.at > resetAt; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function keyDeadByCheck(pool, providerId, fp) { |
| +добавлено | const checks = readJson(checksPath(), {}); |
| +добавлено | const c = checks?.keys?.[fp]; |
| +добавлено | if (!c || c.ok || now() - (c.at || 0) > CHECK_TRUST_MS) return false; |
| +добавлено | const resetAt = Number(pool.cooldownResetAt[providerId] || 0); |
| +добавлено | return (c.status === 401 || c.status === 402 || c.status === 403) && c.at > resetAt; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function coolKey(fp, ms, reason, status) { |
| +добавлено | const prev = state.keys[fp] ?? { uses: 0, fails: 0 }; |
| +добавлено | state.keys[fp] = { ...prev, until: now() + ms, reason, status, at: now(), fails: (prev.fails || 0) + 1 }; |
| +добавлено | saveState(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function markKeyOk(fp) { |
| +добавлено | const prev = state.keys[fp] ?? { uses: 0, fails: 0 }; |
| +добавлено | state.keys[fp] = { ...prev, until: 0, reason: '', status: 200, at: now(), uses: (prev.uses || 0) + 1 }; |
| +добавлено | saveState(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Ключи провайдера в порядке ротации: сначала живые, потом «подозрительные» по проверке. */ |
| +добавлено | function orderedKeys(pool, provider) { |
| +добавлено | const keys = keysOf(pool, provider); |
| +добавлено | if (!keys.length) return []; |
| +добавлено | const start = (state.cursor[provider.id] ?? 0) % keys.length; |
| +добавлено | const rotated = keys.map((_, i) => keys[(start + i) % keys.length]); |
| +добавлено | state.cursor[provider.id] = (start + 1) % keys.length; |
| +добавлено | const live = []; |
| +добавлено | const doubtful = []; |
| +добавлено | for (const key of rotated) { |
| +добавлено | const fp = fingerprint(key); |
| +добавлено | if (keyCooling(pool, provider.id, fp)) continue; |
| +добавлено | (keyDeadByCheck(pool, provider.id, fp) ? doubtful : live).push(key); |
| +добавлено | } |
| +добавлено | return [...live, ...doubtful]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function recordUsage(providerId, modelId, ok, status) { |
| +добавлено | const k = `${providerId}/${modelId}`; |
| +добавлено | const u = state.usage[k] ?? { count: 0, ok: 0, fail: 0, lastAt: 0 }; |
| +добавлено | u.count += 1; |
| +добавлено | u.lastAt = now(); |
| +добавлено | u.lastStatus = status; |
| +добавлено | if (ok) u.ok += 1; |
| +добавлено | else { |
| +добавлено | u.fail += 1; |
| +добавлено | state.modelFails[k] = now(); |
| +добавлено | } |
| +добавлено | state.usage[k] = u; |
| +добавлено | saveState(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- запрос |
| +добавлено | |
| +добавлено | function normalizeBase(apiType, baseUrl) { |
| +добавлено | let b = String(baseUrl || '').trim().replace(/\/+$/u, ''); |
| +добавлено | if (apiType === 'anthropic-messages' && !/\/v1$/iu.test(b)) b = `${b}/v1`; |
| +добавлено | return b; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function readRequest(input, init) { |
| +добавлено | if (typeof Request !== 'undefined' && input instanceof Request) { |
| +добавлено | const method = (init?.method || input.method || 'GET').toUpperCase(); |
| +добавлено | let body = init?.body; |
| +добавлено | if (body === undefined && method !== 'GET' && method !== 'HEAD') body = await input.clone().text(); |
| +добавлено | return { |
| +добавлено | url: input.url, |
| +добавлено | method, |
| +добавлено | headers: new Headers(init?.headers ?? input.headers), |
| +добавлено | body, |
| +добавлено | signal: init?.signal ?? input.signal, |
| +добавлено | rest: {}, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | const { headers, body, method, signal, ...rest } = init ?? {}; |
| +добавлено | return { |
| +добавлено | url: input instanceof URL ? input.href : String(input), |
| +добавлено | method: (method || 'GET').toUpperCase(), |
| +добавлено | headers: new Headers(headers), |
| +добавлено | body, |
| +добавлено | signal, |
| +добавлено | rest, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function bodyText(body) { |
| +добавлено | if (typeof body === 'string') return body; |
| +добавлено | if (body instanceof Uint8Array) return Buffer.from(body).toString('utf8'); |
| +добавлено | if (body instanceof ArrayBuffer) return Buffer.from(body).toString('utf8'); |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function setAuth(headers, key, apiType) { |
| +добавлено | const hadXKey = headers.has('x-api-key'); |
| +добавлено | const hadAuth = headers.has('authorization'); |
| +добавлено | if (hadXKey || (!hadAuth && apiType === 'anthropic-messages')) headers.set('x-api-key', key); |
| +добавлено | if (hadAuth || (!hadXKey && apiType !== 'anthropic-messages')) headers.set('authorization', `Bearer ${key}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const MODEL_MISSING_RE = /model[^.]{0,60}(not\s*found|not\s*exist|does\s*not|unsupported|not\s*supported|invalid|unavailable|no\s*available)|no\s*such\s*model|unknown\s*model|模型/iu; |
| +добавлено | |
| +добавлено | function classify(status, text) { |
| +добавлено | if (status === 401 || status === 403) return { action: 'next-key', cool: COOLDOWN_AUTH_MS, reason: status === 401 ? 'invalid' : 'forbidden' }; |
| +добавлено | if (status === 402) return { action: 'next-key', cool: COOLDOWN_BALANCE_MS, reason: 'no-balance' }; |
| +добавлено | if (status === 429) { |
| +добавлено | if (/insufficient|quota|balance|credit|billing/iu.test(text)) return { action: 'next-key', cool: COOLDOWN_BALANCE_MS, reason: 'no-balance' }; |
| +добавлено | return { action: 'next-key', cool: COOLDOWN_RATE_MS, reason: 'rate-limit' }; |
| +добавлено | } |
| +добавлено | if (status === 404) return { action: 'next-model', reason: 'not-found' }; |
| +добавлено | if (status === 408 || status >= 500) return { action: 'next-model', reason: `http-${status}` }; |
| +добавлено | if ((status === 400 || status === 422) && MODEL_MISSING_RE.test(text)) return { action: 'next-model', reason: 'model-unavailable' }; |
| +добавлено | return { action: 'return' }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function hasImages(text) { |
| +добавлено | return /"(image_url|input_image)"|"type"\s*:\s*"image"/u.test(text); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Цепочка кандидатов: та же модель → тот же уровень → ниже по лестнице. */ |
| +добавлено | function buildChain(pool, doc, origin, modelId, allowFallback, wantsImages) { |
| +добавлено | const chain = [{ provider: origin, model: modelId, tier: tierOf(pool, origin.id, modelId) }]; |
| +добавлено | if (!allowFallback || !pool.autoRouting) return chain; |
| +добавлено | const wantTier = tierOf(pool, origin.id, modelId); |
| +добавлено | const compatible = doc.providers.filter( |
| +добавлено | (p) => p.enabled && p.apiType === origin.apiType && keysOf(pool, p).length > 0, |
| +добавлено | ); |
| +добавлено | const seen = new Set([`${origin.id}/${modelId}`]); |
| +добавлено | const usable = (p, m) => { |
| +добавлено | const key = `${p.id}/${m}`; |
| +добавлено | if (seen.has(key)) return false; |
| +добавлено | if (!doc.modelInfo(p.id, m).enabled) return false; |
| +добавлено | return true; |
| +добавлено | }; |
| +добавлено | const add = (list, p, m) => { |
| +добавлено | seen.add(`${p.id}/${m}`); |
| +добавлено | list.push({ provider: p, model: m, tier: tierOf(pool, p.id, m) }); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // та же модель у других провайдеров |
| +добавлено | for (const p of compatible) if (p.id !== origin.id && p.models.includes(modelId) && usable(p, modelId)) add(chain, p, modelId); |
| +добавлено | |
| +добавлено | // без цензуры — только сама модель |
| +добавлено | if (wantTier === UNCENSORED) return chain; |
| +добавлено | |
| +добавлено | const startTier = wantTier === UNSET ? 'medium' : wantTier; |
| +добавлено | const rest = []; |
| +добавлено | for (let i = ROUTING_TIERS.indexOf(startTier); i < ROUTING_TIERS.length; i++) { |
| +добавлено | const tier = ROUTING_TIERS[i]; |
| +добавлено | const sameProvider = []; |
| +добавлено | const others = []; |
| +добавлено | for (const p of compatible) { |
| +добавлено | for (const m of p.models) { |
| +добавлено | if (tierOf(pool, p.id, m) !== tier || !usable(p, m)) continue; |
| +добавлено | add(p.id === origin.id ? sameProvider : others, p, m); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | rest.push(...sameProvider, ...others); |
| +добавлено | } |
| +добавлено | // недавно упавшие и не умеющие картинки — в конец |
| +добавлено | const score = (c) => { |
| +добавлено | const failedAt = state.modelFails[`${c.provider.id}/${c.model}`] ?? 0; |
| +добавлено | const recentFail = now() - failedAt < MODEL_FAIL_MEMORY_MS ? 2 : 0; |
| +добавлено | const img = wantsImages && doc.modelInfo(c.provider.id, c.model).supportsImage !== true ? 1 : 0; |
| +добавлено | return recentFail + img; |
| +добавлено | }; |
| +добавлено | rest.sort((a, b) => score(a) - score(b)); |
| +добавлено | return [...chain, ...rest]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function cloneResponse(res, text) { |
| +добавлено | return new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function wrap(providerId, fetchImpl) { |
| +добавлено | if (typeof fetchImpl !== 'function') return fetchImpl; |
| +добавлено | return async function keyPoolFetch(input, init) { |
| +добавлено | let doc; |
| +добавлено | let pool; |
| +добавлено | try { |
| +добавлено | doc = providerDoc(); |
| +добавлено | pool = poolConfig(); |
| +добавлено | loadState(); |
| +добавлено | } catch { |
| +добавлено | return fetchImpl(input, init); |
| +добавлено | } |
| +добавлено | const origin = doc.providers.find((p) => p.id === providerId); |
| +добавлено | if (!origin) return fetchImpl(input, init); |
| +добавлено | |
| +добавлено | const req = await readRequest(input, init); |
| +добавлено | let text = bodyText(req.body); |
| +добавлено | let payload = null; |
| +добавлено | if (text && req.method === 'POST') { |
| +добавлено | try { |
| +добавлено | payload = JSON.parse(text); |
| +добавлено | } catch { |
| +добавлено | payload = null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (payload) { |
| +добавлено | let fixed = null; |
| +добавлено | try { |
| +добавлено | fixed = sanitizer?.sanitizePayload(payload) ?? null; |
| +добавлено | } catch { |
| +добавлено | fixed = null; |
| +добавлено | } |
| +добавлено | if (fixed) { |
| +добавлено | payload = fixed.payload; |
| +добавлено | text = JSON.stringify(payload); |
| +добавлено | req.body = text; |
| +добавлено | req.headers.delete('content-length'); |
| +добавлено | pushEvent({ kind: 'history-fix', providerId, model: typeof payload.model === 'string' ? payload.model : null, ...fixed.stats }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const modelId = payload && typeof payload.model === 'string' ? payload.model : null; |
| +добавлено | const originBase = normalizeBase(origin.apiType, origin.baseUrl); |
| +добавлено | const routable = !!modelId && req.url.startsWith(originBase) && text !== null; |
| +добавлено | const isProbe = |
| +добавлено | (req.headers.get('x-zcode-query-source') || '') === PROBE_QUERY_SOURCE || (text ?? '').includes(PROBE_PROMPT); |
| +добавлено | const retryableBody = text !== null || req.body == null; |
| +добавлено | |
| +добавлено | const chain = routable |
| +добавлено | ? buildChain(pool, doc, origin, modelId, !isProbe, hasImages(text)) |
| +добавлено | : [{ provider: origin, model: modelId, tier: UNSET }]; |
| +добавлено | |
| +добавлено | let lastResponse = null; |
| +добавлено | let lastError = null; |
| +добавлено | const tried = []; |
| +добавлено | |
| +добавлено | for (const cand of chain) { |
| +добавлено | const keys = orderedKeys(pool, cand.provider); |
| +добавлено | if (!keys.length) { |
| +добавлено | tried.push({ to: `${cand.provider.id}/${cand.model}`, reason: 'all-keys-cooling' }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const base = normalizeBase(cand.provider.apiType, cand.provider.baseUrl); |
| +добавлено | const url = cand.provider.id === origin.id ? req.url : base + req.url.slice(originBase.length); |
| +добавлено | const body = |
| +добавлено | cand.model && cand.model !== modelId && payload ? JSON.stringify({ ...payload, model: cand.model }) : req.body; |
| +добавлено | let nextModel = false; |
| +добавлено | |
| +добавлено | for (const key of keys) { |
| +добавлено | if (req.signal?.aborted) throw req.signal.reason ?? new Error('aborted'); |
| +добавлено | const fp = fingerprint(key); |
| +добавлено | const headers = new Headers(req.headers); |
| +добавлено | if (cand.provider.id !== origin.id) { |
| +добавлено | for (const h of Object.keys(origin.headers)) headers.delete(h); |
| +добавлено | for (const [h, v] of Object.entries(cand.provider.headers)) headers.set(h, v); |
| +добавлено | } |
| +добавлено | setAuth(headers, key, cand.provider.apiType); |
| +добавлено | let res; |
| +добавлено | try { |
| +добавлено | res = await fetchImpl(url, { ...req.rest, method: req.method, headers, body, signal: req.signal }); |
| +добавлено | } catch (err) { |
| +добавлено | if (req.signal?.aborted) throw err; |
| +добавлено | lastError = err; |
| +добавлено | tried.push({ to: `${cand.provider.id}/${cand.model}`, reason: 'network' }); |
| +добавлено | if (cand.model) recordUsage(cand.provider.id, cand.model, false, 0); |
| +добавлено | nextModel = true; |
| +добавлено | break; |
| +добавлено | } |
| +добавлено | if (res.ok) { |
| +добавлено | markKeyOk(fp); |
| +добавлено | if (cand.model) recordUsage(cand.provider.id, cand.model, true, res.status); |
| +добавлено | if (tried.length) { |
| +добавлено | pushEvent({ |
| +добавлено | kind: cand.model === modelId && cand.provider.id === origin.id ? 'key-swap' : 'fallback', |
| +добавлено | from: `${origin.id}/${modelId}`, |
| +добавлено | to: `${cand.provider.id}/${cand.model}`, |
| +добавлено | fromName: origin.name, |
| +добавлено | toName: cand.provider.name, |
| +добавлено | steps: tried.slice(-6), |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | return res; |
| +добавлено | } |
| +добавлено | if (!retryableBody) return res; |
| +добавлено | const errText = await res.text().catch(() => ''); |
| +добавлено | lastResponse = cloneResponse(res, errText); |
| +добавлено | const verdict = classify(res.status, errText); |
| +добавлено | if (verdict.action === 'return') { |
| +добавлено | if (cand.model) recordUsage(cand.provider.id, cand.model, false, res.status); |
| +добавлено | return lastResponse; |
| +добавлено | } |
| +добавлено | tried.push({ to: `${cand.provider.id}/${cand.model}`, key: fp, status: res.status, reason: verdict.reason }); |
| +добавлено | if (verdict.action === 'next-key') { |
| +добавлено | coolKey(fp, verdict.cool, verdict.reason, res.status); |
| +добавлено | pushEvent({ kind: 'key-cooldown', providerId: cand.provider.id, toName: cand.provider.name, key: fp, status: res.status, reason: verdict.reason }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (cand.model) recordUsage(cand.provider.id, cand.model, false, res.status); |
| +добавлено | nextModel = true; |
| +добавлено | break; |
| +добавлено | } |
| +добавлено | if (!nextModel && !routable) break; |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (tried.length) { |
| +добавлено | pushEvent({ kind: 'exhausted', from: `${origin.id}/${modelId}`, fromName: origin.name, steps: tried.slice(-8) }); |
| +добавлено | } |
| +добавлено | if (lastResponse) return lastResponse; |
| +добавлено | if (lastError) throw lastError; |
| +добавлено | return new Response( |
| +добавлено | JSON.stringify({ error: { message: 'All API keys of this provider are cooling down. Add keys or reset cooldowns in Model settings.', type: 'key_pool_exhausted' } }), |
| +добавлено | { status: 429, headers: { 'content-type': 'application/json' } }, |
| +добавлено | ); |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | module.exports = { wrap, fingerprint, TIERS, ROUTING_TIERS, _internal: { buildChain, classify, state, poolConfig, providerDoc } }; |
| +добавлено | @echo off |
| +добавлено | setlocal |
| +добавлено | set "ROOT=%~dp0" |
| +добавлено | set "HOME_DIR=%ROOT%home" |
| +добавлено | rem переменные основной установки не должны протекать в форк |
| +добавлено | set "ZCODE_PERSONAL_PROVIDER_CONFIG_FILE=" |
| +добавлено | set "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE=" |
| +добавлено | set "ZCODE_WINDOWS_APP_INSTALL_DIR=" |
| +добавлено | set "ZCODE_GEN_UI_OUTPUT_ROOT=" |
| +добавлено | set "ZCODE_PROCESS_LABEL=" |
| +добавлено | set "ZCODE_RUNTIME_ENV=" |
| +добавлено | set "ZCODE_APP_VERSION=" |
| +добавлено | set "ZCODE_BUILD_COMMIT_ID=" |
| +добавлено | set "ZCODE_RG_BINARY=" |
| +добавлено | set "ZCODE_UGREP_BINARY=" |
| +добавлено | set "ZCODE_CUA_WIN_HELPER_RECIPE=" |
| +добавлено | set "ZCODE_DESKTOP_CONTEXT_PROMPT_ENABLED=" |
| +добавлено | set "ZCODE_ENV=" |
| +добавлено | set "USERPROFILE=%HOME_DIR%" |
| +добавлено | set "HOME=%HOME_DIR%" |
| +добавлено | set "ZCODE_DATA_BASE_DIR=%HOME_DIR%" |
| +добавлено | set "ZCODE_DESKTOP_HOME_DIR=%HOME_DIR%" |
| +добавлено | set "ZCODE_DESKTOP_USER_DATA_DIR=%ROOT%profile\desktop" |
| +добавлено | set "ZCODE_DESKTOP_SESSION_DATA_DIR=%ROOT%profile\desktop-session" |
| +добавлено | set "ZCODE_ENDPOINT_ORIGIN=http://127.0.0.1:9" |
| +добавлено | set "ZCODE_BASE_URL=http://127.0.0.1:9" |
| +добавлено | set "ZCODE_DISABLE_FIXED_REMOTE_DEBUGGING_PORT=" |
| +добавлено | set "ZCODE_MODEL_TELEMETRY_ENABLED=false" |
| +добавлено | set "OTEL_SDK_DISABLED=true" |
| +добавлено | set "ELECTRON_NO_ATTACH_CONSOLE=1" |
| +добавлено | set "ZCODE_UPDATE_FEED_URL=http://127.0.0.1:9/updates/latest.yml" |
| +добавлено | |
| +добавлено | rem без providerFamilyDomain окно форка остаётся пустым (экран входа Z.ai вырезан) |
| +добавлено | node "%ROOT%hooks\ensure-settings.mjs" |
| +добавлено | |
| +добавлено | start "" /min cmd /c "cd /d "%ROOT%team" && node server.mjs >> team.log 2>&1" |
| +добавлено | |
| +добавлено | rem дать team-серверу подняться |
| +добавлено | ping -n 2 127.0.0.1 >nul |
| +добавлено | |
| +добавлено | rem --- применить подготовленный app.asar.new, если приложение закрыто --- |
| +добавлено | if exist "%ROOT%resources\app.asar.new" ( |
| +добавлено | if exist "%ROOT%resources\app.asar.bak" del /q "%ROOT%resources\app.asar.bak" >nul 2>&1 |
| +добавлено | move /y "%ROOT%resources\app.asar" "%ROOT%resources\app.asar.bak" >nul 2>&1 |
| +добавлено | if exist "%ROOT%resources\app.asar.bak" ( |
| +добавлено | move /y "%ROOT%resources\app.asar.new" "%ROOT%resources\app.asar" >nul 2>&1 |
| +добавлено | if not exist "%ROOT%resources\app.asar" move /y "%ROOT%resources\app.asar.bak" "%ROOT%resources\app.asar" >nul 2>&1 |
| +добавлено | ) |
| +добавлено | ) |
| +добавлено | |
| +добавлено | rem app.asar.unpacked идёт парой к app.asar: без подмены нативный node-pty |
| +добавлено | rem останется от прежней сборки. Бэкап держим отдельным именем. |
| +добавлено | if exist "%ROOT%resources\app.asar.new.unpacked" ( |
| +добавлено | if exist "%ROOT%resources\app.asar.unpacked.bak" rd /s /q "%ROOT%resources\app.asar.unpacked.bak" >nul 2>&1 |
| +добавлено | if exist "%ROOT%resources\app.asar.unpacked" move /y "%ROOT%resources\app.asar.unpacked" "%ROOT%resources\app.asar.unpacked.bak" >nul 2>&1 |
| +добавлено | if exist "%ROOT%resources\app.asar.unpacked.bak" move /y "%ROOT%resources\app.asar.new.unpacked" "%ROOT%resources\app.asar.unpacked" >nul 2>&1 |
| +добавлено | ) |
| +добавлено | |
| +добавлено | start "" "%ROOT%ZCode.exe" %* |
| +добавлено | endlocal |
| +добавлено | #!/usr/bin/env bash |
| +добавлено | # Запуск форка с полностью изолированным домом и профилем. |
| +добавлено | set -euo pipefail |
| +добавлено | ROOT="$(cd "$(dirname "$0")" && pwd)" |
| +добавлено | # переменные основной установки не должны протекать в форк |
| +добавлено | unset ZCODE_PERSONAL_PROVIDER_CONFIG_FILE ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ZCODE_WINDOWS_APP_INSTALL_DIR \ |
| +добавлено | ZCODE_GEN_UI_OUTPUT_ROOT ZCODE_PROCESS_LABEL ZCODE_RUNTIME_ENV ZCODE_APP_VERSION ZCODE_BUILD_COMMIT_ID \ |
| +добавлено | ZCODE_RG_BINARY ZCODE_UGREP_BINARY ZCODE_CUA_WIN_HELPER_RECIPE ZCODE_DESKTOP_CONTEXT_PROMPT_ENABLED ZCODE_ENV || true |
| +добавлено | export HOME="$ROOT/home" |
| +добавлено | export USERPROFILE="$ROOT/home" |
| +добавлено | export ZCODE_DATA_BASE_DIR="$ROOT/home" |
| +добавлено | export ZCODE_DESKTOP_HOME_DIR="$ROOT/home" |
| +добавлено | export ZCODE_DESKTOP_USER_DATA_DIR="$ROOT/profile/desktop" |
| +добавлено | export ZCODE_DESKTOP_SESSION_DATA_DIR="$ROOT/profile/desktop-session" |
| +добавлено | export ZCODE_ENDPOINT_ORIGIN="http://127.0.0.1:9" |
| +добавлено | export ZCODE_BASE_URL="http://127.0.0.1:9" |
| +добавлено | export ZCODE_DISABLE_FIXED_REMOTE_DEBUGGING_PORT= |
| +добавлено | export ZCODE_MODEL_TELEMETRY_ENABLED=false |
| +добавлено | export OTEL_SDK_DISABLED=true |
| +добавлено | export ZCODE_UPDATE_FEED_URL="http://127.0.0.1:9/updates/latest.yml" |
| +добавлено | |
| +добавлено | node "$ROOT/hooks/ensure-settings.mjs" || true |
| +добавлено | |
| +добавлено | cd "$ROOT/team" |
| +добавлено | node server.mjs >> team.log 2>&1 & |
| +добавлено | sleep 1 |
| +добавлено | |
| +добавлено | cd "$ROOT" |
| +добавлено | exec ./ZCode.exe "$@" |
| +добавлено | |
| +добавлено | Apache License |
| +добавлено | Version 2.0, January 2004 |
| +добавлено | http://www.apache.org/licenses/ |
| +добавлено | |
| +добавлено | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
| +добавлено | |
| +добавлено | 1. Definitions. |
| +добавлено | |
| +добавлено | "License" shall mean the terms and conditions for use, reproduction, |
| +добавлено | and distribution as defined by Sections 1 through 9 of this document. |
| +добавлено | |
| +добавлено | "Licensor" shall mean the copyright owner or entity authorized by |
| +добавлено | the copyright owner that is granting the License. |
| +добавлено | |
| +добавлено | "Legal Entity" shall mean the union of the acting entity and all |
| +добавлено | other entities that control, are controlled by, or are under common |
| +добавлено | control with that entity. For the purposes of this definition, |
| +добавлено | "control" means (i) the power, direct or indirect, to cause the |
| +добавлено | direction or management of such entity, whether by contract or |
| +добавлено | otherwise, or (ii) ownership of fifty percent (50%) or more of the |
| +добавлено | outstanding shares, or (iii) beneficial ownership of such entity. |
| +добавлено | |
| +добавлено | "You" (or "Your") shall mean an individual or Legal Entity |
| +добавлено | exercising permissions granted by this License. |
| +добавлено | |
| +добавлено | "Source" form shall mean the preferred form for making modifications, |
| +добавлено | including but not limited to software source code, documentation |
| +добавлено | source, and configuration files. |
| +добавлено | |
| +добавлено | "Object" form shall mean any form resulting from mechanical |
| +добавлено | transformation or translation of a Source form, including but |
| +добавлено | not limited to compiled object code, generated documentation, |
| +добавлено | and conversions to other media types. |
| +добавлено | |
| +добавлено | "Work" shall mean the work of authorship, whether in Source or |
| +добавлено | Object form, made available under the License, as indicated by a |
| +добавлено | copyright notice that is included in or attached to the work |
| +добавлено | (an example is provided in the Appendix below). |
| +добавлено | |
| +добавлено | "Derivative Works" shall mean any work, whether in Source or Object |
| +добавлено | form, that is based on (or derived from) the Work and for which the |
| +добавлено | editorial revisions, annotations, elaborations, or other modifications |
| +добавлено | represent, as a whole, an original work of authorship. For the purposes |
| +добавлено | of this License, Derivative Works shall not include works that remain |
| +добавлено | separable from, or merely link (or bind by name) to the interfaces of, |
| +добавлено | the Work and Derivative Works thereof. |
| +добавлено | |
| +добавлено | "Contribution" shall mean any work of authorship, including |
| +добавлено | the original version of the Work and any modifications or additions |
| +добавлено | to that Work or Derivative Works thereof, that is intentionally |
| +добавлено | submitted to Licensor for inclusion in the Work by the copyright owner |
| +добавлено | or by an individual or Legal Entity authorized to submit on behalf of |
| +добавлено | the copyright owner. For the purposes of this definition, "submitted" |
| +добавлено | means any form of electronic, verbal, or written communication sent |
| +добавлено | to the Licensor or its representatives, including but not limited to |
| +добавлено | communication on electronic mailing lists, source code control systems, |
| +добавлено | and issue tracking systems that are managed by, or on behalf of, the |
| +добавлено | Licensor for the purpose of discussing and improving the Work, but |
| +добавлено | excluding communication that is conspicuously marked or otherwise |
| +добавлено | designated in writing by the copyright owner as "Not a Contribution." |
| +добавлено | |
| +добавлено | "Contributor" shall mean Licensor and any individual or Legal Entity |
| +добавлено | on behalf of whom a Contribution has been received by Licensor and |
| +добавлено | subsequently incorporated within the Work. |
| +добавлено | |
| +добавлено | 2. Grant of Copyright License. Subject to the terms and conditions of |
| +добавлено | this License, each Contributor hereby grants to You a perpetual, |
| +добавлено | worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
| +добавлено | copyright license to reproduce, prepare Derivative Works of, |
| +добавлено | publicly display, publicly perform, sublicense, and distribute the |
| +добавлено | Work and such Derivative Works in Source or Object form. |
| +добавлено | |
| +добавлено | 3. Grant of Patent License. Subject to the terms and conditions of |
| +добавлено | this License, each Contributor hereby grants to You a perpetual, |
| +добавлено | worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
| +добавлено | (except as stated in this section) patent license to make, have made, |
| +добавлено | use, offer to sell, sell, import, and otherwise transfer the Work, |
| +добавлено | where such license applies only to those patent claims licensable |
| +добавлено | by such Contributor that are necessarily infringed by their |
| +добавлено | Contribution(s) alone or by combination of their Contribution(s) |
| +добавлено | with the Work to which such Contribution(s) was submitted. If You |
| +добавлено | institute patent litigation against any entity (including a |
| +добавлено | cross-claim or counterclaim in a lawsuit) alleging that the Work |
| +добавлено | or a Contribution incorporated within the Work constitutes direct |
| +добавлено | or contributory patent infringement, then any patent licenses |
| +добавлено | granted to You under this License for that Work shall terminate |
| +добавлено | as of the date such litigation is filed. |
| +добавлено | |
| +добавлено | 4. Redistribution. You may reproduce and distribute copies of the |
| +добавлено | Work or Derivative Works thereof in any medium, with or without |
| +добавлено | modifications, and in Source or Object form, provided that You |
| +добавлено | meet the following conditions: |
| +добавлено | |
| +добавлено | (a) You must give any other recipients of the Work or |
| +добавлено | Derivative Works a copy of this License; and |
| +добавлено | |
| +добавлено | (b) You must cause any modified files to carry prominent notices |
| +добавлено | stating that You changed the files; and |
| +добавлено | |
| +добавлено | (c) You must retain, in the Source form of any Derivative Works |
| +добавлено | that You distribute, all copyright, patent, trademark, and |
| +добавлено | attribution notices from the Source form of the Work, |
| +добавлено | excluding those notices that do not pertain to any part of |
| +добавлено | the Derivative Works; and |
| +добавлено | |
| +добавлено | (d) If the Work includes a "NOTICE" text file as part of its |
| +добавлено | distribution, then any Derivative Works that You distribute must |
| +добавлено | include a readable copy of the attribution notices contained |
| +добавлено | within such NOTICE file, excluding those notices that do not |
| +добавлено | pertain to any part of the Derivative Works, in at least one |
| +добавлено | of the following places: within a NOTICE text file distributed |
| +добавлено | as part of the Derivative Works; within the Source form or |
| +добавлено | documentation, if provided along with the Derivative Works; or, |
| +добавлено | within a display generated by the Derivative Works, if and |
| +добавлено | wherever such third-party notices normally appear. The contents |
| +добавлено | of the NOTICE file are for informational purposes only and |
| +добавлено | do not modify the License. You may add Your own attribution |
| +добавлено | notices within Derivative Works that You distribute, alongside |
| +добавлено | or as an addendum to the NOTICE text from the Work, provided |
| +добавлено | that such additional attribution notices cannot be construed |
| +добавлено | as modifying the License. |
| +добавлено | |
| +добавлено | You may add Your own copyright statement to Your modifications and |
| +добавлено | may provide additional or different license terms and conditions |
| +добавлено | for use, reproduction, or distribution of Your modifications, or |
| +добавлено | for any such Derivative Works as a whole, provided Your use, |
| +добавлено | reproduction, and distribution of the Work otherwise complies with |
| +добавлено | the conditions stated in this License. |
| +добавлено | |
| +добавлено | 5. Submission of Contributions. Unless You explicitly state otherwise, |
| +добавлено | any Contribution intentionally submitted for inclusion in the Work |
| +добавлено | by You to the Licensor shall be under the terms and conditions of |
| +добавлено | this License, without any additional terms or conditions. |
| +добавлено | Notwithstanding the above, nothing herein shall supersede or modify |
| +добавлено | the terms of any separate license agreement you may have executed |
| +добавлено | with Licensor regarding such Contributions. |
| +добавлено | |
| +добавлено | 6. Trademarks. This License does not grant permission to use the trade |
| +добавлено | names, trademarks, service marks, or product names of the Licensor, |
| +добавлено | except as required for reasonable and customary use in describing the |
| +добавлено | origin of the Work and reproducing the content of the NOTICE file. |
| +добавлено | |
| +добавлено | 7. Disclaimer of Warranty. Unless required by applicable law or |
| +добавлено | agreed to in writing, Licensor provides the Work (and each |
| +добавлено | Contributor provides its Contributions) on an "AS IS" BASIS, |
| +добавлено | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| +добавлено | implied, including, without limitation, any warranties or conditions |
| +добавлено | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
| +добавлено | PARTICULAR PURPOSE. You are solely responsible for determining the |
| +добавлено | appropriateness of using or redistributing the Work and assume any |
| +добавлено | risks associated with Your exercise of permissions under this License. |
| +добавлено | |
| +добавлено | 8. Limitation of Liability. In no event and under no legal theory, |
| +добавлено | whether in tort (including negligence), contract, or otherwise, |
| +добавлено | unless required by applicable law (such as deliberate and grossly |
| +добавлено | negligent acts) or agreed to in writing, shall any Contributor be |
| +добавлено | liable to You for damages, including any direct, indirect, special, |
| +добавлено | incidental, or consequential damages of any character arising as a |
| +добавлено | result of this License or out of the use or inability to use the |
| +добавлено | Work (including but not limited to damages for loss of goodwill, |
| +добавлено | work stoppage, computer failure or malfunction, or any and all |
| +добавлено | other commercial damages or losses), even if such Contributor |
| +добавлено | has been advised of the possibility of such damages. |
| +добавлено | |
| +добавлено | 9. Accepting Warranty or Additional Liability. While redistributing |
| +добавлено | the Work or Derivative Works thereof, You may choose to offer, |
| +добавлено | and charge a fee for, acceptance of support, warranty, indemnity, |
| +добавлено | or other liability obligations and/or rights consistent with this |
| +добавлено | License. However, in accepting such obligations, You may act only |
| +добавлено | on Your own behalf and on Your sole responsibility, not on behalf |
| +добавлено | of any other Contributor, and only if You agree to indemnify, |
| +добавлено | defend, and hold each Contributor harmless for any liability |
| +добавлено | incurred by, or claims asserted against, such Contributor by reason |
| +добавлено | of your accepting any such warranty or additional liability. |
| +добавлено | |
| +добавлено | END OF TERMS AND CONDITIONS |
| +добавлено | |
| +добавлено | APPENDIX: How to apply the Apache License to your work. |
| +добавлено | |
| +добавлено | To apply the Apache License to your work, attach the following |
| +добавлено | boilerplate notice, with the fields enclosed by brackets "[]" |
| +добавлено | replaced with your own identifying information. (Don't include |
| +добавлено | the brackets!) The text should be enclosed in the appropriate |
| +добавлено | comment syntax for the file format. We also recommend that a |
| +добавлено | file or class name and description of purpose be included on the |
| +добавлено | same "printed page" as the copyright notice for easier |
| +добавлено | identification within third-party archives. |
| +добавлено | |
| +добавлено | Copyright 2018 Google Inc. |
| +добавлено | |
| +добавлено | Licensed under the Apache License, Version 2.0 (the "License"); |
| +добавлено | you may not use this file except in compliance with the License. |
| +добавлено | You may obtain a copy of the License at |
| +добавлено | |
| +добавлено | http://www.apache.org/licenses/LICENSE-2.0 |
| +добавлено | |
| +добавлено | Unless required by applicable law or agreed to in writing, software |
| +добавлено | distributed under the License is distributed on an "AS IS" BASIS, |
| +добавлено | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| +добавлено | See the License for the specific language governing permissions and |
| +добавлено | limitations under the License. |
| +добавлено | The MIT License (MIT) |
| +добавлено | |
| +добавлено | Copyright (c) 2015-present Jason Miller |
| +добавлено | |
| +добавлено | Permission is hereby granted, free of charge, to any person obtaining a copy |
| +добавлено | of this software and associated documentation files (the "Software"), to deal |
| +добавлено | in the Software without restriction, including without limitation the rights |
| +добавлено | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| +добавлено | copies of the Software, and to permit persons to whom the Software is |
| +добавлено | furnished to do so, subject to the following conditions: |
| +добавлено | |
| +добавлено | The above copyright notice and this permission notice shall be included in all |
| +добавлено | copies or substantial portions of the Software. |
| +добавлено | |
| +добавлено | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| +добавлено | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| +добавлено | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| +добавлено | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| +добавлено | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| +добавлено | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| +добавлено | SOFTWARE. |
| +добавлено | // Глобальное состояние приложения: сессия, выбранная команда, роль, SSE, связь с родительским окном. |
| +добавлено | import { createStore, loadState, saveSettings, rpc, invalidate, fetchRes, clearCache, onAuthLost, debounce, svc, peekRes, humanError } from './core.js'; |
| +добавлено | |
| +добавлено | export const app = createStore({ |
| +добавлено | phase: 'loading', // loading | error | auth | ready |
| +добавлено | error: null, |
| +добавлено | state: null, // /state |
| +добавлено | session: null, // rpc session |
| +добавлено | teamId: null, |
| +добавлено | live: false, // SSE подключён |
| +добавлено | visible: true, |
| +добавлено | lastEvent: null, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | const set = (patch) => app.set((s) => ({ ...s, ...patch })); |
| +добавлено | |
| +добавлено | export const currentTeam = (s = app.get()) => s.session?.teams?.find((t) => t.id === s.teamId) ?? null; |
| +добавлено | export const myRole = (s = app.get()) => currentTeam(s)?.role ?? null; |
| +добавлено | export const me = (s = app.get()) => s.session?.user ?? null; |
| +добавлено | |
| +добавлено | export const keyFor = { |
| +добавлено | board: (t) => `board:${t}`, |
| +добавлено | activity: (t) => `activity:${t}`, |
| +добавлено | trash: (t) => `trash:${t}`, |
| +добавлено | keys: (t) => `keys:${t}`, |
| +добавлено | usage: (t) => `usage:${t}`, |
| +добавлено | files: (t) => `files:${t}`, |
| +добавлено | archives: (t) => `archives:${t}`, |
| +добавлено | invite: (t) => `invite:${t}`, |
| +добавлено | proxyTokens: (t) => `proxyTokens:${t}`, |
| +добавлено | providers: (t) => `providers:${t}`, |
| +добавлено | limits: (t) => `limits:${t}`, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- загрузка |
| +добавлено | |
| +добавлено | export async function boot() { |
| +добавлено | try { |
| +добавлено | const state = await loadState(); |
| +добавлено | set({ state }); |
| +добавлено | if (!state.signedIn) { set({ phase: 'auth', session: null }); return; } |
| +добавлено | await refreshSession(); |
| +добавлено | } catch (e) { |
| +добавлено | set({ phase: 'error', error: humanError(e) }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function refreshSession() { |
| +добавлено | try { |
| +добавлено | const session = await rpc('session'); |
| +добавлено | const state = svc.state; |
| +добавлено | let teamId = state?.teamId ?? null; |
| +добавлено | const teams = session?.teams ?? []; |
| +добавлено | if (teamId && !teams.some((t) => t.id === teamId)) teamId = null; |
| +добавлено | // Без выбранной команды роль не разрешается и управление ключами вкладки «Ключи» |
| +добавлено | // прячется. Берём первую из списка, а не только когда команда ровно одна. |
| +добавлено | if (!teamId && teams.length) { |
| +добавлено | teamId = teams[0].id; |
| +добавлено | saveSettings({ teamId }).catch(() => {}); |
| +добавлено | } |
| +добавлено | set({ session, teamId, phase: 'ready', error: null, state: svc.state }); |
| +добавлено | return session; |
| +добавлено | } catch (e) { |
| +добавлено | if (e.status === 401) { set({ phase: 'auth', session: null }); return null; } |
| +добавлено | set({ phase: 'error', error: humanError(e) }); |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function selectTeam(teamId) { |
| +добавлено | set({ teamId }); |
| +добавлено | await saveSettings({ teamId }).catch(() => {}); |
| +добавлено | rpc('selectTeam', { teamId }).catch(() => {}); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function afterSignIn() { |
| +добавлено | clearCache(); |
| +добавлено | await loadState().catch(() => {}); |
| +добавлено | set({ state: svc.state }); |
| +добавлено | await refreshSession(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function signOut() { |
| +добавлено | try { await rpc('logout'); } catch { /* всё равно выходим */ } |
| +добавлено | clearCache(); |
| +добавлено | await loadState().catch(() => {}); |
| +добавлено | set({ phase: 'auth', session: null, teamId: null, state: svc.state }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | onAuthLost(() => { |
| +добавлено | if (app.get().phase === 'ready') set({ phase: 'auth', session: null }); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- SSE |
| +добавлено | |
| +добавлено | const TEAM_EVENT_MAP = { |
| +добавлено | 'task.changed': ['board', 'trash', 'taskHistory', 'taskCommits'], |
| +добавлено | 'activity.changed': ['activity'], |
| +добавлено | 'membership.changed': ['board', 'session', 'invite', 'directory'], |
| +добавлено | 'member.changed': ['board', 'session'], |
| +добавлено | 'presence.changed': ['board'], |
| +добавлено | 'project.changed': ['board', 'archives'], |
| +добавлено | 'file.changed': ['files', 'archives'], |
| +добавлено | 'team.changed': ['session', 'board'], |
| +добавлено | }; |
| +добавлено | |
| +добавлено | let pending = new Set(); |
| +добавлено | const flush = debounce(() => { |
| +добавлено | const list = [...pending]; |
| +добавлено | pending = new Set(); |
| +добавлено | if (list.includes('session')) refreshSession(); |
| +добавлено | if (list.includes('state')) loadState().then(() => set({ state: svc.state })).catch(() => {}); |
| +добавлено | const rest = list.filter((x) => x !== 'session' && x !== 'state'); |
| +добавлено | if (rest.length) invalidate(...rest); |
| +добавлено | }, 250); |
| +добавлено | |
| +добавлено | function queue(keys) { |
| +добавлено | for (const k of keys) pending.add(k); |
| +добавлено | flush(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | let es = null; |
| +добавлено | let retry = 0; |
| +добавлено | let retryTimer = 0; |
| +добавлено | |
| +добавлено | export function connectEvents() { |
| +добавлено | if (es || !app.get().visible) return; |
| +добавлено | if (typeof EventSource === 'undefined') return; |
| +добавлено | try { |
| +добавлено | es = new EventSource('/events'); |
| +добавлено | } catch { |
| +добавлено | scheduleReconnect(); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | es.onopen = () => { |
| +добавлено | const wasDown = retry > 0; |
| +добавлено | retry = 0; |
| +добавлено | set({ live: true }); |
| +добавлено | if (wasDown) queue(['board', 'activity', 'files', 'keys', 'session']); |
| +добавлено | }; |
| +добавлено | es.onerror = () => { |
| +добавлено | set({ live: false }); |
| +добавлено | es?.close(); |
| +добавлено | es = null; |
| +добавлено | scheduleReconnect(); |
| +добавлено | }; |
| +добавлено | es.addEventListener('team', (ev) => { |
| +добавлено | let data = {}; |
| +добавлено | try { data = JSON.parse(ev.data); } catch { /* ignore */ } |
| +добавлено | const keys = TEAM_EVENT_MAP[data.type]; |
| +добавлено | set({ lastEvent: { ...data, at: Date.now() } }); |
| +добавлено | if (keys) queue(data.type === 'activity.changed' || data.type.startsWith('task') ? [...keys, 'activity'] : keys); |
| +добавлено | }); |
| +добавлено | es.addEventListener('local', (ev) => { |
| +добавлено | let data = {}; |
| +добавлено | try { data = JSON.parse(ev.data); } catch { /* ignore */ } |
| +добавлено | if (data.type === 'git') queue(['git', 'gitLog', 'gitBranches']); |
| +добавлено | else if (data.type === 'ide') queue(['state', 'git']); |
| +добавлено | else if (data.type === 'state') queue(['state', 'localProviders', 'keys']); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function scheduleReconnect() { |
| +добавлено | clearTimeout(retryTimer); |
| +добавлено | if (!app.get().visible) return; |
| +добавлено | retry++; |
| +добавлено | const delay = Math.min(15000, 600 * 2 ** Math.min(retry, 5)); |
| +добавлено | retryTimer = setTimeout(connectEvents, delay); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function disconnectEvents() { |
| +добавлено | clearTimeout(retryTimer); |
| +добавлено | es?.close(); |
| +добавлено | es = null; |
| +добавлено | set({ live: false }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- родительское окно |
| +добавлено | |
| +добавлено | let lastPending = -1; |
| +добавлено | export function postPending(count) { |
| +добавлено | if (count === lastPending) return; |
| +добавлено | lastPending = count; |
| +добавлено | try { window.parent?.postMessage({ type: 'zteam:pending', count }, '*'); } catch { /* ignore */ } |
| +добавлено | } |
| +добавлено | export function postClose() { |
| +добавлено | try { window.parent?.postMessage({ type: 'zteam:close' }, '*'); } catch { /* ignore */ } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function applyTheme(dark, vars) { |
| +добавлено | const root = document.documentElement; |
| +добавлено | root.classList.toggle('light', !dark); |
| +добавлено | if (vars && typeof vars === 'object') { |
| +добавлено | for (const [k, v] of Object.entries(vars)) { |
| +добавлено | if (/^--zt-[a-z0-9-]+$/i.test(k) && typeof v === 'string' && v.length < 200) root.style.setProperty(k, v); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function installParentBridge() { |
| +добавлено | window.addEventListener('message', (ev) => { |
| +добавлено | const d = ev.data; |
| +добавлено | if (!d || typeof d !== 'object') return; |
| +добавлено | if (d.type === 'zteam:theme') applyTheme(d.dark !== false, d.vars); |
| +добавлено | else if (d.type === 'zteam:visible') { |
| +добавлено | const visible = !!d.visible; |
| +добавлено | set({ visible }); |
| +добавлено | if (!visible) disconnectEvents(); |
| +добавлено | else { connectEvents(); queue(['board', 'activity', 'session']); } |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | document.addEventListener('visibilitychange', () => { |
| +добавлено | if (document.hidden) return; |
| +добавлено | if (!es && app.get().visible) connectEvents(); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function reloadAll() { |
| +добавлено | queue(['session', 'state']); |
| +добавлено | invalidate('board', 'activity', 'trash', 'keys', 'usage', 'files', 'archives', 'invite', 'proxyTokens', 'localProviders', 'git', 'gitLog', 'gitBranches', 'limits', 'providers'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export { peekRes, fetchRes }; |
| +добавлено | // Ядро панели: htm-биндинг, клиент локального сервиса, кэш ресурсов, тосты, утилиты. |
| +добавлено | import { h } from 'preact'; |
| +добавлено | import { useEffect, useState, useRef, useCallback } from 'preact/hooks'; |
| +добавлено | import htm from 'htm'; |
| +добавлено | |
| +добавлено | export const html = htm.bind(h); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- клиент сервиса |
| +добавлено | |
| +добавлено | export const svc = { |
| +добавлено | state: null, // GET /state |
| +добавлено | csrf: '', |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export class RpcError extends Error { |
| +добавлено | constructor(message, status, body) { |
| +добавлено | super(message); |
| +добавлено | this.status = status; |
| +добавлено | this.body = body; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const authListeners = new Set(); |
| +добавлено | export function onAuthLost(fn) { authListeners.add(fn); return () => authListeners.delete(fn); } |
| +добавлено | |
| +добавлено | export async function loadState() { |
| +добавлено | const res = await fetch('/state', { cache: 'no-store' }); |
| +добавлено | if (!res.ok) throw new RpcError('Сервис недоступен (HTTP ' + res.status + ')', res.status); |
| +добавлено | svc.state = await res.json(); |
| +добавлено | svc.csrf = svc.state.csrfToken || ''; |
| +добавлено | return svc.state; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function saveSettings(patch) { |
| +добавлено | const res = await fetch('/settings', { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'Content-Type': 'application/json', 'X-ZTeam-CSRF': svc.csrf }, |
| +добавлено | body: JSON.stringify(patch), |
| +добавлено | }); |
| +добавлено | if (!res.ok) throw new RpcError('Не удалось сохранить настройки', res.status); |
| +добавлено | if (svc.state) { |
| +добавлено | if (patch.ui) svc.state = { ...svc.state, ...patch, ui: { ...(svc.state.ui || {}), ...patch.ui } }; |
| +добавлено | else svc.state = { ...svc.state, ...patch }; |
| +добавлено | } |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | let uiSaveTimer = null; |
| +добавлено | let uiPending = {}; |
| +добавлено | export function saveUi(patch) { |
| +добавлено | uiPending = { ...uiPending, ...patch }; |
| +добавлено | if (svc.state) svc.state.ui = { ...(svc.state.ui || {}), ...patch }; |
| +добавлено | clearTimeout(uiSaveTimer); |
| +добавлено | uiSaveTimer = setTimeout(() => { |
| +добавлено | const ui = { ...(svc.state?.ui || {}), ...uiPending }; |
| +добавлено | uiPending = {}; |
| +добавлено | saveSettings({ ui }).catch(() => {}); |
| +добавлено | }, 400); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const ERR_RU = [ |
| +добавлено | [/invalid (email or )?password|invalid credentials|wrong password/i, 'Неверный email или пароль'], |
| +добавлено | [/already (registered|exists)|email.*taken/i, 'Этот email уже зарегистрирован'], |
| +добавлено | [/not signed in|unauthorized/i, 'Требуется вход'], |
| +добавлено | [/forbidden|insufficient|not allowed|permission/i, 'Недостаточно прав'], |
| +добавлено | [/not found/i, 'Не найдено'], |
| +добавлено | [/fetch failed|network|ECONNREFUSED|ENOTFOUND/i, 'Нет связи с сервером'], |
| +добавлено | [/too many|rate limit/i, 'Слишком много запросов, попробуйте позже'], |
| +добавлено | [/invalid.*code|expired/i, 'Код недействителен или истёк'], |
| +добавлено | ]; |
| +добавлено | export function humanError(err) { |
| +добавлено | const msg = String(err?.message || err || 'Ошибка'); |
| +добавлено | for (const [re, ru] of ERR_RU) if (re.test(msg)) return ru; |
| +добавлено | return msg; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const rpcLog = []; // для dev-тестов |
| +добавлено | |
| +добавлено | export async function rpc(method, params = {}) { |
| +добавлено | rpcLog.push({ method, params, at: Date.now() }); |
| +добавлено | if (rpcLog.length > 400) rpcLog.shift(); |
| +добавлено | let res; |
| +добавлено | try { |
| +добавлено | res = await fetch('/rpc', { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'Content-Type': 'application/json', 'X-ZTeam-CSRF': svc.csrf }, |
| +добавлено | body: JSON.stringify({ method, params }), |
| +добавлено | }); |
| +добавлено | } catch (e) { |
| +добавлено | throw new RpcError('Локальный сервис недоступен', 0); |
| +добавлено | } |
| +добавлено | let data = null; |
| +добавлено | try { data = await res.json(); } catch { /* пусто */ } |
| +добавлено | if (!res.ok || data?.ok === false) { |
| +добавлено | const err = new RpcError(data?.error || 'HTTP ' + res.status, res.status, data?.body); |
| +добавлено | if (res.status === 401 && method !== 'login' && method !== 'devicePoll' && method !== 'changePassword') { |
| +добавлено | for (const fn of authListeners) fn(err); |
| +добавлено | } |
| +добавлено | if (res.status === 403 && /csrf/i.test(err.message)) { |
| +добавлено | // токен сменился (сервис перезапущен) — подтянем новый и повторим один раз |
| +добавлено | await loadState().catch(() => {}); |
| +добавлено | return rpc(method, params); |
| +добавлено | } |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | return data?.result; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** rpc + тост об ошибке. Возвращает [result, error]. */ |
| +добавлено | export async function act(method, params, { ok, quiet } = {}) { |
| +добавлено | try { |
| +добавлено | const r = await rpc(method, params); |
| +добавлено | if (ok) toast(typeof ok === 'function' ? ok(r) : ok, { kind: 'ok' }); |
| +добавлено | return [r, null]; |
| +добавлено | } catch (e) { |
| +добавлено | if (!quiet) { |
| +добавлено | if (e.status === 403) toast('Недостаточно прав', { kind: 'err' }); |
| +добавлено | else if (e.status !== 401) toast(humanError(e), { kind: 'err' }); |
| +добавлено | } |
| +добавлено | return [null, e]; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- маленький pub/sub |
| +добавлено | |
| +добавлено | export function createStore(initial) { |
| +добавлено | let value = initial; |
| +добавлено | const subs = new Set(); |
| +добавлено | return { |
| +добавлено | get: () => value, |
| +добавлено | set(next) { |
| +добавлено | value = typeof next === 'function' ? next(value) : next; |
| +добавлено | for (const s of subs) s(value); |
| +добавлено | }, |
| +добавлено | sub(fn) { subs.add(fn); return () => subs.delete(fn); }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function useStore(store) { |
| +добавлено | const [v, setV] = useState(store.get()); |
| +добавлено | useEffect(() => { |
| +добавлено | setV(store.get()); |
| +добавлено | return store.sub(setV); |
| +добавлено | }, [store]); |
| +добавлено | return v; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- кэш ресурсов |
| +добавлено | |
| +добавлено | const cache = new Map(); // key -> {data, error, loading, at, fetcher, subs:Set, promise, stale} |
| +добавлено | |
| +добавлено | function entry(key) { |
| +добавлено | let e = cache.get(key); |
| +добавлено | if (!e) { |
| +добавлено | e = { data: undefined, error: null, loading: false, at: 0, fetcher: null, subs: new Set(), promise: null, stale: true }; |
| +добавлено | cache.set(key, e); |
| +добавлено | } |
| +добавлено | return e; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function emit(e) { for (const s of e.subs) s({ data: e.data, error: e.error, loading: e.loading }); } |
| +добавлено | |
| +добавлено | export function fetchRes(key, fetcher) { |
| +добавлено | const e = entry(key); |
| +добавлено | if (fetcher) e.fetcher = fetcher; |
| +добавлено | if (!e.fetcher) return Promise.resolve(e.data); |
| +добавлено | if (e.promise) { e.again = true; return e.promise; } |
| +добавлено | e.loading = true; |
| +добавлено | e.stale = false; |
| +добавлено | emit(e); |
| +добавлено | const run = async () => { |
| +добавлено | try { |
| +добавлено | const data = await e.fetcher(); |
| +добавлено | e.data = data; |
| +добавлено | e.error = null; |
| +добавлено | e.at = Date.now(); |
| +добавлено | } catch (err) { |
| +добавлено | e.error = err; |
| +добавлено | } finally { |
| +добавлено | e.loading = false; |
| +добавлено | e.promise = null; |
| +добавлено | emit(e); |
| +добавлено | if (e.again) { e.again = false; fetchRes(key); } |
| +добавлено | } |
| +добавлено | return e.data; |
| +добавлено | }; |
| +добавлено | e.promise = run(); |
| +добавлено | return e.promise; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Локально поменять данные ресурса (оптимистичные апдейты). */ |
| +добавлено | export function mutateRes(key, fn) { |
| +добавлено | const e = entry(key); |
| +добавлено | e.data = typeof fn === 'function' ? fn(e.data) : fn; |
| +добавлено | emit(e); |
| +добавлено | } |
| +добавлено | export function peekRes(key) { return cache.get(key)?.data; } |
| +добавлено | |
| +добавлено | /** Перезапросить все ресурсы, чей ключ начинается с одного из префиксов. Неактивные — пометить stale. */ |
| +добавлено | export function invalidate(...prefixes) { |
| +добавлено | for (const [key, e] of cache) { |
| +добавлено | if (!prefixes.some((p) => key === p || key.startsWith(p + ':'))) continue; |
| +добавлено | if (e.subs.size && e.fetcher) fetchRes(key); |
| +добавлено | else e.stale = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | export function clearCache() { |
| +добавлено | for (const [, e] of cache) { e.data = undefined; e.error = null; e.stale = true; emit(e); } |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * useRes(key, fetcher): общий кэш. key=null — ничего не грузить. |
| +добавлено | * Возвращает {data, error, loading, reload}. |
| +добавлено | */ |
| +добавлено | export function useRes(key, fetcher) { |
| +добавлено | const fRef = useRef(fetcher); |
| +добавлено | fRef.current = fetcher; |
| +добавлено | const [snap, setSnap] = useState(() => { |
| +добавлено | const e = key ? cache.get(key) : null; |
| +добавлено | return { data: e?.data, error: e?.error ?? null, loading: !!e?.loading || (key != null && e?.data === undefined) }; |
| +добавлено | }); |
| +добавлено | useEffect(() => { |
| +добавлено | if (!key) { setSnap({ data: undefined, error: null, loading: false }); return; } |
| +добавлено | const e = entry(key); |
| +добавлено | e.fetcher = () => fRef.current(); |
| +добавлено | e.subs.add(setSnap); |
| +добавлено | setSnap({ data: e.data, error: e.error, loading: e.loading || e.data === undefined }); |
| +добавлено | if (e.stale || e.data === undefined) fetchRes(key); |
| +добавлено | return () => e.subs.delete(setSnap); |
| +добавлено | }, [key]); |
| +добавлено | const reload = useCallback(() => (key ? fetchRes(key) : Promise.resolve()), [key]); |
| +добавлено | return { ...snap, reload }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- тосты |
| +добавлено | |
| +добавлено | export const toasts = createStore([]); |
| +добавлено | let toastSeq = 0; |
| +добавлено | export function toast(message, { kind = 'info', action, timeout = 3500 } = {}) { |
| +добавлено | const id = ++toastSeq; |
| +добавлено | toasts.set((list) => [...list.slice(-3), { id, message, kind, action, timeout }]); |
| +добавлено | return id; |
| +добавлено | } |
| +добавлено | export function dismissToast(id) { |
| +добавлено | toasts.set((list) => list.map((t) => (t.id === id ? { ...t, leaving: true } : t))); |
| +добавлено | setTimeout(() => toasts.set((list) => list.filter((t) => t.id !== id)), 180); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- утилиты |
| +добавлено | |
| +добавлено | export const ROLE_RANK = { viewer: 0, dev: 1, maintainer: 2, owner: 3 }; |
| +добавлено | export const ROLE_RU = { owner: 'Владелец', maintainer: 'Мейнтейнер', dev: 'Разработчик', viewer: 'Наблюдатель' }; |
| +добавлено | export const roleAtLeast = (role, min) => (ROLE_RANK[role] ?? -1) >= ROLE_RANK[min]; |
| +добавлено | |
| +добавлено | export const STATUS_RU = { '': 'Не задан', online: 'В сети', away: 'Отошёл', busy: 'Занят', dnd: 'Не беспокоить' }; |
| +добавлено | export const TASK_STATUSES = [ |
| +добавлено | { id: 'todo', label: 'К выполнению' }, |
| +добавлено | { id: 'doing', label: 'В работе' }, |
| +добавлено | { id: 'review', label: 'Проверка' }, |
| +добавлено | { id: 'done', label: 'Готово' }, |
| +добавлено | ]; |
| +добавлено | export const STATUS_LABEL = Object.fromEntries(TASK_STATUSES.map((s) => [s.id, s.label])); |
| +добавлено | export const PRIORITIES = [ |
| +добавлено | { id: 'urgent', label: 'Срочно' }, |
| +добавлено | { id: 'high', label: 'Высокий' }, |
| +добавлено | { id: 'normal', label: 'Обычный' }, |
| +добавлено | { id: 'low', label: 'Низкий' }, |
| +добавлено | ]; |
| +добавлено | export const PRIORITY_LABEL = Object.fromEntries(PRIORITIES.map((p) => [p.id, p.label])); |
| +добавлено | |
| +добавлено | export const AVATAR_COLORS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#14b8a6', '#0ea5e9', '#6366f1', '#a855f7', '#ec4899', '#64748b']; |
| +добавлено | |
| +добавлено | export function initials(name = '') { |
| +добавлено | const parts = String(name).trim().split(/[\s._@-]+/).filter(Boolean); |
| +добавлено | if (!parts.length) return '?'; |
| +добавлено | if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase(); |
| +добавлено | return (parts[0][0] + parts[1][0]).toUpperCase(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function colorFor(id = '', fallback) { |
| +добавлено | if (fallback) return fallback; |
| +добавлено | let x = 0; |
| +добавлено | for (const ch of String(id)) x = (x * 31 + ch.charCodeAt(0)) >>> 0; |
| +добавлено | return AVATAR_COLORS[x % AVATAR_COLORS.length]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const shortId = (id = '') => String(id).replace(/-/g, '').slice(0, 8); |
| +добавлено | |
| +добавлено | export function plural(n, one, few, many) { |
| +добавлено | const a = Math.abs(n) % 100; |
| +добавлено | const b = a % 10; |
| +добавлено | if (a > 10 && a < 20) return many; |
| +добавлено | if (b > 1 && b < 5) return few; |
| +добавлено | if (b === 1) return one; |
| +добавлено | return many; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function relTime(iso, now = Date.now()) { |
| +добавлено | if (!iso) return ''; |
| +добавлено | const t = new Date(iso).getTime(); |
| +добавлено | if (!Number.isFinite(t)) return ''; |
| +добавлено | const s = Math.round((now - t) / 1000); |
| +добавлено | const fut = s < 0; |
| +добавлено | const a = Math.abs(s); |
| +добавлено | let txt; |
| +добавлено | if (a < 45) return fut ? 'через минуту' : 'только что'; |
| +добавлено | if (a < 3600) { const m = Math.max(1, Math.round(a / 60)); txt = `${m} мин`; } |
| +добавлено | else if (a < 86400) { const hh = Math.round(a / 3600); txt = `${hh} ч`; } |
| +добавлено | else if (a < 86400 * 7) { const d = Math.round(a / 86400); if (d === 1 && !fut) return 'вчера'; txt = `${d} ${plural(d, 'день', 'дня', 'дней')}`; } |
| +добавлено | else return fmtDate(iso); |
| +добавлено | return fut ? 'через ' + txt : txt + ' назад'; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const MONTHS = ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']; |
| +добавлено | export function fmtDate(iso, withYear) { |
| +добавлено | if (!iso) return ''; |
| +добавлено | const d = new Date(iso); |
| +добавлено | if (!Number.isFinite(d.getTime())) return ''; |
| +добавлено | const y = withYear ?? d.getFullYear() !== new Date().getFullYear(); |
| +добавлено | return `${d.getDate()} ${MONTHS[d.getMonth()]}${y ? ' ' + d.getFullYear() : ''}`; |
| +добавлено | } |
| +добавлено | export function fmtDateTime(iso) { |
| +добавлено | if (!iso) return ''; |
| +добавлено | const d = new Date(iso); |
| +добавлено | if (!Number.isFinite(d.getTime())) return ''; |
| +добавлено | return `${fmtDate(iso)}, ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; |
| +добавлено | } |
| +добавлено | export function isOverdue(iso, status) { |
| +добавлено | if (!iso || status === 'done') return false; |
| +добавлено | const d = new Date(iso); |
| +добавлено | const today = new Date(); |
| +добавлено | today.setHours(0, 0, 0, 0); |
| +добавлено | return d.getTime() < today.getTime(); |
| +добавлено | } |
| +добавлено | export function toDateInput(iso) { |
| +добавлено | if (!iso) return ''; |
| +добавлено | const d = new Date(iso); |
| +добавлено | if (!Number.isFinite(d.getTime())) return ''; |
| +добавлено | return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function humanBytes(n) { |
| +добавлено | const v = Number(n) || 0; |
| +добавлено | if (v >= 1024 ** 3) return (v / 1024 ** 3).toFixed(1).replace('.', ',') + ' ГБ'; |
| +добавлено | if (v >= 1024 ** 2) return (v / 1024 ** 2).toFixed(v >= 10 * 1024 ** 2 ? 0 : 1).replace('.', ',') + ' МБ'; |
| +добавлено | if (v >= 1024) return Math.round(v / 1024) + ' КБ'; |
| +добавлено | return v + ' Б'; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function hostOf(url) { |
| +добавлено | if (!url) return ''; |
| +добавлено | try { return new URL(url).host; } catch { return String(url).replace(/^https?:\/\//, '').split('/')[0]; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function copyText(text, label = 'Скопировано') { |
| +добавлено | try { |
| +добавлено | await navigator.clipboard.writeText(text); |
| +добавлено | } catch { |
| +добавлено | const ta = document.createElement('textarea'); |
| +добавлено | ta.value = text; |
| +добавлено | ta.style.position = 'fixed'; |
| +добавлено | ta.style.opacity = '0'; |
| +добавлено | document.body.append(ta); |
| +добавлено | ta.select(); |
| +добавлено | try { document.execCommand('copy'); } catch { /* ignore */ } |
| +добавлено | ta.remove(); |
| +добавлено | } |
| +добавлено | toast(label, { kind: 'ok', timeout: 2000 }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const reducedMotion = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; |
| +добавлено | |
| +добавлено | export function debounce(fn, ms) { |
| +добавлено | let t; |
| +добавлено | return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Удерживать состояние "busy", но показывать спиннер только после 300мс. */ |
| +добавлено | export function useBusy() { |
| +добавлено | const [busy, setBusy] = useState(false); |
| +добавлено | const [spin, setSpin] = useState(false); |
| +добавлено | const t = useRef(0); |
| +добавлено | const run = useCallback(async (fn) => { |
| +добавлено | setBusy(true); |
| +добавлено | clearTimeout(t.current); |
| +добавлено | t.current = setTimeout(() => setSpin(true), 300); |
| +добавлено | try { return await fn(); } finally { clearTimeout(t.current); setBusy(false); setSpin(false); } |
| +добавлено | }, []); |
| +добавлено | return [busy, spin, run]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Тик раз в N секунд — для относительных времён. */ |
| +добавлено | export function useTick(ms = 30000) { |
| +добавлено | const [, set] = useState(0); |
| +добавлено | useEffect(() => { const i = setInterval(() => set((x) => x + 1), ms); return () => clearInterval(i); }, [ms]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Человекочитаемая строка активности/истории. */ |
| +добавлено | export function describeAction(a) { |
| +добавлено | const d = a.details || {}; |
| +добавлено | const t = a.taskTitle || d.title || ''; |
| +добавлено | const q = (s) => (s ? `«${s}»` : ''); |
| +добавлено | switch (a.action) { |
| +добавлено | case 'task.create': return `создал(а) задачу ${q(t)}`; |
| +добавлено | case 'task.update': { |
| +добавлено | const ch = d.changes || d; |
| +добавлено | if (ch.status) return `перевёл(а) ${q(t)} в «${STATUS_LABEL[ch.status] || ch.status}»`; |
| +добавлено | if ('assigneeId' in ch || ch.assigneeName) return ch.assigneeName ? `назначил(а) ${q(t)} на ${ch.assigneeName}` : `снял(а) исполнителя с ${q(t)}`; |
| +добавлено | if (ch.priority) return `изменил(а) приоритет ${q(t)} на «${PRIORITY_LABEL[ch.priority] || ch.priority}»`; |
| +добавлено | if ('dueAt' in ch) return ch.dueAt ? `назначил(а) срок ${q(t)} на ${fmtDate(ch.dueAt)}` : `убрал(а) срок у ${q(t)}`; |
| +добавлено | if (ch.title) return `переименовал(а) задачу в ${q(ch.title)}`; |
| +добавлено | if (ch.labels) return `изменил(а) метки ${q(t)}`; |
| +добавлено | if ('description' in ch) return `обновил(а) описание ${q(t)}`; |
| +добавлено | return `обновил(а) задачу ${q(t)}`; |
| +добавлено | } |
| +добавлено | case 'task.delete': return `удалил(а) задачу ${q(t)}`; |
| +добавлено | case 'task.restore': return `восстановил(а) задачу ${q(t)}`; |
| +добавлено | case 'task.reorder': return d.status ? `переместил(а) задачи в «${STATUS_LABEL[d.status] || d.status}»` : 'изменил(а) порядок задач'; |
| +добавлено | case 'task.commit_link': return `привязал(а) коммит ${String(d.hash || '').slice(0, 7)} к ${q(t)}`; |
| +добавлено | case 'team.create': return `создал(а) команду ${q(d.name)}`; |
| +добавлено | case 'team.rename': return `переименовал(а) команду в ${q(d.name)}`; |
| +добавлено | case 'invite.create': return 'создал(а) код приглашения'; |
| +добавлено | case 'invite.revoke': return 'отозвал(а) приглашение'; |
| +добавлено | case 'invite.accept': return 'вступил(а) в команду'; |
| +добавлено | case 'member.add': return `добавил(а) ${d.displayName || 'участника'} в команду`; |
| +добавлено | case 'membership.role': return `сменил(а) роль${d.displayName ? ' ' + d.displayName : ''} на «${ROLE_RU[d.role] || d.role}»`; |
| +добавлено | case 'membership.remove': return `исключил(а) ${d.displayName || 'участника'}`; |
| +добавлено | case 'membership.leave': return 'покинул(а) команду'; |
| +добавлено | case 'member.quota': return d.dailyRequests == null ? 'снял(а) лимит запросов' : `установил(а) лимит ${d.dailyRequests} запросов/день`; |
| +добавлено | case 'api_key.create': return `добавил(а) ключ ${q(d.label || d.provider)}`; |
| +добавлено | case 'api_key.update': return `изменил(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.delete': return `удалил(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.disable': return `отключил(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.enable': return `включил(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.reveal': return `просмотрел(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.ping': return `проверил(а) ключ ${q(d.label)}`; |
| +добавлено | case 'api_key.check_all': return 'проверил(а) все ключи'; |
| +добавлено | case 'file.upload': return `отправил(а) файл ${q(d.name)}`; |
| +добавлено | case 'file.delete': return `удалил(а) файл ${q(d.name)}`; |
| +добавлено | case 'archive.upload': return `загрузил(а) архив ${q(d.projectName || d.name)}`; |
| +добавлено | case 'archive.delete': return 'удалил(а) архив'; |
| +добавлено | case 'project.create': return `создал(а) проект ${q(d.name)}`; |
| +добавлено | case 'proxy_token.create': return 'выпустил(а) токен доступа'; |
| +добавлено | case 'proxy_token.revoke': return 'отозвал(а) токен доступа'; |
| +добавлено | case 'activity.delete': return 'удалил(а) событие ленты'; |
| +добавлено | default: return a.action; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import{options as n}from"preact";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,p=c.__;function s(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,y(D,n)}function y(n,u,i){var o=s(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=!1,i=o.__c.props!==n;if(o.__c.__H.__.some(function(n){if(n.__N){u=!0;var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c){var f=c.call(this,n,t,r);return u?f||i:f}return!u||i};r.__f=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function h(n,u){var i=s(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=s(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=s(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=s(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=s(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function g(){var n=s(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function j(){for(var n;n=f.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(z),t.__h.some(B),t.__h=[]}catch(r){t.__h=[],c.__e(r,n.__v)}}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.some(z),i.__h.some(B),i.__h=[],t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.some(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.some(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return"function"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,h as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,y as useReducer,A as useRef,d as useState}; |
| +добавлено |
| +добавлено | var n=function(t,s,r,e){var u;s[0]=0;for(var h=1;h<s.length;h++){var p=s[h++],a=s[h]?(s[0]|=p?1:2,r[s[h++]]):s[++h];3===p?e[0]=a:4===p?e[1]=Object.assign(e[1]||{},a):5===p?(e[1]=e[1]||{})[s[++h]]=a:6===p?e[1][s[++h]]+=a+"":p?(u=t.apply(a,n(t,a,r,["",null])),e.push(u),a[0]?s[0]|=2:(s[h-2]=0,s[h]=u)):e.push(a)}return e},t=new Map;export default function(s){var r=t.get(this);return r||(r=new Map,t.set(this,r)),(r=n(this,r.get(s)||(r.set(s,r=function(n){for(var t,s,r=1,e="",u="",h=[0],p=function(n){1===r&&(n||(e=e.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?h.push(0,n,e):3===r&&(n||e)?(h.push(3,n,e),r=2):2===r&&"..."===e&&n?h.push(4,n,0):2===r&&e&&!n?h.push(5,0,!0,e):r>=5&&((e||!n&&5===r)&&(h.push(r,0,e,s),r=6),n&&(h.push(r,n,0,s),r=6)),e=""},a=0;a<n.length;a++){a&&(1===r&&p(),p(a));for(var l=0;l<n[a].length;l++)t=n[a][l],1===r?"<"===t?(p(),h=[h],r=3):e+=t:4===r?"--"===e&&">"===t?(r=1,e=""):e=t+e[0]:u?t===u?u="":e+=t:'"'===t||"'"===t?u=t:">"===t?(p(),r=1):r&&("="===t?(r=5,s=e,e=""):"/"===t&&(r<5||">"===n[a][l+1])?(p(),3===r&&(h=h[0]),r=h,(h=h[0]).push(2,0,r),r=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(p(),r=2):e+=t),3===r&&"!--"===e&&(r=4,h=h[0])}return p(),h}(s)),r),arguments,[])).length>1?r:r[0]} |
| +добавлено | // Набор иконок в стиле lucide (24×24, stroke 1.75). Только inline SVG — без сети. |
| +добавлено | import { h } from 'preact'; |
| +добавлено | |
| +добавлено | const FILE = '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>'; |
| +добавлено | |
| +добавлено | const P = { |
| +добавлено | users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>', |
| +добавлено | 'user-plus': '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M19 8v6"/><path d="M22 11h-6"/>', |
| +добавлено | kanban: '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M8 7v7"/><path d="M12 7v4"/><path d="M16 7v9"/>', |
| +добавлено | key: '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>', |
| +добавлено | file: FILE, |
| +добавлено | 'file-text': FILE + '<path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>', |
| +добавлено | 'file-code': FILE + '<path d="m10 13-2 2 2 2"/><path d="m14 17 2-2-2-2"/>', |
| +добавлено | 'file-image': FILE + '<circle cx="10" cy="12" r="2"/><path d="m20 17-1.3-1.3a2.4 2.4 0 0 0-3.4 0L9 22"/>', |
| +добавлено | 'file-archive': FILE + '<path d="M10 11v1"/><path d="M10 14v1"/><rect x="8.5" y="16.5" width="3" height="3" rx=".8"/>', |
| +добавлено | 'git-branch': '<path d="M6 3v12"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/>', |
| +добавлено | 'git-commit': '<circle cx="12" cy="12" r="3"/><path d="M3 12h6"/><path d="M15 12h6"/>', |
| +добавлено | 'git-merge': '<circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M6 21V9a9 9 0 0 0 9 9"/>', |
| +добавлено | user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>', |
| +добавлено | plus: '<path d="M5 12h14"/><path d="M12 5v14"/>', |
| +добавлено | minus: '<path d="M5 12h14"/>', |
| +добавлено | search: '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>', |
| +добавлено | x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>', |
| +добавлено | chevron: '<path d="m6 9 6 6 6-6"/>', |
| +добавлено | 'chevron-right': '<path d="m9 18 6-6-6-6"/>', |
| +добавлено | 'chevron-up': '<path d="m18 15-6-6-6 6"/>', |
| +добавлено | 'chevrons-up-down': '<path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/>', |
| +добавлено | check: '<path d="M20 6 9 17l-5-5"/>', |
| +добавлено | copy: '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>', |
| +добавлено | trash: '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>', |
| +добавлено | upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m17 8-5-5-5 5"/><path d="M12 3v12"/>', |
| +добавлено | download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>', |
| +добавлено | refresh: '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>', |
| +добавлено | 'log-out': '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5"/><path d="M21 12H9"/>', |
| +добавлено | 'log-in': '<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><path d="m10 17 5-5-5-5"/><path d="M15 12H3"/>', |
| +добавлено | link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>', |
| +добавлено | shield: '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>', |
| +добавлено | crown: '<path d="M11.56 3.27a.5.5 0 0 1 .88 0l2.95 5.6a1 1 0 0 0 1.52.29l4.27-3.66a.5.5 0 0 1 .82.5l-2.83 10.25a1 1 0 0 1-.97.75H5.81a1 1 0 0 1-.97-.75L2.01 6a.5.5 0 0 1 .82-.5L7.1 9.16a1 1 0 0 0 1.52-.29z"/><path d="M5 21h14"/>', |
| +добавлено | eye: '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>', |
| +добавлено | 'eye-off': '<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.4 10.4 0 0 1 12 5c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.39-1.61"/><path d="m2 2 20 20"/>', |
| +добавлено | more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>', |
| +добавлено | 'arrow-up': '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>', |
| +добавлено | 'arrow-down': '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>', |
| +добавлено | 'arrow-right': '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>', |
| +добавлено | 'arrow-down-line': '<path d="M12 17V3"/><path d="m6 11 6 6 6-6"/><path d="M19 21H5"/>', |
| +добавлено | 'arrow-up-line': '<path d="m18 9-6-6-6 6"/><path d="M12 3v14"/><path d="M5 21h14"/>', |
| +добавлено | clock: '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>', |
| +добавлено | calendar: '<rect width="18" height="18" x="3" y="4" rx="2"/><path d="M16 2v4"/><path d="M8 2v4"/><path d="M3 10h18"/>', |
| +добавлено | flag: '<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><path d="M4 22v-7"/>', |
| +добавлено | tag: '<path d="M12.59 2.59A2 2 0 0 0 11.17 2H4a2 2 0 0 0-2 2v7.17a2 2 0 0 0 .59 1.42l8.7 8.7a2.43 2.43 0 0 0 3.42 0l6.58-6.58a2.43 2.43 0 0 0 0-3.42z"/><circle cx="7.5" cy="7.5" r=".6" fill="currentColor"/>', |
| +добавлено | send: '<path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>', |
| +добавлено | folder: '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>', |
| +добавлено | history: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>', |
| +добавлено | undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>', |
| +добавлено | restore: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>', |
| +добавлено | pencil: '<path d="M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5z"/><path d="m15 5 4 4"/>', |
| +добавлено | archive: '<rect width="20" height="5" x="2" y="3" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>', |
| +добавлено | activity: '<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>', |
| +добавлено | alert: '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>', |
| +добавлено | globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>', |
| +добавлено | server: '<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01"/><path d="M6 18h.01"/>', |
| +добавлено | zap: '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>', |
| +добавлено | power: '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>', |
| +добавлено | chart: '<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/>', |
| +добавлено | plug: '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>', |
| +добавлено | share: '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><path d="m16 6-4-4-4 4"/><path d="M12 2v13"/>', |
| +добавлено | mail: '<rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>', |
| +добавлено | lock: '<rect width="18" height="11" x="3" y="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>', |
| +добавлено | inbox: '<path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>', |
| +добавлено | external: '<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>', |
| +добавлено | filter: '<path d="M22 3H2l8 9.46V19l4 2v-8.54z"/>', |
| +добавлено | terminal: '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>', |
| +добавлено | hash: '<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>', |
| +добавлено | monitor: '<rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/>', |
| +добавлено | puzzle: '<path d="M15.39 4.39a1 1 0 0 0 1.68-.47 2.5 2.5 0 1 1 3.01 3.01 1 1 0 0 0-.47 1.68l1.68 1.68a2.41 2.41 0 0 1 0 3.42l-1.61 1.61a1 1 0 0 1-1.6-.34 2.5 2.5 0 1 0-3.21 3.21 1 1 0 0 1 .34 1.6l-1.61 1.61a2.41 2.41 0 0 1-3.42 0l-1.68-1.68a1 1 0 0 0-1.68.47 2.5 2.5 0 1 1-3.01-3.01 1 1 0 0 0 .47-1.68l-1.68-1.68a2.41 2.41 0 0 1 0-3.42l1.61-1.61a1 1 0 0 1 1.6.34 2.5 2.5 0 1 0 3.21-3.21 1 1 0 0 1-.34-1.6l1.61-1.61a2.41 2.41 0 0 1 3.42 0z"/>', |
| +добавлено | grip: '<circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/>', |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export function Icon({ name, size = 16, stroke = 1.75, class: cls = '', title }) { |
| +добавлено | const body = P[name] ?? P.file; |
| +добавлено | return h('svg', { |
| +добавлено | class: 'ic ' + cls, |
| +добавлено | width: size, |
| +добавлено | height: size, |
| +добавлено | viewBox: '0 0 24 24', |
| +добавлено | fill: 'none', |
| +добавлено | stroke: 'currentColor', |
| +добавлено | 'stroke-width': stroke, |
| +добавлено | 'stroke-linecap': 'round', |
| +добавлено | 'stroke-linejoin': 'round', |
| +добавлено | 'aria-hidden': title ? undefined : 'true', |
| +добавлено | role: title ? 'img' : undefined, |
| +добавлено | dangerouslySetInnerHTML: { __html: (title ? `<title>${title}</title>` : '') + body }, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function fileIconFor(name = '') { |
| +добавлено | const ext = String(name).toLowerCase().split('.').pop(); |
| +добавлено | if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif'].includes(ext)) return 'file-image'; |
| +добавлено | if (['zip', 'rar', '7z', 'gz', 'tgz', 'tar', 'bz2', 'xz'].includes(ext)) return 'file-archive'; |
| +добавлено | if (['js', 'mjs', 'ts', 'tsx', 'jsx', 'json', 'py', 'rs', 'go', 'java', 'cs', 'cpp', 'c', 'h', 'css', 'html', 'sh', 'ps1', 'yml', 'yaml', 'toml', 'sql'].includes(ext)) return 'file-code'; |
| +добавлено | if (['md', 'txt', 'pdf', 'doc', 'docx', 'rtf', 'csv', 'log', 'xlsx', 'pptx'].includes(ext)) return 'file-text'; |
| +добавлено | return 'file'; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function BrandMark({ size = 40 }) { |
| +добавлено | return h('svg', { |
| +добавлено | class: 'brand-mark', |
| +добавлено | width: size, |
| +добавлено | height: size, |
| +добавлено | viewBox: '0 0 40 40', |
| +добавлено | 'aria-hidden': 'true', |
| +добавлено | dangerouslySetInnerHTML: { |
| +добавлено | __html: |
| +добавлено | '<defs><radialGradient id="bm-g" cx="50%" cy="38%" r="70%"><stop offset="0" stop-color="#38bdf8" stop-opacity=".95"/><stop offset=".55" stop-color="#0ea5e9" stop-opacity=".35"/><stop offset="1" stop-color="#0ea5e9" stop-opacity="0"/></radialGradient></defs>' + |
| +добавлено | '<rect x="0.5" y="0.5" width="39" height="39" rx="11" fill="var(--zt-card)" stroke="var(--zt-border)"/>' + |
| +добавлено | '<circle cx="20" cy="20" r="13" fill="url(#bm-g)"/>' + |
| +добавлено | '<circle cx="20" cy="20" r="8.5" fill="none" stroke="var(--zt-fg)" stroke-width="1.75" stroke-opacity=".9"/>' + |
| +добавлено | '<circle cx="15.5" cy="22" r="2.6" fill="var(--zt-fg)"/><circle cx="24.5" cy="22" r="2.6" fill="var(--zt-fg)"/><circle cx="20" cy="14.6" r="2.6" fill="var(--zt-fg)"/>', |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | // Оболочка: шапка, вкладки, лента, экраны входа и онбординга. |
| +добавлено | import { render, Fragment } from 'preact'; |
| +добавлено | import { useEffect, useLayoutEffect, useRef, useState, useMemo } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, useStore, useRes, toast, humanError, saveSettings, saveUi, svc, loadState, |
| +добавлено | relTime, describeAction, useTick, ROLE_RU, initials, rpcLog, plural, invalidate, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon, BrandMark } from './icons.js'; |
| +добавлено | import { |
| +добавлено | Avatar, AvatarStack, Seg, Popover, Layer, ConfirmHost, ToastHost, Launcher, Empty, AsyncButton, Field, |
| +добавлено | RoleBadge, closeTopLayer, Skel, Spinner, |
| +добавлено | } from './ui.js'; |
| +добавлено | import { |
| +добавлено | app, boot, currentTeam, myRole, me, keyFor, selectTeam, afterSignIn, signOut, connectEvents, installParentBridge, |
| +добавлено | postPending, postClose, reloadAll, refreshSession, |
| +добавлено | } from './app-state.js'; |
| +добавлено | import { TasksTab } from './tab-tasks.js'; |
| +добавлено | import { TeamTab } from './tab-team.js'; |
| +добавлено | import { KeysTab } from './tab-keys.js'; |
| +добавлено | import { FilesTab } from './tab-files.js'; |
| +добавлено | import { GitTab } from './tab-git.js'; |
| +добавлено | import { ProfileTab } from './tab-profile.js'; |
| +добавлено | |
| +добавлено | window.__zteam = { rpcLog, app }; |
| +добавлено | |
| +добавлено | const TABS = [ |
| +добавлено | { id: 'tasks', label: 'Задачи', icon: 'kanban', team: true }, |
| +добавлено | { id: 'team', label: 'Команда', icon: 'users', team: true }, |
| +добавлено | { id: 'keys', label: 'Ключи', icon: 'key', team: true }, |
| +добавлено | { id: 'files', label: 'Файлы', icon: 'file', team: true }, |
| +добавлено | { id: 'git', label: 'Git', icon: 'git-branch', team: false }, |
| +добавлено | { id: 'profile', label: 'Профиль', icon: 'user', team: false }, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- создание / вступление |
| +добавлено | |
| +добавлено | function CreateTeamSheet({ open, onClose }) { |
| +добавлено | const [name, setName] = useState(''); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | useEffect(() => { if (open) { setName(''); setErr(''); } }, [open]); |
| +добавлено | const submit = async (e) => { |
| +добавлено | e?.preventDefault?.(); |
| +добавлено | if (!name.trim()) { setErr('Введите название'); return; } |
| +добавлено | try { |
| +добавлено | const r = await rpc('createTeam', { name: name.trim() }); |
| +добавлено | const s = await refreshSession(); |
| +добавлено | const created = r?.id ?? r?.team?.id ?? s?.teams?.find((t) => t.name === name.trim())?.id; |
| +добавлено | if (created) await selectTeam(created); |
| +добавлено | toast(`Команда «${name.trim()}» создана`, { kind: 'ok' }); |
| +добавлено | onClose(); |
| +добавлено | } catch (ex) { setErr(humanError(ex)); } |
| +добавлено | }; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title="Новая команда" initialFocus="input"> |
| +добавлено | <form class="stack" onSubmit=${submit}> |
| +добавлено | <${Field} label="Название" hint="Его увидят все участники. Можно поменять позже."> |
| +добавлено | <input class=${'inp' + (err ? ' err' : '')} value=${name} maxlength="60" placeholder="Например, «Frontend»" onInput=${(e) => { setName(e.currentTarget.value); setErr(''); }} /> |
| +добавлено | <//> |
| +добавлено | ${err ? html`<div class="err-box"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | <div class="row" style="justify-content:flex-end"> |
| +добавлено | <button type="button" class="btn" onClick=${onClose}>Отмена</button> |
| +добавлено | <${AsyncButton} type="submit" class="btn primary" onClick=${submit}>Создать команду<//> |
| +добавлено | </div> |
| +добавлено | </form> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function JoinTeamSheet({ open, onClose }) { |
| +добавлено | const [code, setCode] = useState(''); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | useEffect(() => { if (open) { setCode(''); setErr(''); } }, [open]); |
| +добавлено | const submit = async (e) => { |
| +добавлено | e?.preventDefault?.(); |
| +добавлено | if (!code.trim()) { setErr('Введите код приглашения'); return; } |
| +добавлено | try { |
| +добавлено | const r = await rpc('joinTeam', { code: code.trim() }); |
| +добавлено | const s = await refreshSession(); |
| +добавлено | const id = r?.teamId ?? r?.team?.id; |
| +добавлено | const target = id ?? (s?.teams?.length ? s.teams[s.teams.length - 1].id : null); |
| +добавлено | if (target) await selectTeam(target); |
| +добавлено | toast('Вы вступили в команду', { kind: 'ok' }); |
| +добавлено | onClose(); |
| +добавлено | } catch (ex) { setErr(humanError(ex)); } |
| +добавлено | }; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title="Вступить по коду" initialFocus="input"> |
| +добавлено | <form class="stack" onSubmit=${submit}> |
| +добавлено | <${Field} label="Код приглашения" hint="Код выдаёт владелец или мейнтейнер команды."> |
| +добавлено | <input class=${'inp mono' + (err ? ' err' : '')} value=${code} placeholder="XXXX-XXXX" autocomplete="off" spellcheck="false" |
| +добавлено | onInput=${(e) => { setCode(e.currentTarget.value); setErr(''); }} style="letter-spacing:.08em" /> |
| +добавлено | <//> |
| +добавлено | ${err ? html`<div class="err-box"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | <div class="row" style="justify-content:flex-end"> |
| +добавлено | <button type="button" class="btn" onClick=${onClose}>Отмена</button> |
| +добавлено | <${AsyncButton} type="submit" class="btn primary" onClick=${submit}>Вступить<//> |
| +добавлено | </div> |
| +добавлено | </form> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const teamSheets = { open: null }; |
| +добавлено | let setSheetGlobal = () => {}; |
| +добавлено | export function openTeamSheet(kind) { setSheetGlobal(kind); } |
| +добавлено | |
| +добавлено | function TeamSheets() { |
| +добавлено | const [sheet, setSheet] = useState(null); |
| +добавлено | setSheetGlobal = setSheet; |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <${CreateTeamSheet} open=${sheet === 'create'} onClose=${() => setSheet(null)} /> |
| +добавлено | <${JoinTeamSheet} open=${sheet === 'join'} onClose=${() => setSheet(null)} /> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- шапка |
| +добавлено | |
| +добавлено | function TeamTile({ name, lg }) { |
| +добавлено | return html`<span class=${'team-tile' + (lg ? ' lg' : '')}>${initials(name || '?')}</span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function TeamSwitcher({ s }) { |
| +добавлено | const [open, setOpen] = useState(false); |
| +добавлено | const ref = useRef(null); |
| +добавлено | const team = currentTeam(s); |
| +добавлено | const teams = s.session?.teams ?? []; |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <button type="button" class="team-sw" ref=${ref} aria-haspopup="menu" aria-expanded=${String(open)} onClick=${() => setOpen((o) => !o)} |
| +добавлено | title=${team ? team.name : 'Выбрать команду'}> |
| +добавлено | ${team ? html`<${TeamTile} name=${team.name} />` : html`<span class="team-tile" style="background:var(--zt-tag)"><${Icon} name="users" size=${13} /></span>`} |
| +добавлено | <span class="name">${team ? team.name : 'Aura Team'}</span> |
| +добавлено | <${Icon} name="chevrons-up-down" size=${14} /> |
| +добавлено | </button> |
| +добавлено | ${open ? html`<${Popover} anchor=${ref.current} onClose=${() => setOpen(false)} width=${260}> |
| +добавлено | <div class="lbl">Мои команды</div> |
| +добавлено | ${teams.length ? teams.map((t) => html`<button type="button" class="mi" role="menuitem" key=${t.id} |
| +добавлено | onClick=${() => { setOpen(false); selectTeam(t.id); }}> |
| +добавлено | <${TeamTile} name=${t.name} /> |
| +добавлено | <span class="grow ell">${t.name}</span> |
| +добавлено | <span class="faint xs">${ROLE_RU[t.role] || t.role}</span> |
| +добавлено | ${t.id === s.teamId ? html`<${Icon} name="check" class="chk-ic" />` : html`<span style="width:16px"></span>`} |
| +добавлено | </button>`) : html`<div class="mi faint" style="cursor:default">Команд пока нет</div>`} |
| +добавлено | <div class="sep"></div> |
| +добавлено | <button type="button" class="mi" role="menuitem" onClick=${() => { setOpen(false); openTeamSheet('create'); }}><${Icon} name="plus" />Создать команду</button> |
| +добавлено | <button type="button" class="mi" role="menuitem" onClick=${() => { setOpen(false); openTeamSheet('join'); }}><${Icon} name="link" />Вступить по коду</button> |
| +добавлено | <//>` : null} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function Header({ s, onlineMembers }) { |
| +добавлено | const [spin, setSpin] = useState(false); |
| +добавлено | return html`<header class="hdr"> |
| +добавлено | ${s.phase === 'ready' ? html`<${TeamSwitcher} s=${s} />` : html`<div class="row" style="padding-left:6px"><span class="b" style="font-size:13.5px">Aura Team</span></div>`} |
| +добавлено | <span class=${'live-dot' + (s.live ? ' on' : '')} title=${s.live ? 'Онлайн: обновления приходят в реальном времени' : 'Нет живого соединения — переподключаюсь'}></span> |
| +добавлено | <span class="grow"></span> |
| +добавлено | ${onlineMembers?.length ? html`<${AvatarStack} members=${onlineMembers} />` : null} |
| +добавлено | ${s.phase === 'ready' ? html`<button type="button" class="ibtn" title="Обновить" aria-label="Обновить" |
| +добавлено | onClick=${() => { setSpin(true); reloadAll(); setTimeout(() => setSpin(false), 600); }}> |
| +добавлено | <span style=${{ display: 'grid', transition: 'transform .6s cubic-bezier(.22,1,.36,1)', transform: spin ? 'rotate(360deg)' : 'none' }}><${Icon} name="refresh" /></span> |
| +добавлено | </button>` : null} |
| +добавлено | <button type="button" class="ibtn" title="Закрыть панель" aria-label="Закрыть панель" onClick=${postClose}><${Icon} name="x" /></button> |
| +добавлено | </header>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вкладки |
| +добавлено | |
| +добавлено | function Tabs({ tab, onTab, badges, narrow }) { |
| +добавлено | const ref = useRef(null); |
| +добавлено | const [ind, setInd] = useState(null); |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | const root = ref.current; |
| +добавлено | if (!root) return; |
| +добавлено | const measure = () => { |
| +добавлено | const btn = root.querySelector(`[data-tab="${tab}"]`); |
| +добавлено | if (!btn) return; |
| +добавлено | setInd({ x: btn.offsetLeft + 6, w: btn.offsetWidth - 12 }); |
| +добавлено | btn.scrollIntoView?.({ block: 'nearest', inline: 'nearest' }); |
| +добавлено | }; |
| +добавлено | measure(); |
| +добавлено | const ro = new ResizeObserver(measure); |
| +добавлено | ro.observe(root); |
| +добавлено | return () => ro.disconnect(); |
| +добавлено | }, [tab, narrow, badges.tasks, badges.files]); |
| +добавлено | const onKey = (e) => { |
| +добавлено | const i = TABS.findIndex((t) => t.id === tab); |
| +добавлено | if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { |
| +добавлено | e.preventDefault(); |
| +добавлено | const n = TABS[(i + (e.key === 'ArrowRight' ? 1 : -1) + TABS.length) % TABS.length]; |
| +добавлено | onTab(n.id); |
| +добавлено | requestAnimationFrame(() => ref.current?.querySelector(`[data-tab="${n.id}"]`)?.focus()); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | return html`<nav class="tabs" role="tablist" ref=${ref} onKeyDown=${onKey}> |
| +добавлено | ${TABS.map((t) => html`<button type="button" role="tab" class="tab" key=${t.id} data-tab=${t.id} aria-selected=${String(t.id === tab)} |
| +добавлено | tabindex=${t.id === tab ? '0' : '-1'} title=${t.label} onClick=${() => onTab(t.id)}> |
| +добавлено | <${Icon} name=${t.icon} /> |
| +добавлено | <span class="lbl">${t.label}</span> |
| +добавлено | ${badges[t.id] ? html`<span class=${'badge' + (t.id === 'files' ? ' brand' : '')}>${badges[t.id]}</span>` : null} |
| +добавлено | </button>`)} |
| +добавлено | ${ind ? html`<span class="tab-ind" style=${{ transform: `translateX(${ind.x}px) scaleX(${ind.w / 100})` }}></span>` : null} |
| +добавлено | </nav>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- лента |
| +добавлено | |
| +добавлено | function Feed({ s }) { |
| +добавлено | const ui = svc.state?.ui || {}; |
| +добавлено | const [open, setOpen] = useState(!!ui.feedOpen); |
| +добавлено | const [seenAt, setSeenAt] = useState(ui.feedSeenAt || 0); |
| +добавлено | const seenIds = useRef(null); |
| +добавлено | useTick(30000); |
| +добавлено | const { data } = useRes(s.teamId ? keyFor.activity(s.teamId) : null, () => rpc('activity', { teamId: s.teamId, limit: 40 })); |
| +добавлено | const list = data ?? []; |
| +добавлено | const unread = list.filter((a) => new Date(a.createdAt).getTime() > seenAt).length; |
| +добавлено | const last = list[0]; |
| +добавлено | useEffect(() => { |
| +добавлено | if (open && list.length) { |
| +добавлено | const t = new Date(list[0].createdAt).getTime(); |
| +добавлено | if (t > seenAt) { setSeenAt(t); saveUi({ feedSeenAt: t }); } |
| +добавлено | } |
| +добавлено | }, [open, list[0]?.id]); |
| +добавлено | const isNew = (a) => { |
| +добавлено | if (!seenIds.current) return false; |
| +добавлено | return !seenIds.current.has(a.id); |
| +добавлено | }; |
| +добавлено | useEffect(() => { seenIds.current = new Set(list.map((a) => a.id)); }); |
| +добавлено | const toggle = () => { setOpen((o) => { saveUi({ feedOpen: !o }); return !o; }); }; |
| +добавлено | const del = async (a) => { const [, e] = await act('deleteActivity', { teamId: s.teamId, eventId: a.id }); if (!e) invalidate('activity'); }; |
| +добавлено | const canDel = ['owner', 'maintainer'].includes(myRole(s)); |
| +добавлено | return html`<section class=${'feed' + (open ? ' open' : '')} aria-label="Лента активности"> |
| +добавлено | <button type="button" class="feed-peek" aria-expanded=${String(open)} onClick=${toggle}> |
| +добавлено | <${Icon} name="activity" size=${14} /> |
| +добавлено | <span class="b" style="color:var(--zt-fg)">Лента</span> |
| +добавлено | ${unread && !open ? html`<span class="badge brand">${unread > 99 ? '99+' : unread}</span>` : null} |
| +добавлено | <span class="grow ell">${last ? html`<span>${last.userName}</span> <span class="faint">${describeAction(last)} · ${relTime(last.createdAt)}</span>` : html`<span class="faint">Событий пока нет</span>`}</span> |
| +добавлено | <${Icon} name="chevron-up" size=${14} class="chev" /> |
| +добавлено | </button> |
| +добавлено | <div class="feed-body" aria-hidden=${String(!open)}> |
| +добавлено | ${open ? list.map((a) => html`<div class=${'feed-item' + (isNew(a) ? ' new' : '')} key=${a.id}> |
| +добавлено | <${Avatar} name=${a.userName} id=${a.userId} size=${20} /> |
| +добавлено | <div class="txt"><b>${a.userName}</b> <span class="muted">${describeAction(a)}</span></div> |
| +добавлено | <span class="tm" title=${new Date(a.createdAt).toLocaleString('ru-RU')}>${relTime(a.createdAt)}</span> |
| +добавлено | ${canDel ? html`<button type="button" class="ibtn sm" title="Удалить событие" aria-label="Удалить событие" onClick=${() => del(a)}><${Icon} name="x" size=${12} /></button>` : null} |
| +добавлено | </div>`) : null} |
| +добавлено | ${open && !list.length ? html`<div class="feed-item faint">Здесь появятся действия участников.</div>` : null} |
| +добавлено | </div> |
| +добавлено | </section>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вход |
| +добавлено | |
| +добавлено | function AuthScreen({ s }) { |
| +добавлено | const [mode, setMode] = useState('login'); |
| +добавлено | const [email, setEmail] = useState(''); |
| +добавлено | const [password, setPassword] = useState(''); |
| +добавлено | const [name, setName] = useState(''); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | const [busy, setBusy] = useState(false); |
| +добавлено | const [device, setDevice] = useState(null); |
| +добавлено | const [srvOpen, setSrvOpen] = useState(false); |
| +добавлено | const [server, setServer] = useState(s.state?.serverUrl || 'https://team-server.invalid'); |
| +добавлено | const pollRef = useRef(0); |
| +добавлено | |
| +добавлено | useEffect(() => () => clearTimeout(pollRef.current), []); |
| +добавлено | |
| +добавлено | const submit = async (e) => { |
| +добавлено | e.preventDefault(); |
| +добавлено | setErr(''); |
| +добавлено | if (!email.trim() || !password) { setErr('Введите email и пароль'); return; } |
| +добавлено | if (mode === 'register' && password.length < 8) { setErr('Пароль — минимум 8 символов'); return; } |
| +добавлено | setBusy(true); |
| +добавлено | try { |
| +добавлено | if (mode === 'register') await rpc('register', { email: email.trim(), password, displayName: name.trim() || email.split('@')[0] }); |
| +добавлено | await rpc('login', { email: email.trim(), password }); |
| +добавлено | await afterSignIn(); |
| +добавлено | } catch (ex) { |
| +добавлено | setErr(humanError(ex)); |
| +добавлено | } finally { setBusy(false); } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const startDevice = async () => { |
| +добавлено | setErr(''); |
| +добавлено | try { |
| +добавлено | const d = await rpc('deviceStart'); |
| +добавлено | const startedAt = Date.now(); |
| +добавлено | setDevice({ ...d, until: Date.now() + (d.expiresIn || 600) * 1000 }); |
| +добавлено | const tick = async () => { |
| +добавлено | try { |
| +добавлено | const r = await rpc('devicePoll', { deviceCode: d.deviceCode }); |
| +добавлено | if (r?.ok) { setDevice(null); await afterSignIn(); return; } |
| +добавлено | } catch (ex) { |
| +добавлено | if (ex.status && ex.status !== 428 && ex.status !== 400) { setDevice(null); setErr(humanError(ex)); return; } |
| +добавлено | } |
| +добавлено | if (Date.now() - startedAt > (d.expiresIn || 600) * 1000) { setDevice(null); setErr('Код истёк — начните заново'); return; } |
| +добавлено | pollRef.current = setTimeout(tick, Math.max(2, d.interval || 5) * 1000); |
| +добавлено | }; |
| +добавлено | pollRef.current = setTimeout(tick, Math.max(2, d.interval || 5) * 1000); |
| +добавлено | } catch (ex) { setErr(humanError(ex)); } |
| +добавлено | }; |
| +добавлено | const cancelDevice = () => { clearTimeout(pollRef.current); setDevice(null); }; |
| +добавлено | |
| +добавлено | const saveServer = async () => { |
| +добавлено | const url = server.trim(); |
| +добавлено | if (!/^https?:\/\/.+/i.test(url)) { setErr('Адрес сервера должен начинаться с http:// или https://'); return; } |
| +добавлено | await saveSettings({ serverUrl: url }); |
| +добавлено | toast('Сервер сохранён', { kind: 'ok' }); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | return html`<div class="center-wrap"> |
| +добавлено | <div class="auth"> |
| +добавлено | <div class="hero"> |
| +добавлено | <${BrandMark} size=${44} /> |
| +добавлено | <div><div class="h1">Aura Team</div><div class="muted small" style="margin-top:2px">Задачи, ключи, файлы и git вашей команды</div></div> |
| +добавлено | </div> |
| +добавлено | <div class="card"> |
| +добавлено | ${device ? html`<div class="stack reveal"> |
| +добавлено | <div class="b">Подтвердите вход в браузере</div> |
| +добавлено | <div class="muted small">Откройте страницу и введите этот код. Панель войдёт сама.</div> |
| +добавлено | <div class="device-code sel-text">${device.userCode}</div> |
| +добавлено | <div class="row"> |
| +добавлено | <a class="btn primary" href=${device.verificationUri} target="_blank" rel="noopener"><${Icon} name="external" size=${14} />Открыть страницу</a> |
| +добавлено | <button type="button" class="btn ghost" onClick=${() => navigator.clipboard?.writeText(device.userCode).then(() => toast('Код скопирован', { kind: 'ok' }))}><${Icon} name="copy" size=${14} />Код</button> |
| +добавлено | <span class="grow"></span> |
| +добавлено | </div> |
| +добавлено | <div class="row muted small"><${Spinner} size=${14} /> Ждём подтверждения…<span class="grow"></span><button type="button" class="linkbtn" onClick=${cancelDevice}>Отмена</button></div> |
| +добавлено | </div>` : html`<form class="stack" onSubmit=${submit} novalidate> |
| +добавлено | <${Seg} block value=${mode} onChange=${(m) => { setMode(m); setErr(''); }} label="Режим" |
| +добавлено | options=${[{ id: 'login', label: 'Вход' }, { id: 'register', label: 'Регистрация' }]} /> |
| +добавлено | ${mode === 'register' ? html`<${Field} label="Имя"><input class="inp" value=${name} autocomplete="name" placeholder="Как вас видят в команде" onInput=${(e) => setName(e.currentTarget.value)} /><//>` : null} |
| +добавлено | <${Field} label="Email"><input class="inp" type="email" value=${email} autocomplete="email" placeholder="you@example.com" onInput=${(e) => setEmail(e.currentTarget.value)} data-autofocus /><//> |
| +добавлено | <${Field} label="Пароль"><input class="inp" type="password" value=${password} autocomplete=${mode === 'login' ? 'current-password' : 'new-password'} placeholder=${mode === 'register' ? 'Минимум 8 символов' : '••••••••'} onInput=${(e) => setPassword(e.currentTarget.value)} /><//> |
| +добавлено | ${err ? html`<div class="err-box" role="alert"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | <button type="submit" class="btn primary lg block" disabled=${busy}>${busy ? html`<span class="spin"></span>` : null}${mode === 'login' ? 'Войти' : 'Создать аккаунт'}</button> |
| +добавлено | <div class="row faint xs" style="justify-content:center;gap:10px"><span style="height:1px;flex:1;background:var(--zt-border)"></span>или<span style="height:1px;flex:1;background:var(--zt-border)"></span></div> |
| +добавлено | <button type="button" class="btn lg block" onClick=${startDevice}><${Icon} name="globe" size=${15} />Войти через браузер</button> |
| +добавлено | </form>`} |
| +добавлено | </div> |
| +добавлено | <div class="row faint xs" style="justify-content:center;gap:5px"><${Icon} name="shield" size=${12} />Тот же аккаунт, что в Aura IDE</div> |
| +добавлено | <div class="stack-s" style="align-items:center"> |
| +добавлено | <button type="button" class="collapse-btn" aria-expanded=${String(srvOpen)} onClick=${() => setSrvOpen((o) => !o)}><${Icon} name="server" size=${13} />Сервер<${Icon} name="chevron" size=${13} /></button> |
| +добавлено | ${srvOpen ? html`<div class="row reveal" style="width:100%"> |
| +добавлено | <input class="inp sm mono" value=${server} onInput=${(e) => setServer(e.currentTarget.value)} aria-label="Адрес сервера" /> |
| +добавлено | <button type="button" class="btn sq" onClick=${saveServer}>Сохранить</button> |
| +добавлено | </div>` : null} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- онбординг |
| +добавлено | |
| +добавлено | function Onboarding({ s, compact }) { |
| +добавлено | const teams = s.session?.teams ?? []; |
| +добавлено | const user = me(s); |
| +добавлено | return html`<div class="pad stack" style="max-width:620px;margin:0 auto;padding-top:20px"> |
| +добавлено | <div> |
| +добавлено | <div class="h1">${compact ? 'Нужна команда' : `Здравствуйте${user?.displayName ? ', ' + user.displayName : ''}`}</div> |
| +добавлено | <div class="muted" style="margin-top:4px">${compact ? 'Этот раздел работает внутри команды. Выберите её или создайте новую.' : 'Выберите команду или создайте новую — задачи, ключи и файлы живут внутри неё.'}</div> |
| +добавлено | </div> |
| +добавлено | <div class="stack-s"> |
| +добавлено | <${Launcher} icon="plus" title="Создать команду" text="Вы станете владельцем и сможете пригласить коллег" pill="Создать" onClick=${() => openTeamSheet('create')} /> |
| +добавлено | <${Launcher} icon="link" title="Вступить по коду приглашения" text="Код выдаёт владелец или мейнтейнер" pill="Ввести код" onClick=${() => openTeamSheet('join')} /> |
| +добавлено | </div> |
| +добавлено | ${teams.length ? html`<div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="users" size=${14} />Мои команды</div> |
| +добавлено | <div class="card list"> |
| +добавлено | ${teams.map((t, i) => html`<div class="li click enter-item" key=${t.id} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }} role="button" tabindex="0" |
| +добавлено | onClick=${() => selectTeam(t.id)} onKeyDown=${(e) => e.key === 'Enter' && selectTeam(t.id)}> |
| +добавлено | <${TeamTile} name=${t.name} lg /> |
| +добавлено | <div class="grow"><div class="b ell">${t.name}</div><div class="muted xs">${t.memberCount ?? '?'} ${plural(t.memberCount ?? 0, 'участник', 'участника', 'участников')}</div></div> |
| +добавлено | <${RoleBadge} role=${t.role} /> |
| +добавлено | <span class="pill" style="height:26px;padding:0 12px;color:var(--zt-fg)">Открыть</span> |
| +добавлено | </div>`)} |
| +добавлено | </div> |
| +добавлено | </div>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- основное |
| +добавлено | |
| +добавлено | function useWidth(ref) { |
| +добавлено | const [w, setW] = useState(window.innerWidth); |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | const ro = new ResizeObserver(([e]) => setW(e.contentRect.width)); |
| +добавлено | if (ref.current) ro.observe(ref.current); |
| +добавлено | return () => ro.disconnect(); |
| +добавлено | }, []); |
| +добавлено | return w; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function Ready({ s }) { |
| +добавлено | const ui = svc.state?.ui || {}; |
| +добавлено | const [tab, setTab] = useState(TABS.some((t) => t.id === ui.tab) ? ui.tab : 'tasks'); |
| +добавлено | const [visited, setVisited] = useState(() => new Set([TABS.some((t) => t.id === ui.tab) ? ui.tab : 'tasks'])); |
| +добавлено | const [enterDir, setEnterDir] = useState(''); |
| +добавлено | const shell = useRef(null); |
| +добавлено | const width = useWidth(shell); |
| +добавлено | const narrow = width < 420; |
| +добавлено | const compactTabs = width < 560; |
| +добавлено | const user = me(s); |
| +добавлено | const board = useRes(s.teamId ? keyFor.board(s.teamId) : null, () => rpc('board', { teamId: s.teamId })); |
| +добавлено | const files = useRes(s.teamId ? keyFor.files(s.teamId) : null, () => rpc('files', { teamId: s.teamId })); |
| +добавлено | const [filesSeen, setFilesSeen] = useState(ui.filesSeenAt || 0); |
| +добавлено | |
| +добавлено | const myOpen = useMemo(() => { |
| +добавлено | if (!board.data || !user) return 0; |
| +добавлено | return board.data.tasks.filter((t) => t.assigneeId === user.id && t.status !== 'done').length; |
| +добавлено | }, [board.data, user?.id]); |
| +добавлено | useEffect(() => { if (board.data) postPending(myOpen); }, [myOpen, !!board.data]); |
| +добавлено | |
| +добавлено | const incoming = useMemo(() => (files.data ?? []).filter((f) => f.recipient?.id === user?.id && f.createdBy?.id !== user?.id && new Date(f.createdAt).getTime() > filesSeen).length, [files.data, filesSeen, user?.id]); |
| +добавлено | |
| +добавлено | useEffect(() => { |
| +добавлено | if (tab === 'files' && files.data?.length) { |
| +добавлено | const t = Math.max(...files.data.map((f) => new Date(f.createdAt).getTime())); |
| +добавлено | if (t > filesSeen) { setFilesSeen(t); saveUi({ filesSeenAt: t }); } |
| +добавлено | } |
| +добавлено | }, [tab, files.data]); |
| +добавлено | |
| +добавлено | const onTab = (id) => { |
| +добавлено | if (id === tab) return; |
| +добавлено | const a = TABS.findIndex((t) => t.id === tab); |
| +добавлено | const b = TABS.findIndex((t) => t.id === id); |
| +добавлено | setEnterDir(b > a ? 'enter' : 'enter-l'); |
| +добавлено | setTab(id); |
| +добавлено | setVisited((v) => (v.has(id) ? v : new Set([...v, id]))); |
| +добавлено | saveUi({ tab: id }); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const online = (board.data?.members ?? []).filter((m) => m.online && m.id !== user?.id); |
| +добавлено | const noTeam = !s.teamId; |
| +добавлено | |
| +добавлено | const renderTab = (id) => { |
| +добавлено | const def = TABS.find((t) => t.id === id); |
| +добавлено | if (def.team && noTeam) return html`<${Onboarding} s=${s} compact=${id !== 'tasks'} />`; |
| +добавлено | switch (id) { |
| +добавлено | case 'tasks': return html`<${TasksTab} s=${s} board=${board} narrow=${narrow} />`; |
| +добавлено | case 'team': return html`<${TeamTab} s=${s} board=${board} />`; |
| +добавлено | case 'keys': return html`<${KeysTab} s=${s} />`; |
| +добавлено | case 'files': return html`<${FilesTab} s=${s} files=${files} board=${board} active=${tab === 'files'} />`; |
| +добавлено | case 'git': return html`<${GitTab} s=${s} board=${board} />`; |
| +добавлено | case 'profile': return html`<${ProfileTab} s=${s} />`; |
| +добавлено | default: return null; |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | return html`<div class=${'shell' + (narrow ? ' narrow' : '') + (compactTabs ? ' compact-tabs' : '')} ref=${shell}> |
| +добавлено | <${Header} s=${s} onlineMembers=${online} /> |
| +добавлено | <${Tabs} tab=${tab} onTab=${onTab} narrow=${compactTabs} badges=${{ tasks: myOpen || 0, files: incoming || 0 }} /> |
| +добавлено | <main class="main"> |
| +добавлено | ${TABS.filter((t) => visited.has(t.id)).map((t) => html`<div key=${t.id} class=${'pane' + (t.id === tab ? ' ' + enterDir : '')} hidden=${t.id !== tab} |
| +добавлено | role="tabpanel" aria-label=${t.label} data-pane=${t.id}> |
| +добавлено | ${renderTab(t.id)} |
| +добавлено | </div>`)} |
| +добавлено | </main> |
| +добавлено | ${!noTeam ? html`<${Feed} s=${s} />` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function App() { |
| +добавлено | const s = useStore(app); |
| +добавлено | let body; |
| +добавлено | if (s.phase === 'loading') { |
| +добавлено | body = html`<div class="shell"><header class="hdr"><${Skel} w=${140} hgt=${20} /><span class="grow"></span><${Skel} w=${60} hgt=${20} /></header> |
| +добавлено | <div class="pad stack">${[0, 1, 2].map((i) => html`<${Skel} key=${i} hgt=${64} r=${12} />`)}</div></div>`; |
| +добавлено | } else if (s.phase === 'error') { |
| +добавлено | body = html`<div class="shell"><${Header} s=${s} /><div class="center-wrap"><${Empty} icon="alert" title="Сервис Aura Team недоступен" text=${s.error}> |
| +добавлено | <button type="button" class="btn primary" onClick=${() => { app.set((x) => ({ ...x, phase: 'loading' })); boot(); }}><${Icon} name="refresh" size=${14} />Повторить</button> |
| +добавлено | <//></div></div>`; |
| +добавлено | } else if (s.phase === 'auth') { |
| +добавлено | body = html`<div class="shell"><${Header} s=${s} /><div class="main"><div class="pane"><${AuthScreen} s=${s} /></div></div></div>`; |
| +добавлено | } else { |
| +добавлено | body = html`<${Ready} s=${s} key=${s.session?.user?.id || 'ready'} />`; |
| +добавлено | } |
| +добавлено | return html`<${Fragment}>${body}<${TeamSheets} /><${ConfirmHost} /><${ToastHost} /><//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- старт |
| +добавлено | |
| +добавлено | installParentBridge(); |
| +добавлено | document.addEventListener('keydown', (e) => { |
| +добавлено | if (e.key !== 'Escape' || e.defaultPrevented) return; |
| +добавлено | if (closeTopLayer()) { e.preventDefault(); return; } |
| +добавлено | const a = document.activeElement; |
| +добавлено | if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.tagName === 'SELECT') && a.value) { a.blur(); return; } |
| +добавлено | postClose(); |
| +добавлено | }); |
| +добавлено | // Файлы, брошенные мимо зоны, не должны открываться в iframe. |
| +добавлено | window.addEventListener('dragover', (e) => e.preventDefault()); |
| +добавлено | window.addEventListener('drop', (e) => e.preventDefault()); |
| +добавлено | |
| +добавлено | render(html`<${App} />`, document.getElementById('app')); |
| +добавлено | boot().then(() => connectEvents()); |
| +добавлено | /* Aura Team — панель ZCode. Токены совпадают с тёмной/светлой темой ZCode. */ |
| +добавлено | :root { |
| +добавлено | color-scheme: dark; |
| +добавлено | --zt-bg: #171717; |
| +добавлено | --zt-header: #171717; |
| +добавлено | --zt-card: #262626; |
| +добавлено | --zt-card-sel: #404040; |
| +добавлено | --zt-popover: #262626; |
| +добавлено | --zt-border: rgba(250, 250, 250, .10); |
| +добавлено | --zt-border-hover: rgba(250, 250, 250, .30); |
| +добавлено | --zt-surface: rgba(255, 255, 255, .05); |
| +добавлено | --zt-hover: rgba(255, 255, 255, .10); |
| +добавлено | --zt-selected: rgba(255, 255, 255, .10); |
| +добавлено | --zt-fg: #e5e5e5; |
| +добавлено | --zt-fg2: rgba(229, 229, 229, .60); |
| +добавлено | --zt-fg3: rgba(229, 229, 229, .30); |
| +добавлено | --zt-tag: #404040; |
| +добавлено | --zt-brand: #0ea5e9; |
| +добавлено | --zt-success: #22c55e; |
| +добавлено | --zt-danger: #ef4444; |
| +добавлено | --zt-warning: #eab308; |
| +добавлено | --zt-orange: #f97316; |
| +добавлено | --zt-primary: #fafafa; |
| +добавлено | --zt-primary-fg: #0a0a0a; |
| +добавлено | --zt-shadow: 0 10px 30px -8px rgba(0, 0, 0, .6), 0 2px 6px rgba(0, 0, 0, .35); |
| +добавлено | --zt-shadow-lift: 0 18px 40px -10px rgba(0, 0, 0, .75), 0 4px 12px rgba(0, 0, 0, .4); |
| +добавлено | --zt-backdrop: rgba(0, 0, 0, .45); |
| +добавлено | --zt-scroll: rgba(255, 255, 255, .14); |
| +добавлено | --zt-scroll-hover: rgba(255, 255, 255, .26); |
| +добавлено | --zt-diff-add: rgba(34, 197, 94, .13); |
| +добавлено | --zt-diff-add-fg: #86efac; |
| +добавлено | --zt-diff-del: rgba(239, 68, 68, .13); |
| +добавлено | --zt-diff-del-fg: #fca5a5; |
| +добавлено | --zt-diff-hunk: rgba(14, 165, 233, .10); |
| +добавлено | --zt-shimmer: rgba(255, 255, 255, .06); |
| +добавлено | --ease: cubic-bezier(.22, 1, .36, 1); |
| +добавлено | --font: ui-sans-serif, system-ui, "Segoe UI", sans-serif; |
| +добавлено | --mono: ui-monospace, "Cascadia Code", Consolas, monospace; |
| +добавлено | } |
| +добавлено | html.light { |
| +добавлено | color-scheme: light; |
| +добавлено | --zt-bg: #f8f8f8; |
| +добавлено | --zt-header: #f8f8f8; |
| +добавлено | --zt-card: #ffffff; |
| +добавлено | --zt-card-sel: #ececec; |
| +добавлено | --zt-popover: #ffffff; |
| +добавлено | --zt-border: rgba(13, 13, 13, .10); |
| +добавлено | --zt-border-hover: rgba(13, 13, 13, .24); |
| +добавлено | --zt-surface: rgba(13, 13, 13, .03); |
| +добавлено | --zt-hover: rgba(13, 13, 13, .05); |
| +добавлено | --zt-selected: rgba(13, 13, 13, .07); |
| +добавлено | --zt-fg: #404040; |
| +добавлено | --zt-fg2: rgba(64, 64, 64, .6); |
| +добавлено | --zt-fg3: rgba(64, 64, 64, .35); |
| +добавлено | --zt-tag: #ececec; |
| +добавлено | --zt-brand: #000000; |
| +добавлено | --zt-primary: #0a0a0a; |
| +добавлено | --zt-primary-fg: #fafafa; |
| +добавлено | --zt-shadow: 0 10px 30px -10px rgba(0, 0, 0, .18), 0 2px 6px rgba(0, 0, 0, .06); |
| +добавлено | --zt-shadow-lift: 0 18px 40px -10px rgba(0, 0, 0, .25), 0 4px 12px rgba(0, 0, 0, .08); |
| +добавлено | --zt-backdrop: rgba(0, 0, 0, .18); |
| +добавлено | --zt-scroll: rgba(0, 0, 0, .14); |
| +добавлено | --zt-scroll-hover: rgba(0, 0, 0, .26); |
| +добавлено | --zt-diff-add: rgba(34, 197, 94, .12); |
| +добавлено | --zt-diff-add-fg: #15803d; |
| +добавлено | --zt-diff-del: rgba(239, 68, 68, .10); |
| +добавлено | --zt-diff-del-fg: #b91c1c; |
| +добавлено | --zt-diff-hunk: rgba(14, 165, 233, .08); |
| +добавлено | --zt-shimmer: rgba(0, 0, 0, .05); |
| +добавлено | } |
| +добавлено | |
| +добавлено | * { box-sizing: border-box; } |
| +добавлено | html, body { height: 100%; margin: 0; } |
| +добавлено | body { |
| +добавлено | background: var(--zt-bg); |
| +добавлено | color: var(--zt-fg); |
| +добавлено | font: 13px/1.45 var(--font); |
| +добавлено | -webkit-font-smoothing: antialiased; |
| +добавлено | overflow: hidden; |
| +добавлено | user-select: none; |
| +добавлено | } |
| +добавлено | #app { height: 100%; } |
| +добавлено | input, textarea, select, button { font: inherit; color: inherit; } |
| +добавлено | button { cursor: pointer; } |
| +добавлено | a { color: var(--zt-brand); text-decoration: none; } |
| +добавлено | a:hover { text-decoration: underline; } |
| +добавлено | .ic { flex: none; display: block; } |
| +добавлено | .sel-text, input, textarea, .mono, .diff, .selectable { user-select: text; } |
| +добавлено | |
| +добавлено | /* ---------- скроллбары ---------- */ |
| +добавлено | * { scrollbar-width: thin; scrollbar-color: var(--zt-scroll) transparent; } |
| +добавлено | ::-webkit-scrollbar { width: 8px; height: 8px; } |
| +добавлено | ::-webkit-scrollbar-track { background: transparent; } |
| +добавлено | ::-webkit-scrollbar-thumb { background: var(--zt-scroll); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; } |
| +добавлено | ::-webkit-scrollbar-thumb:hover { background: var(--zt-scroll-hover); background-clip: padding-box; border: 2px solid transparent; } |
| +добавлено | ::-webkit-scrollbar-corner { background: transparent; } |
| +добавлено | |
| +добавлено | /* ---------- раскладка ---------- */ |
| +добавлено | .shell { display: flex; flex-direction: column; height: 100%; min-width: 0; } |
| +добавлено | .hdr { |
| +добавлено | height: 44px; flex: none; display: flex; align-items: center; gap: 6px; |
| +добавлено | padding: 0 8px 0 8px; background: var(--zt-header); |
| +добавлено | border-bottom: 1px solid var(--zt-border); |
| +добавлено | } |
| +добавлено | .hdr .grow { flex: 1; min-width: 0; } |
| +добавлено | .team-sw { |
| +добавлено | display: flex; align-items: center; gap: 8px; min-width: 0; max-width: 260px; |
| +добавлено | height: 32px; padding: 0 8px 0 4px; border-radius: 8px; border: 0; background: transparent; |
| +добавлено | transition: background-color .12s var(--ease); |
| +добавлено | } |
| +добавлено | .team-sw:hover, .team-sw[aria-expanded="true"] { background: var(--zt-hover); } |
| +добавлено | .team-sw .name { font-weight: 600; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| +добавлено | .team-sw .ic { color: var(--zt-fg2); } |
| +добавлено | .team-tile { |
| +добавлено | width: 24px; height: 24px; border-radius: 6px; flex: none; display: grid; place-items: center; |
| +добавлено | font-size: 10.5px; font-weight: 700; letter-spacing: .02em; color: #fff; |
| +добавлено | background: linear-gradient(135deg, #0ea5e9, #6366f1); |
| +добавлено | } |
| +добавлено | .team-tile.lg { width: 40px; height: 40px; border-radius: 10px; font-size: 14px; } |
| +добавлено | .live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--zt-fg3); flex: none; transition: background-color .2s; } |
| +добавлено | .live-dot.on { background: var(--zt-success); box-shadow: 0 0 0 3px rgba(34, 197, 94, .15); } |
| +добавлено | |
| +добавлено | .tabs { |
| +добавлено | flex: none; position: relative; display: flex; gap: 2px; padding: 0 8px; |
| +добавлено | border-bottom: 1px solid var(--zt-border); overflow-x: auto; overflow-y: hidden; scrollbar-width: none; |
| +добавлено | } |
| +добавлено | .tabs::-webkit-scrollbar { display: none; } |
| +добавлено | .tab { |
| +добавлено | position: relative; display: flex; align-items: center; gap: 6px; height: 38px; padding: 0 10px; |
| +добавлено | border: 0; background: transparent; color: var(--zt-fg2); font-size: 13px; font-weight: 500; white-space: nowrap; |
| +добавлено | border-radius: 6px; transition: color .12s var(--ease); |
| +добавлено | } |
| +добавлено | .tab:hover { color: var(--zt-fg); } |
| +добавлено | .tab[aria-selected="true"] { color: var(--zt-fg); } |
| +добавлено | .tab .badge { margin-left: 1px; } |
| +добавлено | .tab-ind { |
| +добавлено | position: absolute; left: 0; bottom: -1px; height: 2px; width: 100px; background: var(--zt-fg); |
| +добавлено | border-radius: 2px; transform-origin: 0 0; transition: transform .24s var(--ease); pointer-events: none; |
| +добавлено | } |
| +добавлено | .compact-tabs .tab:not([aria-selected="true"]) .lbl { display: none; } |
| +добавлено | .compact-tabs .tab { padding: 0 9px; } |
| +добавлено | .narrow .tab .lbl { display: none; } |
| +добавлено | |
| +добавлено | .main { flex: 1; min-height: 0; position: relative; } |
| +добавлено | .pane { position: absolute; inset: 0; overflow: auto; overscroll-behavior: contain; } |
| +добавлено | .pane[hidden] { display: none; } |
| +добавлено | .pane.enter { animation: paneIn .22s var(--ease); } |
| +добавлено | .pane.enter-l { animation: paneInL .22s var(--ease); } |
| +добавлено | @keyframes paneIn { from { opacity: 0; transform: translateX(6px); } to { opacity: 1; transform: none; } } |
| +добавлено | @keyframes paneInL { from { opacity: 0; transform: translateX(-6px); } to { opacity: 1; transform: none; } } |
| +добавлено | .pad { padding: 12px; } |
| +добавлено | .stack { display: flex; flex-direction: column; gap: 12px; } |
| +добавлено | .stack-s { display: flex; flex-direction: column; gap: 8px; } |
| +добавлено | .row { display: flex; align-items: center; gap: 8px; min-width: 0; } |
| +добавлено | .row.wrap { flex-wrap: wrap; } |
| +добавлено | .row.top { align-items: flex-start; } |
| +добавлено | .grow { flex: 1; min-width: 0; } |
| +добавлено | .spacer { flex: 1; } |
| +добавлено | .ell { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } |
| +добавлено | .muted { color: var(--zt-fg2); } |
| +добавлено | .faint { color: var(--zt-fg3); } |
| +добавлено | .small { font-size: 12px; } |
| +добавлено | .xs { font-size: 11px; } |
| +добавлено | .mono { font-family: var(--mono); font-size: 12px; } |
| +добавлено | .b { font-weight: 600; } |
| +добавлено | .danger-t { color: var(--zt-danger); } |
| +добавлено | .ok-t { color: var(--zt-success); } |
| +добавлено | .warn-t { color: var(--zt-warning); } |
| +добавлено | .h1 { font-size: 18px; font-weight: 600; margin: 0; letter-spacing: -.01em; } |
| +добавлено | .h2 { font-size: 14px; font-weight: 600; margin: 0; } |
| +добавлено | .sec-title { |
| +добавлено | display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; |
| +добавлено | color: var(--zt-fg2); text-transform: none; margin: 0; |
| +добавлено | } |
| +добавлено | .sec-title .ic { color: var(--zt-fg2); } |
| +добавлено | .divider { height: 1px; background: var(--zt-border); border: 0; margin: 4px 0; } |
| +добавлено | |
| +добавлено | /* ---------- кнопки ---------- */ |
| +добавлено | .btn { |
| +добавлено | display: inline-flex; align-items: center; justify-content: center; gap: 6px; flex: none; |
| +добавлено | height: 28px; padding: 0 12px; border-radius: 999px; border: 0; white-space: nowrap; |
| +добавлено | background: var(--zt-hover); color: var(--zt-fg); font-size: 12.5px; font-weight: 500; |
| +добавлено | transition: background-color .12s var(--ease), color .12s var(--ease), transform .12s var(--ease), opacity .12s; |
| +добавлено | } |
| +добавлено | .btn:hover { background: rgba(255, 255, 255, .15); } |
| +добавлено | html.light .btn:hover { background: rgba(13, 13, 13, .09); } |
| +добавлено | .btn:active:not(:disabled) { transform: scale(.97); } |
| +добавлено | .btn:disabled { opacity: .45; cursor: default; } |
| +добавлено | .btn.primary { background: var(--zt-primary); color: var(--zt-primary-fg); } |
| +добавлено | .btn.primary:hover { background: color-mix(in srgb, var(--zt-primary) 88%, transparent); } |
| +добавлено | .btn.ghost { background: transparent; color: var(--zt-fg2); } |
| +добавлено | .btn.ghost:hover { background: var(--zt-hover); color: var(--zt-fg); } |
| +добавлено | .btn.danger { background: rgba(239, 68, 68, .12); color: #f87171; } |
| +добавлено | .btn.danger:hover { background: rgba(239, 68, 68, .2); } |
| +добавлено | html.light .btn.danger { color: #dc2626; } |
| +добавлено | .btn.solid-danger { background: var(--zt-danger); color: #fff; } |
| +добавлено | .btn.solid-danger:hover { background: #dc2626; } |
| +добавлено | .btn.lg { height: 34px; padding: 0 16px; font-size: 13px; border-radius: 8px; } |
| +добавлено | .btn.block { width: 100%; } |
| +добавлено | .btn.sq { border-radius: 8px; } |
| +добавлено | .btn.sm { height: 24px; padding: 0 9px; font-size: 12px; } |
| +добавлено | .ibtn { |
| +добавлено | width: 28px; height: 28px; flex: none; display: inline-grid; place-items: center; border-radius: 7px; border: 0; |
| +добавлено | background: transparent; color: var(--zt-fg2); |
| +добавлено | transition: background-color .12s var(--ease), color .12s var(--ease), transform .12s var(--ease); |
| +добавлено | } |
| +добавлено | .ibtn:hover { background: var(--zt-hover); color: var(--zt-fg); } |
| +добавлено | .ibtn:active:not(:disabled) { transform: scale(.94); } |
| +добавлено | .ibtn:disabled { opacity: .4; cursor: default; } |
| +добавлено | .ibtn.sm { width: 24px; height: 24px; border-radius: 6px; } |
| +добавлено | .ibtn.danger:hover { color: var(--zt-danger); background: rgba(239, 68, 68, .1); } |
| +добавлено | .ibtn.on { color: var(--zt-fg); background: var(--zt-selected); } |
| +добавлено | :focus { outline: none; } |
| +добавлено | :focus-visible { outline: 2px solid var(--zt-brand); outline-offset: 1px; } |
| +добавлено | .btn .spin, .ibtn .spin { width: 13px; height: 13px; } |
| +добавлено | .linkbtn { border: 0; background: none; padding: 0; color: var(--zt-fg2); font-size: 12px; text-decoration: underline; text-decoration-color: var(--zt-fg3); text-underline-offset: 2px; } |
| +добавлено | .linkbtn:hover { color: var(--zt-fg); } |
| +добавлено | |
| +добавлено | /* ---------- поля ---------- */ |
| +добавлено | .field { display: flex; flex-direction: column; gap: 5px; min-width: 0; } |
| +добавлено | .field > .lbl { font-size: 12px; color: var(--zt-fg2); font-weight: 500; } |
| +добавлено | .field .hint { font-size: 11.5px; color: var(--zt-fg3); } |
| +добавлено | .inp, .ta, .sel { |
| +добавлено | width: 100%; height: 32px; padding: 0 10px; border-radius: 8px; |
| +добавлено | background: var(--zt-surface); border: 1px solid var(--zt-border); color: var(--zt-fg); |
| +добавлено | font-size: 13px; outline: none; min-width: 0; |
| +добавлено | transition: border-color .12s var(--ease), background-color .12s var(--ease), box-shadow .12s var(--ease); |
| +добавлено | } |
| +добавлено | .inp:hover, .ta:hover, .sel:hover { border-color: var(--zt-border-hover); } |
| +добавлено | .inp:focus, .ta:focus, .sel:focus { border-color: var(--zt-brand); box-shadow: 0 0 0 1px var(--zt-brand); } |
| +добавлено | .inp:focus-visible, .ta:focus-visible, .sel:focus-visible { outline: none; } |
| +добавлено | .inp::placeholder, .ta::placeholder { color: var(--zt-fg3); } |
| +добавлено | .inp:disabled, .ta:disabled, .sel:disabled { opacity: .6; cursor: default; } |
| +добавлено | .inp.sm, .sel.sm { height: 28px; font-size: 12.5px; padding: 0 8px; } |
| +добавлено | .inp.mono { font-family: var(--mono); font-size: 12.5px; } |
| +добавлено | .inp.err { border-color: var(--zt-danger); } |
| +добавлено | .ta { height: auto; min-height: 64px; padding: 8px 10px; resize: none; line-height: 1.5; overflow: hidden; } |
| +добавлено | .ta.scroll { overflow: auto; } |
| +добавлено | .sel { |
| +добавлено | appearance: none; -webkit-appearance: none; padding-right: 28px; cursor: pointer; |
| +добавлено | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a3a3a3' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); |
| +добавлено | background-repeat: no-repeat; background-position: right 8px center; background-size: 14px; |
| +добавлено | } |
| +добавлено | .row > .sel { width: auto; flex: none; max-width: 60%; } |
| +добавлено | .row > .sel.grow { flex: 1; max-width: none; } |
| +добавлено | .sel.role-sel { width: 132px; flex: none; } |
| +добавлено | .sel option { background: var(--zt-popover); color: var(--zt-fg); } |
| +добавлено | input[type="date"].inp { padding-right: 6px; } |
| +добавлено | input[type="date"]::-webkit-calendar-picker-indicator { opacity: .6; cursor: pointer; filter: invert(.85); } |
| +добавлено | html.light input[type="date"]::-webkit-calendar-picker-indicator { filter: none; } |
| +добавлено | input[type="date"]::-webkit-datetime-edit { color: var(--zt-fg); } |
| +добавлено | input[type="date"].empty::-webkit-datetime-edit { color: var(--zt-fg3); } |
| +добавлено | input[type="number"]::-webkit-inner-spin-button { opacity: .4; } |
| +добавлено | .inp-icon { position: relative; display: flex; align-items: center; min-width: 0; } |
| +добавлено | .inp-icon > .ic { position: absolute; left: 9px; color: var(--zt-fg3); pointer-events: none; } |
| +добавлено | .inp-icon > .inp { padding-left: 30px; } |
| +добавлено | .inp-icon > .clr { position: absolute; right: 3px; } |
| +добавлено | |
| +добавлено | .chk { |
| +добавлено | appearance: none; -webkit-appearance: none; width: 16px; height: 16px; flex: none; margin: 0; border-radius: 4px; |
| +добавлено | border: 1px solid var(--zt-border-hover); background: var(--zt-surface); cursor: pointer; display: inline-grid; place-items: center; |
| +добавлено | transition: background-color .12s var(--ease), border-color .12s var(--ease); |
| +добавлено | } |
| +добавлено | .chk:checked { background: var(--zt-primary); border-color: var(--zt-primary); } |
| +добавлено | .chk:checked::after { |
| +добавлено | content: ""; width: 10px; height: 10px; |
| +добавлено | background: var(--zt-primary-fg); |
| +добавлено | -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E") center/contain no-repeat; |
| +добавлено | mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E") center/contain no-repeat; |
| +добавлено | } |
| +добавлено | .chk-row { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 12.5px; } |
| +добавлено | |
| +добавлено | /* ---------- сегменты / чипы ---------- */ |
| +добавлено | .seg { |
| +добавлено | position: relative; display: inline-flex; padding: 2px; gap: 0; border-radius: 9px; |
| +добавлено | background: var(--zt-surface); border: 1px solid var(--zt-border); min-width: 0; |
| +добавлено | } |
| +добавлено | .seg.block { display: flex; } |
| +добавлено | .seg button { |
| +добавлено | position: relative; z-index: 1; flex: 1; height: 26px; padding: 0 10px; border: 0; background: transparent; |
| +добавлено | color: var(--zt-fg2); font-size: 12.5px; font-weight: 500; border-radius: 7px; white-space: nowrap; |
| +добавлено | transition: color .12s var(--ease); |
| +добавлено | } |
| +добавлено | .seg button[aria-pressed="true"] { color: var(--zt-fg); } |
| +добавлено | .seg button:disabled { cursor: default; } |
| +добавлено | .seg .thumb { |
| +добавлено | position: absolute; top: 2px; bottom: 2px; left: 0; border-radius: 7px; background: var(--zt-card-sel); |
| +добавлено | transition: transform .22s var(--ease), width .22s var(--ease); box-shadow: 0 1px 2px rgba(0, 0, 0, .25); |
| +добавлено | } |
| +добавлено | html.light .seg .thumb { background: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .12); } |
| +добавлено | .chips { display: flex; gap: 4px; flex-wrap: wrap; } |
| +добавлено | .chip { |
| +добавлено | display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 10px; border-radius: 999px; |
| +добавлено | border: 1px solid var(--zt-border); background: transparent; color: var(--zt-fg2); font-size: 12px; font-weight: 500; |
| +добавлено | transition: background-color .12s var(--ease), color .12s, border-color .12s, transform .12s var(--ease); |
| +добавлено | white-space: nowrap; |
| +добавлено | } |
| +добавлено | .chip:hover { color: var(--zt-fg); background: var(--zt-surface); } |
| +добавлено | .chip:active { transform: scale(.97); } |
| +добавлено | .chip[aria-pressed="true"] { background: var(--zt-selected); color: var(--zt-fg); border-color: transparent; } |
| +добавлено | |
| +добавлено | .badge { |
| +добавлено | display: inline-grid; place-items: center; min-width: 17px; height: 17px; padding: 0 5px; border-radius: 999px; |
| +добавлено | background: var(--zt-tag); color: var(--zt-fg); font-size: 10.5px; font-weight: 600; line-height: 1; |
| +добавлено | } |
| +добавлено | .badge.brand { background: var(--zt-brand); color: #fff; } |
| +добавлено | html.light .badge.brand { color: #fff; } |
| +добавлено | .pill { |
| +добавлено | display: inline-flex; align-items: center; gap: 4px; height: 20px; padding: 0 8px; border-radius: 999px; |
| +добавлено | background: var(--zt-hover); color: var(--zt-fg2); font-size: 11.5px; font-weight: 500; white-space: nowrap; flex: none; |
| +добавлено | } |
| +добавлено | .pill.ok { background: rgba(34, 197, 94, .14); color: #4ade80; } |
| +добавлено | .pill.warn { background: rgba(234, 179, 8, .14); color: #facc15; } |
| +добавлено | .pill.err { background: rgba(239, 68, 68, .14); color: #f87171; } |
| +добавлено | .pill.brand { background: rgba(14, 165, 233, .15); color: #38bdf8; } |
| +добавлено | html.light .pill.ok { color: #15803d; } |
| +добавлено | html.light .pill.warn { color: #a16207; } |
| +добавлено | html.light .pill.err { color: #dc2626; } |
| +добавлено | html.light .pill.brand { color: #0369a1; } |
| +добавлено | .tag { |
| +добавлено | display: inline-flex; align-items: center; height: 18px; padding: 0 6px; border-radius: 5px; |
| +добавлено | background: var(--zt-tag); color: var(--zt-fg); font-size: 11px; white-space: nowrap; max-width: 120px; overflow: hidden; text-overflow: ellipsis; |
| +добавлено | } |
| +добавлено | .role { |
| +добавлено | display: inline-flex; align-items: center; gap: 4px; height: 20px; padding: 0 7px; border-radius: 6px; |
| +добавлено | font-size: 11px; font-weight: 500; background: var(--zt-hover); color: var(--zt-fg2); white-space: nowrap; flex: none; |
| +добавлено | } |
| +добавлено | .role.owner { background: rgba(234, 179, 8, .14); color: #facc15; } |
| +добавлено | .role.maintainer { background: rgba(14, 165, 233, .14); color: #38bdf8; } |
| +добавлено | .role.dev { background: rgba(34, 197, 94, .12); color: #4ade80; } |
| +добавлено | html.light .role.owner { color: #a16207; } |
| +добавлено | html.light .role.maintainer { color: #0369a1; } |
| +добавлено | html.light .role.dev { color: #15803d; } |
| +добавлено | .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; background: var(--zt-fg3); } |
| +добавлено | .dot.ok { background: var(--zt-success); } |
| +добавлено | .dot.warn { background: var(--zt-warning); } |
| +добавлено | .dot.err { background: var(--zt-danger); } |
| +добавлено | |
| +добавлено | /* ---------- карточки ---------- */ |
| +добавлено | .card { background: var(--zt-card); border: 1px solid var(--zt-border); border-radius: 12px; } |
| +добавлено | html.light .card { box-shadow: 0 1px 2px rgba(0, 0, 0, .03); } |
| +добавлено | .card.pad { padding: 12px; } |
| +добавлено | .card-h { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--zt-border); min-height: 44px; } |
| +добавлено | .card-b { padding: 12px; } |
| +добавлено | .list { display: flex; flex-direction: column; } |
| +добавлено | .li { |
| +добавлено | display: flex; align-items: center; gap: 10px; padding: 8px 12px; min-height: 44px; min-width: 0; |
| +добавлено | border-top: 1px solid var(--zt-border); transition: background-color .12s var(--ease); |
| +добавлено | } |
| +добавлено | .li:first-child { border-top: 0; } |
| +добавлено | .li.click { cursor: pointer; } |
| +добавлено | .li.click:hover, .li:focus-visible { background: var(--zt-surface); } |
| +добавлено | .li .acts { display: flex; gap: 2px; opacity: 0; transition: opacity .12s var(--ease); } |
| +добавлено | .li:hover .acts, .li:focus-within .acts { opacity: 1; } |
| +добавлено | @media (hover: none) { .li .acts { opacity: 1; } } |
| +добавлено | |
| +добавлено | .launcher { |
| +добавлено | display: flex; align-items: center; gap: 12px; padding: 12px; width: 100%; text-align: left; |
| +добавлено | background: var(--zt-card); border: 1px solid var(--zt-border); border-radius: 12px; color: var(--zt-fg); |
| +добавлено | transition: border-color .12s var(--ease), background-color .12s var(--ease), transform .12s var(--ease); |
| +добавлено | } |
| +добавлено | button.launcher:hover { border-color: var(--zt-border-hover); } |
| +добавлено | button.launcher:active { transform: scale(.99); } |
| +добавлено | .launcher .tile { |
| +добавлено | width: 48px; height: 48px; border-radius: 12px; flex: none; display: grid; place-items: center; |
| +добавлено | background: var(--zt-surface); border: 1px solid var(--zt-border); color: var(--zt-fg); |
| +добавлено | } |
| +добавлено | .launcher .t { font-weight: 600; font-size: 13.5px; } |
| +добавлено | .launcher .d { color: var(--zt-fg2); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| +добавлено | .launcher .pill { height: 26px; padding: 0 12px; font-size: 12.5px; color: var(--zt-fg); background: var(--zt-hover); } |
| +добавлено | .empty { |
| +добавлено | display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 8px; |
| +добавлено | padding: 28px 16px; color: var(--zt-fg2); |
| +добавлено | } |
| +добавлено | .empty .tile { width: 48px; height: 48px; border-radius: 12px; display: grid; place-items: center; background: var(--zt-surface); border: 1px solid var(--zt-border); color: var(--zt-fg2); } |
| +добавлено | .empty .t { color: var(--zt-fg); font-weight: 600; } |
| +добавлено | .empty .d { font-size: 12px; max-width: 280px; } |
| +добавлено | .info-row { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-top: 1px solid var(--zt-border); font-size: 12.5px; min-width: 0; } |
| +добавлено | .info-row:first-child { border-top: 0; } |
| +добавлено | .info-row .k { color: var(--zt-fg2); width: 110px; flex: none; } |
| +добавлено | .info-row .v { flex: 1; min-width: 0; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +добавлено | |
| +добавлено | /* ---------- аватары ---------- */ |
| +добавлено | .av { |
| +добавлено | position: relative; width: 24px; height: 24px; border-radius: 50%; flex: none; display: grid; place-items: center; |
| +добавлено | color: #fff; font-size: 10px; font-weight: 600; letter-spacing: .01em; background: #525252; text-transform: uppercase; |
| +добавлено | } |
| +добавлено | .av.s18 { width: 18px; height: 18px; font-size: 8.5px; } |
| +добавлено | .av.s20 { width: 20px; height: 20px; font-size: 9px; } |
| +добавлено | .av.s32 { width: 32px; height: 32px; font-size: 12px; } |
| +добавлено | .av.s64 { width: 64px; height: 64px; font-size: 22px; } |
| +добавлено | .av .on { |
| +добавлено | position: absolute; right: -1px; bottom: -1px; width: 9px; height: 9px; border-radius: 50%; |
| +добавлено | background: var(--zt-success); border: 2px solid var(--zt-bg); |
| +добавлено | } |
| +добавлено | .av.s32 .on { width: 11px; height: 11px; } |
| +добавлено | .av .on.away { background: var(--zt-warning); } |
| +добавлено | .av .on.busy, .av .on.dnd { background: var(--zt-danger); } |
| +добавлено | .av-stack { display: flex; align-items: center; padding-left: 4px; } |
| +добавлено | .av-stack .av { margin-left: -5px; box-shadow: 0 0 0 2px var(--zt-header); } |
| +добавлено | .av-stack .more { margin-left: -5px; background: var(--zt-tag); color: var(--zt-fg); box-shadow: 0 0 0 2px var(--zt-header); } |
| +добавлено | .av.none { background: transparent; border: 1px dashed var(--zt-border-hover); color: var(--zt-fg3); } |
| +добавлено | |
| +добавлено | /* ---------- поповер / меню ---------- */ |
| +добавлено | .pop { |
| +добавлено | position: fixed; z-index: 60; min-width: 200px; max-width: min(320px, calc(100vw - 16px)); padding: 4px; |
| +добавлено | background: var(--zt-popover); border: 1px solid var(--zt-border); border-radius: 10px; box-shadow: var(--zt-shadow); |
| +добавлено | animation: popIn .16s var(--ease); transform-origin: top left; |
| +добавлено | } |
| +добавлено | @keyframes popIn { from { opacity: 0; transform: scale(.97) translateY(-4px); } to { opacity: 1; transform: none; } } |
| +добавлено | .mi { |
| +добавлено | display: flex; align-items: center; gap: 8px; width: 100%; min-height: 32px; padding: 4px 8px; border: 0; border-radius: 6px; |
| +добавлено | background: transparent; color: var(--zt-fg); text-align: left; font-size: 13px; |
| +добавлено | } |
| +добавлено | .mi:hover, .mi:focus-visible { background: var(--zt-hover); outline: none; } |
| +добавлено | .mi .ic { color: var(--zt-fg2); } |
| +добавлено | .mi.danger { color: #f87171; } |
| +добавлено | .mi.danger .ic { color: #f87171; } |
| +добавлено | .mi .chk-ic { margin-left: auto; color: var(--zt-fg); } |
| +добавлено | .pop .sep { height: 1px; background: var(--zt-border); margin: 4px; } |
| +добавлено | .pop .lbl { padding: 6px 8px 4px; font-size: 11px; color: var(--zt-fg3); font-weight: 600; } |
| +добавлено | |
| +добавлено | /* ---------- слои: шторки, диалоги ---------- */ |
| +добавлено | .backdrop { |
| +добавлено | position: fixed; inset: 0; z-index: 40; background: var(--zt-backdrop); |
| +добавлено | animation: fadeIn .2s var(--ease) both; |
| +добавлено | } |
| +добавлено | .backdrop.out { animation: fadeOut .18s var(--ease) both; } |
| +добавлено | @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } |
| +добавлено | @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } |
| +добавлено | .drawer { |
| +добавлено | position: fixed; z-index: 41; top: 0; right: 0; bottom: 0; width: min(560px, calc(100vw - 24px)); |
| +добавлено | display: flex; flex-direction: column; background: var(--zt-bg); border-left: 1px solid var(--zt-border); |
| +добавлено | box-shadow: var(--zt-shadow-lift); animation: drawerIn .26s var(--ease) both; |
| +добавлено | } |
| +добавлено | .drawer.wide { width: min(820px, calc(100vw - 24px)); } |
| +добавлено | .drawer.out { animation: drawerOut .2s var(--ease) both; } |
| +добавлено | @keyframes drawerIn { from { transform: translateX(100%); } to { transform: none; } } |
| +добавлено | @keyframes drawerOut { from { transform: none; } to { transform: translateX(100%); } } |
| +добавлено | .sheet { |
| +добавлено | position: fixed; z-index: 41; left: 0; right: 0; bottom: 0; max-height: calc(100% - 40px); |
| +добавлено | margin: 0 auto; width: min(560px, 100%); |
| +добавлено | display: flex; flex-direction: column; background: var(--zt-bg); border: 1px solid var(--zt-border); border-bottom: 0; |
| +добавлено | border-radius: 14px 14px 0 0; box-shadow: var(--zt-shadow-lift); animation: sheetIn .26s var(--ease) both; |
| +добавлено | } |
| +добавлено | .sheet.out { animation: sheetOut .2s var(--ease) both; } |
| +добавлено | @keyframes sheetIn { from { transform: translateY(100%); } to { transform: none; } } |
| +добавлено | @keyframes sheetOut { from { transform: none; } to { transform: translateY(100%); } } |
| +добавлено | .sheet .grab { width: 36px; height: 4px; border-radius: 4px; background: var(--zt-border-hover); margin: 8px auto 0; flex: none; } |
| +добавлено | .layer-h { display: flex; align-items: center; gap: 8px; padding: 10px 10px 10px 16px; min-height: 48px; border-bottom: 1px solid var(--zt-border); flex: none; } |
| +добавлено | .layer-h .t { font-size: 14px; font-weight: 600; flex: 1; min-width: 0; } |
| +добавлено | .layer-b { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 18px; } |
| +добавлено | .layer-f { flex: none; display: flex; gap: 8px; justify-content: flex-end; padding: 10px 16px; border-top: 1px solid var(--zt-border); } |
| +добавлено | .dialog { |
| +добавлено | position: fixed; z-index: 51; left: 50%; top: 50%; width: min(380px, calc(100vw - 32px)); |
| +добавлено | transform: translate(-50%, -50%); background: var(--zt-card); border: 1px solid var(--zt-border); |
| +добавлено | border-radius: 12px; box-shadow: var(--zt-shadow-lift); animation: dlgIn .2s var(--ease) both; padding: 16px; |
| +добавлено | } |
| +добавлено | .dialog.out { animation: dlgOut .16s var(--ease) both; } |
| +добавлено | .backdrop.dlg { z-index: 50; } |
| +добавлено | @keyframes dlgIn { from { opacity: 0; transform: translate(-50%, -48%) scale(.97); } to { opacity: 1; transform: translate(-50%, -50%); } } |
| +добавлено | @keyframes dlgOut { from { opacity: 1; transform: translate(-50%, -50%); } to { opacity: 0; transform: translate(-50%, -48%) scale(.98); } } |
| +добавлено | .dialog .t { font-weight: 600; font-size: 14px; margin-bottom: 6px; } |
| +добавлено | .dialog .d { color: var(--zt-fg2); font-size: 12.5px; margin-bottom: 14px; } |
| +добавлено | |
| +добавлено | /* ---------- тосты ---------- */ |
| +добавлено | .toasts { position: fixed; z-index: 70; left: 0; right: 0; bottom: 12px; display: flex; flex-direction: column-reverse; align-items: center; gap: 6px; pointer-events: none; padding: 0 12px; } |
| +добавлено | .toast { |
| +добавлено | pointer-events: auto; display: flex; align-items: center; gap: 10px; max-width: min(440px, 100%); min-height: 38px; |
| +добавлено | padding: 6px 6px 6px 12px; border-radius: 10px; background: var(--zt-popover); border: 1px solid var(--zt-border); |
| +добавлено | box-shadow: var(--zt-shadow); font-size: 12.5px; animation: toastIn .24s var(--ease) both; |
| +добавлено | } |
| +добавлено | .toast.out { animation: toastOut .18s var(--ease) both; } |
| +добавлено | .toast .ic.k { color: var(--zt-fg2); } |
| +добавлено | .toast.ok .ic.k { color: var(--zt-success); } |
| +добавлено | .toast.err .ic.k { color: var(--zt-danger); } |
| +добавлено | .toast .msg { flex: 1; min-width: 0; padding: 3px 0; } |
| +добавлено | .toast .btn { height: 26px; } |
| +добавлено | @keyframes toastIn { from { opacity: 0; transform: translateY(12px) scale(.98); } to { opacity: 1; transform: none; } } |
| +добавлено | @keyframes toastOut { from { opacity: 1; transform: none; } to { opacity: 0; transform: translateY(8px) scale(.98); } } |
| +добавлено | |
| +добавлено | /* ---------- загрузка ---------- */ |
| +добавлено | .skel { position: relative; overflow: hidden; background: var(--zt-surface); border-radius: 8px; } |
| +добавлено | .skel::after { |
| +добавлено | content: ""; position: absolute; inset: 0; transform: translateX(-100%); |
| +добавлено | background: linear-gradient(90deg, transparent, var(--zt-shimmer), transparent); |
| +добавлено | animation: shimmer 1.3s infinite; |
| +добавлено | } |
| +добавлено | @keyframes shimmer { to { transform: translateX(100%); } } |
| +добавлено | .spin { width: 16px; height: 16px; border-radius: 50%; border: 2px solid var(--zt-fg3); border-top-color: var(--zt-fg); animation: spin .7s linear infinite; flex: none; } |
| +добавлено | @keyframes spin { to { transform: rotate(360deg); } } |
| +добавлено | .progress { height: 4px; border-radius: 4px; background: var(--zt-hover); overflow: hidden; flex: none; } |
| +добавлено | .progress.grow { flex: 1; } |
| +добавлено | .progress > i { display: block; height: 100%; width: 100%; background: var(--zt-brand); border-radius: 4px; transform-origin: 0 0; transition: transform .2s var(--ease); } |
| +добавлено | .progress.warn > i { background: var(--zt-warning); } |
| +добавлено | .progress.err > i { background: var(--zt-danger); } |
| +добавлено | .progress.ok > i { background: var(--zt-success); } |
| +добавлено | |
| +добавлено | /* ---------- анимации списков ---------- */ |
| +добавлено | .enter-item { animation: itemIn .24s var(--ease) both; } |
| +добавлено | @keyframes itemIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } |
| +добавлено | .leave-item { animation: itemOut .18s var(--ease) both; pointer-events: none; } |
| +добавлено | @keyframes itemOut { from { opacity: 1; } to { opacity: 0; transform: scale(.98); } } |
| +добавлено | |
| +добавлено | /* ---------- auth / онбординг ---------- */ |
| +добавлено | .center-wrap { min-height: 100%; display: flex; align-items: center; justify-content: center; padding: 20px 14px; } |
| +добавлено | .auth { width: 100%; max-width: 360px; display: flex; flex-direction: column; gap: 14px; } |
| +добавлено | .auth .hero { display: flex; flex-direction: column; align-items: center; gap: 10px; text-align: center; margin-bottom: 4px; } |
| +добавлено | .auth .card { padding: 16px; display: flex; flex-direction: column; gap: 12px; } |
| +добавлено | .err-box { display: flex; gap: 8px; align-items: flex-start; padding: 8px 10px; border-radius: 8px; background: rgba(239, 68, 68, .1); color: #fca5a5; font-size: 12.5px; animation: itemIn .2s var(--ease); } |
| +добавлено | html.light .err-box { color: #b91c1c; } |
| +добавлено | .device-code { font-family: var(--mono); font-size: 26px; font-weight: 600; letter-spacing: .14em; text-align: center; padding: 12px; border-radius: 10px; background: var(--zt-surface); border: 1px dashed var(--zt-border-hover); } |
| +добавлено | .collapse-btn { display: flex; align-items: center; gap: 6px; border: 0; background: none; color: var(--zt-fg2); font-size: 12px; padding: 2px 0; } |
| +добавлено | .collapse-btn .ic { transition: transform .2s var(--ease); } |
| +добавлено | .collapse-btn[aria-expanded="true"] .ic { transform: rotate(180deg); } |
| +добавлено | .reveal { animation: itemIn .2s var(--ease); } |
| +добавлено | |
| +добавлено | /* ---------- лента ---------- */ |
| +добавлено | .feed { flex: none; border-top: 1px solid var(--zt-border); background: var(--zt-header); } |
| +добавлено | .feed-peek { display: flex; align-items: center; gap: 8px; width: 100%; height: 34px; padding: 0 10px; border: 0; background: transparent; color: var(--zt-fg2); font-size: 12px; text-align: left; } |
| +добавлено | .feed-peek:hover { background: var(--zt-surface); } |
| +добавлено | .feed-peek .ic.chev { transition: transform .22s var(--ease); } |
| +добавлено | .feed.open .feed-peek .ic.chev { transform: rotate(180deg); } |
| +добавлено | .feed-body { height: 0; overflow: hidden; transition: height .24s var(--ease); } |
| +добавлено | .feed.open .feed-body { height: 220px; overflow: auto; } |
| +добавлено | .feed-item { display: flex; gap: 8px; align-items: flex-start; padding: 6px 12px; font-size: 12px; } |
| +добавлено | .feed-item .txt { flex: 1; min-width: 0; color: var(--zt-fg); } |
| +добавлено | .feed-item .txt b { font-weight: 600; } |
| +добавлено | .feed-item .tm { color: var(--zt-fg3); font-size: 11px; white-space: nowrap; } |
| +добавлено | .feed-item.new { animation: feedIn .3s var(--ease) both; } |
| +добавлено | @keyframes feedIn { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } } |
| +добавлено | |
| +добавлено | /* ---------- канбан ---------- */ |
| +добавлено | .kb-tools { position: sticky; left: 0; top: 0; z-index: 5; display: flex; flex-direction: column; gap: 8px; padding: 10px 12px 8px; background: var(--zt-bg); } |
| +добавлено | .kb-scroll { overflow-x: auto; overflow-y: visible; padding: 0 12px 16px; } |
| +добавлено | .kb-cols { display: flex; gap: 8px; align-items: flex-start; min-width: min-content; position: relative; } |
| +добавлено | .kb-col { |
| +добавлено | flex: 1 0 clamp(176px, calc(50vw - 16px), 236px); max-width: 360px; display: flex; flex-direction: column; border-radius: 12px; background: var(--zt-surface); |
| +добавлено | border: 1px solid transparent; transition: background-color .15s var(--ease), border-color .15s var(--ease); |
| +добавлено | } |
| +добавлено | @media (min-width: 680px) { .kb-col { flex-basis: 160px; } } |
| +добавлено | .kb-col.hot { background: var(--zt-hover); border-color: var(--zt-border-hover); } |
| +добавлено | .kb-col-h { display: flex; align-items: center; gap: 6px; padding: 9px 10px 6px; font-size: 12px; font-weight: 600; color: var(--zt-fg2); } |
| +добавлено | .kb-col-h .cnt { color: var(--zt-fg3); font-weight: 500; } |
| +добавлено | .kb-col-h .st { width: 8px; height: 8px; border-radius: 50%; border: 1.75px solid currentColor; flex: none; } |
| +добавлено | .kb-col-h .st.todo { color: var(--zt-fg3); } |
| +добавлено | .kb-col-h .st.doing { color: var(--zt-warning); border-style: solid; border-right-color: transparent; } |
| +добавлено | .kb-col-h .st.review { color: var(--zt-brand); } |
| +добавлено | html.light .kb-col-h .st.review { color: #0ea5e9; } |
| +добавлено | .kb-col-h .st.done { color: var(--zt-success); background: var(--zt-success); } |
| +добавлено | .kb-list { display: flex; flex-direction: column; gap: 6px; padding: 2px 6px 6px; min-height: 40px; } |
| +добавлено | .kcard { |
| +добавлено | position: relative; background: var(--zt-card); border: 1px solid var(--zt-border); border-radius: 10px; padding: 8px 10px 8px; |
| +добавлено | cursor: grab; touch-action: none; transition: border-color .12s var(--ease), background-color .12s var(--ease), opacity .12s; |
| +добавлено | display: flex; flex-direction: column; gap: 6px; |
| +добавлено | } |
| +добавлено | .kcard.ro { cursor: pointer; touch-action: auto; } |
| +добавлено | .kcard:hover { border-color: var(--zt-border-hover); } |
| +добавлено | .kcard .ttl { font-size: 12.5px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word; color: var(--zt-fg); } |
| +добавлено | .kcard .meta { display: flex; align-items: center; gap: 6px; min-height: 20px; flex-wrap: wrap; } |
| +добавлено | .kcard .sid { font-family: var(--mono); font-size: 10.5px; color: var(--zt-fg3); border: 0; background: none; padding: 0; border-radius: 4px; } |
| +добавлено | .kcard .sid:hover { color: var(--zt-fg); } |
| +добавлено | .kcard .due { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--zt-fg2); } |
| +добавлено | .kcard .due.over { color: #f87171; } |
| +добавлено | .kcard .flag { display: inline-flex; color: var(--zt-fg3); } |
| +добавлено | .kcard .flag.urgent { color: var(--zt-danger); } |
| +добавлено | .kcard .flag.high { color: var(--zt-orange); } |
| +добавлено | .kcard .flag.low { color: var(--zt-fg3); } |
| +добавлено | .kcard .labels { display: flex; gap: 4px; flex-wrap: wrap; } |
| +добавлено | .kcard .av { margin-left: auto; } |
| +добавлено | .kcard.prio-urgent::before, .kcard.prio-high::before { content: ""; position: absolute; left: -1px; top: 8px; bottom: 8px; width: 2px; border-radius: 2px; background: var(--zt-danger); } |
| +добавлено | .kcard.prio-high::before { background: var(--zt-orange); } |
| +добавлено | .kb-ph { border-radius: 10px; border: 1.5px dashed var(--zt-border-hover); background: var(--zt-surface); flex: none; } |
| +добавлено | .kb-ghost { |
| +добавлено | position: fixed; z-index: 80; pointer-events: none; margin: 0; cursor: grabbing; |
| +добавлено | box-shadow: var(--zt-shadow-lift); border-color: var(--zt-border-hover); background: var(--zt-card); |
| +добавлено | transition: none; will-change: transform; |
| +добавлено | } |
| +добавлено | .kb-ghost.lift { animation: lift .16s var(--ease) forwards; } |
| +добавлено | @keyframes lift { from { scale: 1; rotate: 0deg; } to { scale: 1.02; rotate: .6deg; } } |
| +добавлено | .kb-ghost.drop { transition: transform .18s var(--ease), scale .18s var(--ease), rotate .18s var(--ease); scale: 1; rotate: 0deg; animation: none; } |
| +добавлено | body.dragging, body.dragging * { cursor: grabbing !important; user-select: none !important; } |
| +добавлено | .kb-add { display: flex; align-items: center; gap: 6px; width: 100%; height: 30px; padding: 0 8px; border: 0; border-radius: 8px; background: transparent; color: var(--zt-fg3); font-size: 12px; text-align: left; transition: background-color .12s, color .12s; } |
| +добавлено | .kb-add:hover { background: var(--zt-hover); color: var(--zt-fg); } |
| +добавлено | .kb-quick { padding: 0 6px 6px; } |
| +добавлено | .kb-quick .inp { height: 30px; font-size: 12.5px; } |
| +добавлено | .flip-anim { transition: transform .2s var(--ease); } |
| +добавлено | .kb-empty-col { font-size: 11.5px; color: var(--zt-fg3); padding: 8px 4px; text-align: center; } |
| +добавлено | |
| +добавлено | /* ---------- задача (шторка) ---------- */ |
| +добавлено | .title-edit { width: 100%; border: 1px solid transparent; background: transparent; font-size: 16px; font-weight: 600; padding: 4px 6px; margin: -4px -6px; border-radius: 8px; resize: none; overflow: hidden; line-height: 1.35; color: var(--zt-fg); } |
| +добавлено | .title-edit:hover { background: var(--zt-surface); } |
| +добавлено | .title-edit:focus { border-color: var(--zt-brand); background: var(--zt-surface); outline: none; } |
| +добавлено | .props { display: grid; grid-template-columns: 96px 1fr; gap: 8px 10px; align-items: center; } |
| +добавлено | .props > .k { color: var(--zt-fg2); font-size: 12px; } |
| +добавлено | .labels-ed { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; min-height: 32px; padding: 3px 4px; border-radius: 8px; border: 1px solid var(--zt-border); background: var(--zt-surface); } |
| +добавлено | .labels-ed:focus-within { border-color: var(--zt-brand); box-shadow: 0 0 0 1px var(--zt-brand); } |
| +добавлено | .labels-ed .tag { height: 22px; gap: 3px; padding-right: 2px; } |
| +добавлено | .labels-ed .tag button { border: 0; background: none; padding: 0; color: var(--zt-fg2); display: grid; place-items: center; border-radius: 4px; } |
| +добавлено | .labels-ed .tag button:hover { color: var(--zt-fg); } |
| +добавлено | .labels-ed input { flex: 1; min-width: 70px; border: 0; background: transparent; outline: none; height: 24px; font-size: 12.5px; padding: 0 4px; } |
| +добавлено | .timeline { position: relative; display: flex; flex-direction: column; gap: 10px; padding-left: 16px; } |
| +добавлено | .timeline::before { content: ""; position: absolute; left: 4px; top: 4px; bottom: 4px; width: 1px; background: var(--zt-border); } |
| +добавлено | .tl-item { position: relative; font-size: 12px; } |
| +добавлено | .tl-item::before { content: ""; position: absolute; left: -15px; top: 5px; width: 7px; height: 7px; border-radius: 50%; background: var(--zt-tag); border: 1px solid var(--zt-border-hover); } |
| +добавлено | .tl-item .when { color: var(--zt-fg3); font-size: 11px; } |
| +добавлено | |
| +добавлено | /* ---------- ключи ---------- */ |
| +добавлено | .key-card { padding: 12px; display: flex; flex-direction: column; gap: 8px; border-top: 1px solid var(--zt-border); } |
| +добавлено | .key-card:first-child { border-top: 0; } |
| +добавлено | .key-card.off { opacity: .55; } |
| +добавлено | .models { display: flex; flex-wrap: wrap; gap: 4px; } |
| +добавлено | .model-chip { display: inline-flex; align-items: center; height: 20px; padding: 0 7px; border-radius: 6px; background: var(--zt-surface); border: 1px solid var(--zt-border); font-family: var(--mono); font-size: 11px; color: var(--zt-fg2); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +добавлено | label.model-chip { cursor: pointer; gap: 6px; height: 24px; } |
| +добавлено | label.model-chip.on { color: var(--zt-fg); border-color: var(--zt-border-hover); background: var(--zt-hover); } |
| +добавлено | label.model-chip .chk { width: 13px; height: 13px; } |
| +добавлено | label.model-chip .chk:checked::after { width: 8px; height: 8px; } |
| +добавлено | .bars { display: flex; align-items: flex-end; gap: 3px; height: 64px; } |
| +добавлено | .bars .bar { flex: 1; min-width: 4px; background: var(--zt-tag); border-radius: 3px 3px 1px 1px; transform-origin: bottom; animation: grow .4s var(--ease) both; position: relative; } |
| +добавлено | .bars .bar.today { background: var(--zt-brand); } |
| +добавлено | .bars .bar:hover { background: var(--zt-fg3); } |
| +добавлено | @keyframes grow { from { transform: scaleY(0); } to { transform: none; } } |
| +добавлено | .meter { display: flex; flex-direction: column; gap: 4px; } |
| +добавлено | .meter .row { font-size: 11.5px; } |
| +добавлено | .reveal-box { display: flex; align-items: center; gap: 6px; padding: 6px 6px 6px 10px; border-radius: 8px; background: var(--zt-surface); border: 1px dashed var(--zt-border-hover); } |
| +добавлено | .reveal-box .mono { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +добавлено | |
| +добавлено | /* ---------- файлы ---------- */ |
| +добавлено | .dropzone { |
| +добавлено | display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 18px 12px; text-align: center; |
| +добавлено | border: 1.5px dashed var(--zt-border-hover); border-radius: 12px; background: var(--zt-surface); color: var(--zt-fg2); |
| +добавлено | transition: border-color .15s var(--ease), background-color .15s var(--ease); |
| +добавлено | } |
| +добавлено | .dropzone.hot { border-color: var(--zt-brand); background: rgba(14, 165, 233, .07); } |
| +добавлено | .drop-overlay { |
| +добавлено | position: absolute; inset: 6px; z-index: 30; border-radius: 14px; border: 2px dashed var(--zt-brand); |
| +добавлено | background: color-mix(in srgb, var(--zt-bg) 82%, transparent); display: grid; place-items: center; pointer-events: none; |
| +добавлено | animation: fadeIn .16s var(--ease); backdrop-filter: blur(2px); |
| +добавлено | } |
| +добавлено | .drop-overlay .inner { display: flex; flex-direction: column; align-items: center; gap: 8px; font-weight: 600; } |
| +добавлено | .file-ic { width: 32px; height: 32px; border-radius: 8px; display: grid; place-items: center; background: var(--zt-surface); border: 1px solid var(--zt-border); color: var(--zt-fg2); flex: none; } |
| +добавлено | |
| +добавлено | /* ---------- git ---------- */ |
| +добавлено | .git-top { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--zt-border); } |
| +добавлено | .branch-pill { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; border-radius: 999px; background: var(--zt-hover); font-size: 12.5px; font-weight: 500; min-width: 0; max-width: 100%; } |
| +добавлено | .branch-pill .ab { display: inline-flex; align-items: center; gap: 1px; color: var(--zt-fg2); font-size: 11.5px; } |
| +добавлено | .git-sec-h { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 6px; padding: 6px 8px 6px 12px; min-height: 32px; background: var(--zt-bg); font-size: 12px; font-weight: 600; color: var(--zt-fg2); } |
| +добавлено | .git-sec-h .ibtn { opacity: 0; transition: opacity .12s; } |
| +добавлено | .git-sec-h:hover .ibtn, .git-sec-h:focus-within .ibtn { opacity: 1; } |
| +добавлено | .git-file { display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 6px 0 12px; font-size: 12.5px; cursor: pointer; transition: background-color .12s var(--ease); min-width: 0; } |
| +добавлено | .git-file:hover, .git-file:focus-visible { background: var(--zt-surface); } |
| +добавлено | .git-file.sel { background: var(--zt-selected); } |
| +добавлено | .git-file .nm { white-space: nowrap; flex: none; max-width: 70%; overflow: hidden; text-overflow: ellipsis; } |
| +добавлено | .git-file .dir { color: var(--zt-fg3); font-size: 11.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; direction: rtl; text-align: left; } |
| +добавлено | .git-file .acts { display: flex; gap: 0; opacity: 0; transition: opacity .12s; } |
| +добавлено | .git-file:hover .acts, .git-file:focus-within .acts { opacity: 1; } |
| +добавлено | .st-badge { width: 16px; text-align: center; font-family: var(--mono); font-size: 11px; font-weight: 700; flex: none; } |
| +добавлено | .st-M { color: #eab308; } .st-A { color: #22c55e; } .st-D { color: #ef4444; } .st-R { color: #38bdf8; } .st-U { color: #a3e635; } .st-C { color: #f97316; } |
| +добавлено | html.light .st-M { color: #a16207; } html.light .st-A { color: #15803d; } html.light .st-R { color: #0369a1; } html.light .st-U { color: #4d7c0f; } |
| +добавлено | .commit-box { position: sticky; bottom: 0; z-index: 3; padding: 10px 12px 12px; background: var(--zt-bg); border-top: 1px solid var(--zt-border); display: flex; flex-direction: column; gap: 8px; } |
| +добавлено | .commit-box .ta { min-height: 56px; max-height: 160px; overflow: auto; font-size: 12.5px; } |
| +добавлено | .cnt72 { font-family: var(--mono); font-size: 11px; color: var(--zt-fg3); } |
| +добавлено | .cnt72.over { color: var(--zt-warning); } |
| +добавлено | .diff { font-family: var(--mono); font-size: 12px; line-height: 1.55; overflow: auto; background: var(--zt-card); border: 1px solid var(--zt-border); border-radius: 10px; } |
| +добавлено | .diff table { border-collapse: collapse; min-width: 100%; } |
| +добавлено | .diff td { padding: 0 10px 0 0; white-space: pre; vertical-align: top; } |
| +добавлено | .diff td.ln { width: 1%; min-width: 38px; padding: 0 6px; text-align: right; color: var(--zt-fg3); user-select: none; border-right: 1px solid var(--zt-border); } |
| +добавлено | .diff td.sg { width: 1%; padding: 0 4px 0 8px; user-select: none; color: var(--zt-fg3); } |
| +добавлено | .diff tr.add { background: var(--zt-diff-add); } |
| +добавлено | .diff tr.add td.sg, .diff tr.add td.code { color: var(--zt-diff-add-fg); } |
| +добавлено | .diff tr.del { background: var(--zt-diff-del); } |
| +добавлено | .diff tr.del td.sg, .diff tr.del td.code { color: var(--zt-diff-del-fg); } |
| +добавлено | .diff tr.hunk td { background: var(--zt-diff-hunk); color: var(--zt-fg2); padding-top: 3px; padding-bottom: 3px; } |
| +добавлено | .diff tr.fhead td { background: var(--zt-surface); color: var(--zt-fg); font-weight: 600; padding: 6px 10px; border-top: 1px solid var(--zt-border); border-bottom: 1px solid var(--zt-border); position: sticky; left: 0; } |
| +добавлено | .diff tr.meta td { color: var(--zt-fg3); } |
| +добавлено | .graph { position: relative; } |
| +добавлено | .commit-row { position: relative; display: flex; align-items: flex-start; gap: 10px; padding: 7px 12px 7px 34px; cursor: pointer; transition: background-color .12s; } |
| +добавлено | .commit-row:hover, .commit-row:focus-visible { background: var(--zt-surface); } |
| +добавлено | .commit-row::before { content: ""; position: absolute; left: 17px; top: 0; bottom: 0; width: 2px; background: var(--zt-border-hover); opacity: .55; } |
| +добавлено | .commit-row:first-child::before { top: 14px; } |
| +добавлено | .commit-row:last-child::before { bottom: calc(100% - 14px); } |
| +добавлено | .commit-row .node { position: absolute; left: 12px; top: 10px; width: 12px; height: 12px; border-radius: 50%; background: var(--zt-bg); border: 2px solid var(--zt-fg2); } |
| +добавлено | .commit-row.head .node { border-color: var(--zt-brand); background: var(--zt-brand); } |
| +добавлено | .commit-row.merge .node { border-color: #a78bfa; width: 12px; height: 12px; border-radius: 3px; transform: rotate(45deg); } |
| +добавлено | .commit-row .subj { font-size: 12.5px; color: var(--zt-fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| +добавлено | .commit-row .sub { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--zt-fg3); margin-top: 2px; min-width: 0; } |
| +добавлено | .ref { display: inline-flex; align-items: center; gap: 3px; height: 17px; padding: 0 6px; border-radius: 5px; font-size: 10.5px; font-weight: 500; background: var(--zt-hover); color: var(--zt-fg2); white-space: nowrap; flex: none; } |
| +добавлено | .ref.head { background: rgba(14, 165, 233, .18); color: #38bdf8; } |
| +добавлено | .ref.tag { background: rgba(234, 179, 8, .14); color: #facc15; } |
| +добавлено | .ref.remote { background: rgba(167, 139, 250, .14); color: #c4b5fd; } |
| +добавлено | html.light .ref.head { color: #0369a1; } html.light .ref.tag { color: #a16207; } html.light .ref.remote { color: #6d28d9; } |
| +добавлено | .stat-add { color: var(--zt-diff-add-fg); font-family: var(--mono); font-size: 11.5px; } |
| +добавлено | .stat-del { color: var(--zt-diff-del-fg); font-family: var(--mono); font-size: 11.5px; } |
| +добавлено | .subtabs { display: flex; gap: 2px; } |
| +добавлено | |
| +добавлено | /* ---------- профиль ---------- */ |
| +добавлено | .palette { display: flex; flex-wrap: wrap; gap: 8px; } |
| +добавлено | .swatch { width: 26px; height: 26px; border-radius: 50%; border: 2px solid transparent; padding: 0; cursor: pointer; transition: transform .12s var(--ease); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .15); } |
| +добавлено | .swatch:hover { transform: scale(1.08); } |
| +добавлено | .swatch[aria-pressed="true"] { box-shadow: 0 0 0 2px var(--zt-bg), 0 0 0 4px var(--zt-fg); } |
| +добавлено | .profile-hero { display: flex; align-items: center; gap: 14px; } |
| +добавлено | |
| +добавлено | .legend { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; } |
| +добавлено | .legend .d { color: var(--zt-fg2); } |
| +добавлено | .invite-code { font-family: var(--mono); font-size: 22px; letter-spacing: .1em; font-weight: 600; padding: 12px; border-radius: 10px; background: var(--zt-surface); border: 1px dashed var(--zt-border-hover); display: flex; align-items: center; gap: 10px; justify-content: center; } |
| +добавлено | .danger-zone { border-color: rgba(239, 68, 68, .3); } |
| +добавлено | .kbd { font-family: var(--mono); font-size: 10.5px; padding: 1px 5px; border-radius: 4px; border: 1px solid var(--zt-border); background: var(--zt-surface); color: var(--zt-fg2); } |
| +добавлено | |
| +добавлено | @media (prefers-reduced-motion: reduce) { |
| +добавлено | *, *::before, *::after { animation-duration: 1ms !important; animation-iteration-count: 1 !important; transition-duration: 1ms !important; } |
| +добавлено | .skel::after { animation: none; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | /* Слои получают программный фокус — без рамки вокруг всей шторки. */ |
| +добавлено | .drawer:focus-visible, .sheet:focus-visible, .dialog:focus-visible { outline: none; } |
| +добавлено | var n,l,u,t,i,r,o,e,f,c,a,s,h,p,v,y,d={},w=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function m(n,l){for(var u in l)n[u]=l[u];return n}function b(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function k(l,u,t){var i,r,o,e={};for(o in u)"key"==o?i=u[o]:"ref"==o?r=u[o]:e[o]=u[o];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===e[o]&&(e[o]=l.defaultProps[o]);return x(l,e,i,r,null)}function x(n,t,i,r,o){var e={type:n,props:t,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++u:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(e),e}function M(){return{current:null}}function S(n){return n.children}function C(n,l){this.props=n,this.context=l}function $(n,l){if(null==l)return n.__?$(n.__,n.__i+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return"function"==typeof n.type?$(n):null}function I(n){if(n.__P&&n.__d){var u=n.__v,t=u.__e,i=[],r=[],o=m({},u);o.__v=u.__v+1,l.vnode&&l.vnode(o),q(n.__P,o,u,n.__n,n.__P.namespaceURI,32&u.__u?[t]:null,i,null==t?$(u):t,!!(32&u.__u),r),o.__v=u.__v,o.__.__k[o.__i]=o,D(i,o,r),u.__e=u.__=null,o.__e!=t&&P(o)}}function P(n){if(null!=(n=n.__)&&null!=n.__c)return n.__e=n.__c.base=null,n.__k.some(function(l){if(null!=l&&null!=l.__e)return n.__e=n.__c.base=l.__e}),P(n)}function A(n){(!n.__d&&(n.__d=!0)&&i.push(n)&&!H.__r++||r!=l.debounceRendering)&&((r=l.debounceRendering)||o)(H)}function H(){try{for(var n,l=1;i.length;)i.length>l&&i.sort(e),n=i.shift(),l=i.length,I(n)}finally{i.length=H.__r=0}}function L(n,l,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,_,g=t&&t.__k||w,m=l.length;for(f=T(u,l,g,f,m),s=0;s<m;s++)null!=(p=u.__k[s])&&(h=-1!=p.__i&&g[p.__i]||d,p.__i=s,_=q(n,p,h,i,r,o,e,f,c,a),v=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&J(h.ref,null,p),a.push(p.ref,p.__c||v,p)),null==y&&null!=v&&(y=v),4&p.__u?(f=j(p,f,n),h.__e&&(h.__e=null)):"function"==typeof p.type&&void 0!==_?f=_:v&&(f=v.nextSibling),p.__u&=-7);return u.__e=y,f}function T(n,l,u,t,i){var r,o,e,f,c,a=u.length,s=a,h=0;for(n.__k=new Array(i),r=0;r<i;r++)null!=(o=l[r])&&"boolean"!=typeof o&&"function"!=typeof o?("string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?o=n.__k[r]=x(null,o,null,null,null):g(o)?o=n.__k[r]=x(S,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?o=n.__k[r]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[r]=o,f=r+h,o.__=n,o.__b=n.__b+1,e=null,-1!=(c=o.__i=O(o,u,f,s))&&(s--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>a?h--:i<a&&h++),"function"!=typeof o.type&&(o.__u|=4)):c!=f&&(c==f-1?h--:c==f+1?h++:(c>f?h--:h++,o.__u|=4))):n.__k[r]=null;if(s)for(r=0;r<a;r++)null!=(e=u[r])&&0==(2&e.__u)&&(e.__e==t&&(t=$(e)),K(e,e));return t}function j(n,l,u){var t,i;if("function"==typeof n.type){for(t=n.__k,i=0;t&&i<t.length;i++)t[i]&&(t[i].__=n,l=j(t[i],l,u));return l}n.__e!=l&&(l&&n.type&&!l.parentNode&&(l=$(n)),l=u.insertBefore(n.__e,l||null));do{l=l&&l.nextSibling}while(null!=l&&8==l.nodeType);return l}function F(n,l){return l=l||[],null==n||"boolean"==typeof n||(g(n)?n.some(function(n){F(n,l)}):l.push(n)),l}function O(n,l,u,t){var i,r,o,e=n.key,f=n.type,c=l[u],a=null!=c&&0==(2&c.__u);if(null===c&&null==e||a&&e==c.key&&f==c.type)return u;if(t>(a?1:0))for(i=u-1,r=u+1;i>=0||r<l.length;)if(null!=(c=l[o=i>=0?i--:r++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return o;return-1}function z(n,l,u){"-"==l[0]?n.setProperty(l,null==u?"":u):n[l]=null==u?"":"number"!=typeof u||_.test(l)?u:u+"px"}function N(n,l,u,t,i){var r,o;n:if("style"==l)if("string"==typeof u)n.style.cssText=u;else{if("string"==typeof t&&(n.style.cssText=t=""),t)for(l in t)u&&l in u||z(n.style,l,"");if(u)for(l in u)t&&u[l]==t[l]||z(n.style,l,u[l])}else if("o"==l[0]&&"n"==l[1])r=l!=(l=l.replace(s,"$1")),o=l.toLowerCase(),l=o in n||"onFocusOut"==l||"onFocusIn"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=u,u?t?u[a]=t[a]:(u[a]=h,n.addEventListener(l,r?v:p,r)):n.removeEventListener(l,r?v:p,r);else{if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==u?"":u;break n}catch(n){}"function"==typeof u||(null==u||!1===u&&"-"!=l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==u?"":u))}}function V(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u[c])u[c]=h++;else if(u[c]<t[a])return;return t(l.event?l.event(u):u)}}}function q(n,u,t,i,r,o,e,f,c,a){var s,h,p,v,y,d,_,k,x,M,I,P,A,H,T,j,F=u.type;if(void 0!==u.constructor)return null;128&t.__u&&(c=!!(32&t.__u),o=[f=u.__e=t.__e]),(s=l.__b)&&s(u);n:if("function"==typeof F){h=e.length;try{if(x=u.props,M=F.prototype&&F.prototype.render,I=(s=F.contextType)&&i[s.__c],P=s?I?I.props.value:s.__:i,t.__c?k=(p=u.__c=t.__c).__=p.__E:(M?u.__c=p=new F(x,P):(u.__c=p=new C(x,P),p.constructor=F,p.render=Q),I&&I.sub(p),p.state||(p.state={}),p.__n=i,v=p.__d=!0,p.__h=[],p._sb=[]),M&&null==p.__s&&(p.__s=p.state),M&&null!=F.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=m({},p.__s)),m(p.__s,F.getDerivedStateFromProps(x,p.__s))),y=p.props,d=p.state,p.__v=u,v)M&&null==F.getDerivedStateFromProps&&null!=p.componentWillMount&&p.componentWillMount(),M&&null!=p.componentDidMount&&p.__h.push(p.componentDidMount);else{if(M&&null==F.getDerivedStateFromProps&&x!==y&&null!=p.componentWillReceiveProps&&p.componentWillReceiveProps(x,P),u.__v==t.__v||!p.__e&&null!=p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(x,p.__s,P)){u.__v!=t.__v&&(p.props=x,p.state=p.__s,p.__d=!1),u.__e=t.__e,u.__k=t.__k,u.__k.some(function(n){n&&(n.__=u)}),w.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&e.push(p),f=$(t);break n}null!=p.componentWillUpdate&&p.componentWillUpdate(x,p.__s,P),M&&null!=p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(y,d,_)})}if(p.context=P,p.props=x,p.__P=n,p.__e=!1,A=l.__r,H=0,M)p.state=p.__s,p.__d=!1,A&&A(u),s=p.render(p.props,p.state,p.context),w.push.apply(p.__h,p._sb),p._sb=[];else do{p.__d=!1,A&&A(u),s=p.render(p.props,p.state,p.context),p.state=p.__s}while(p.__d&&++H<25);p.state=p.__s,null!=p.getChildContext&&(i=m(m({},i),p.getChildContext())),M&&!v&&null!=p.getSnapshotBeforeUpdate&&(_=p.getSnapshotBeforeUpdate(y,d)),T=null!=s&&s.type===S&&null==s.key?E(s.props.children):s,f=L(n,g(T)?T:[T],u,t,i,r,o,e,f,c,a),p.base=u.__e,u.__u&=-161,p.__h.length&&e.push(p),k&&(p.__E=p.__=null)}catch(n){if(e.length=h,u.__v=null,c||null!=o){if(n.then){for(u.__u|=c?160:128;f&&8==f.nodeType&&f.nextSibling;)f=f.nextSibling;null!=o&&(o[o.indexOf(f)]=null),u.__e=f}else if(null!=o)for(j=o.length;j--;)b(o[j])}else u.__e=t.__e;null==u.__k&&(u.__k=t.__k||[]),n.then||B(u),l.__e(n,u,t)}}else null==o&&u.__v==t.__v?(u.__k=t.__k,u.__e=t.__e):f=u.__e=G(t.__e,u,t,i,r,o,e,c,a);return(s=l.diffed)&&s(u),128&u.__u?void 0:f}function B(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(B))}function D(n,u,t){for(var i=0;i<t.length;i++)J(t[i],t[++i],t[++i]);l.__c&&l.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u)})}catch(n){l.__e(n,u.__v)}})}function E(n){return"object"!=typeof n||null==n||n.__b>0?n:g(n)?n.map(E):void 0!==n.constructor?null:m({},n)}function G(u,t,i,r,o,e,f,c,a){var s,h,p,v,y,w,_,m=i.props||d,k=t.props,x=t.type;if("svg"==x?o="http://www.w3.org/2000/svg":"math"==x?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),null!=e)for(s=0;s<e.length;s++)if((y=e[s])&&"setAttribute"in y==!!x&&(x?y.localName==x:3==y.nodeType)){u=y,e[s]=null;break}if(null==u){if(null==x)return document.createTextNode(k);u=document.createElementNS(o,x,k.is&&k),c&&(l.__m&&l.__m(t,e),c=!1),e=null}if(null==x)m===k||c&&u.data==k||(u.data=k);else{if(e="textarea"==x&&null!=k.defaultValue?null:e&&n.call(u.childNodes),!c&&null!=e)for(m={},s=0;s<u.attributes.length;s++)m[(y=u.attributes[s]).name]=y.value;for(s in m)y=m[s],"dangerouslySetInnerHTML"==s?p=y:"children"==s||s in k||"value"==s&&"defaultValue"in k||"checked"==s&&"defaultChecked"in k||N(u,s,null,y,o);for(s in k)y=k[s],"children"==s?v=y:"dangerouslySetInnerHTML"==s?h=y:"value"==s?w=y:"checked"==s?_=y:c&&"function"!=typeof y||m[s]===y||N(u,s,y,m[s],o);if(h)c||p&&(h.__html==p.__html||h.__html==u.innerHTML)||(u.innerHTML=h.__html),t.__k=[];else if(p&&(u.innerHTML=""),L("template"==t.type?u.content:u,g(v)?v:[v],t,i,r,"foreignObject"==x?"http://www.w3.org/1999/xhtml":o,e,f,e?e[0]:i.__k&&$(i,0),c,a),null!=e)for(s=e.length;s--;)b(e[s]);c&&"textarea"!=x||(s="value","progress"==x&&null==w?u.removeAttribute("value"):null!=w&&(w!==u[s]||"progress"==x&&!w||"option"==x&&w!=m[s])&&N(u,s,w,m[s],o),s="checked",null!=_&&_!=u[s]&&N(u,s,_,m[s],o))}return u}function J(n,u,t){try{if("function"==typeof n){var i="function"==typeof n.__u;i&&n.__u(),i&&null==u||(n.__u=n(u))}else n.current=u}catch(n){l.__e(n,t)}}function K(n,u,t){var i,r;if(l.unmount&&l.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||J(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(n){l.__e(n,u)}i.base=i.__P=i.__n=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&K(i[r],u,t||"function"!=typeof n.type);t||b(n.__e),n.__c=n.__=n.__e=void 0}function Q(n,l,u){return this.constructor(n,u)}function R(u,t,i){var r,o,e,f;t==document&&(t=document.documentElement),l.__&&l.__(u,t),o=(r="function"==typeof i)?null:i&&i.__k||t.__k,e=[],f=[],q(t,u=(!r&&i||t).__k=k(S,null,[u]),o||d,d,t.namespaceURI,!r&&i?[i]:o?null:t.firstChild?n.call(t.childNodes):null,e,!r&&i?i:o?o.__e:t.firstChild,r,f),D(e,u,f),u.props.children=null}function U(n,l){R(n,l,U)}function W(l,u,t){var i,r,o,e,f=m({},l.props);for(o in l.type&&l.type.defaultProps&&(e=l.type.defaultProps),u)"key"==o?i=u[o]:"ref"==o?r=u[o]:f[o]=void 0===u[o]&&null!=e?e[o]:u[o];return arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),x(l.type,f,i||l.key,r||l.ref,null)}function X(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,A(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c="__cC"+y++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=w.slice,l={__e:function(n,l,u,t){for(var i,r,o;l=l.__;)if((i=l.__c)&&!i.__)try{if((r=i.constructor)&&null!=r.getDerivedStateFromError&&(i.setState(r.getDerivedStateFromError(n)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),o=i.__d),o)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},C.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),"function"==typeof n&&(n=n(m({},u),this.props)),n&&m(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),A(this))},C.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),A(this))},C.prototype.render=S,i=[],o="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},H.__r=0,f=Math.random().toString(8),c="__d"+f,a="__a"+f,s=/(PointerCapture)$|Capture$/i,h=0,p=V(!1),v=V(!0),y=0;export{C as Component,S as Fragment,W as cloneElement,X as createContext,k as createElement,M as createRef,k as h,U as hydrate,t as isValidElement,l as options,R as render,F as toChildArray}; |
| +добавлено |
| +добавлено | // Вкладка «Файлы»: передача файлов через сервер команды и архивы проектов. |
| +добавлено | import { Fragment } from 'preact'; |
| +добавлено | import { useEffect, useMemo, useRef, useState } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, useRes, invalidate, mutateRes, humanError, svc, roleAtLeast, relTime, fmtDateTime, |
| +добавлено | humanBytes, plural, saveUi, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon, fileIconFor } from './icons.js'; |
| +добавлено | import { Avatar, Select, Empty, SkelList, AsyncButton, Field, MenuButton, confirmDialog, Seg, Layer } from './ui.js'; |
| +добавлено | import { keyFor, myRole, me } from './app-state.js'; |
| +добавлено | |
| +добавлено | let uploadSeq = 0; |
| +добавлено | |
| +добавлено | function uploadXhr({ file, kind, teamId, recipientId, note, projectName, onProgress }) { |
| +добавлено | const xhr = new XMLHttpRequest(); |
| +добавлено | const qs = new URLSearchParams({ kind, teamId: teamId || '' }); |
| +добавлено | if (recipientId) qs.set('recipientId', recipientId); |
| +добавлено | if (note) qs.set('note', note); |
| +добавлено | if (projectName) qs.set('projectName', projectName); |
| +добавлено | const promise = new Promise((resolve, reject) => { |
| +добавлено | xhr.open('POST', '/upload?' + qs.toString()); |
| +добавлено | xhr.setRequestHeader('X-ZTeam-CSRF', svc.csrf); |
| +добавлено | xhr.setRequestHeader('X-File-Name', encodeURIComponent(file.name)); |
| +добавлено | xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream'); |
| +добавлено | xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); }; |
| +добавлено | xhr.onload = () => { |
| +добавлено | let body = null; |
| +добавлено | try { body = JSON.parse(xhr.responseText); } catch { /* ignore */ } |
| +добавлено | if (xhr.status >= 200 && xhr.status < 300) resolve(body); |
| +добавлено | else reject(Object.assign(new Error(body?.error || 'HTTP ' + xhr.status), { status: xhr.status })); |
| +добавлено | }; |
| +добавлено | xhr.onerror = () => reject(new Error('Сеть недоступна')); |
| +добавлено | xhr.onabort = () => reject(Object.assign(new Error('Отменено'), { aborted: true })); |
| +добавлено | xhr.send(file); |
| +добавлено | }); |
| +добавлено | return { xhr, promise }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function useUploads(s) { |
| +добавлено | const [items, setItems] = useState([]); // {id,file,kind,progress,status:'up'|'done'|'err'|'cancel',error,xhr,opts} |
| +добавлено | const patch = (id, p) => setItems((list) => list.map((x) => (x.id === id ? { ...x, ...p } : x))); |
| +добавлено | const start = (file, opts) => { |
| +добавлено | const id = ++uploadSeq; |
| +добавлено | const { xhr, promise } = uploadXhr({ file, ...opts, teamId: s.teamId, onProgress: (p) => patch(id, { progress: p }) }); |
| +добавлено | setItems((list) => [...list, { id, file, progress: 0, status: 'up', xhr, opts }]); |
| +добавлено | promise.then(() => { |
| +добавлено | patch(id, { status: 'done', progress: 1 }); |
| +добавлено | invalidate(opts.kind === 'archive' ? 'archives' : 'files'); |
| +добавлено | setTimeout(() => setItems((list) => list.filter((x) => x.id !== id)), 1600); |
| +добавлено | }, (e) => { |
| +добавлено | if (e.aborted) { setItems((list) => list.filter((x) => x.id !== id)); return; } |
| +добавлено | patch(id, { status: 'err', error: e.status === 403 ? 'Недостаточно прав' : e.status === 413 ? 'Файл слишком большой' : humanError(e) }); |
| +добавлено | }); |
| +добавлено | }; |
| +добавлено | const cancel = (id) => { const it = items.find((x) => x.id === id); it?.xhr?.abort(); }; |
| +добавлено | const retry = (id) => { |
| +добавлено | const it = items.find((x) => x.id === id); |
| +добавлено | if (!it) return; |
| +добавлено | setItems((list) => list.filter((x) => x.id !== id)); |
| +добавлено | start(it.file, it.opts); |
| +добавлено | }; |
| +добавлено | const dismiss = (id) => setItems((list) => list.filter((x) => x.id !== id)); |
| +добавлено | return { items, start, cancel, retry, dismiss }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function UploadRow({ it, onCancel, onRetry, onDismiss }) { |
| +добавлено | const pct = Math.round(it.progress * 100); |
| +добавлено | return html`<div class="li enter-item" style="align-items:flex-start;padding-top:10px;padding-bottom:10px"> |
| +добавлено | <span class="file-ic"><${Icon} name=${fileIconFor(it.file.name)} size=${15} /></span> |
| +добавлено | <div class="grow stack-s" style="gap:5px"> |
| +добавлено | <div class="row"><span class="ell grow">${it.file.name}</span> |
| +добавлено | <span class=${'xs ' + (it.status === 'err' ? 'danger-t' : it.status === 'done' ? 'ok-t' : 'faint')}>${it.status === 'err' ? 'ошибка' : it.status === 'done' ? 'готово' : pct + '%'}</span></div> |
| +добавлено | <div class=${'progress' + (it.status === 'err' ? ' err' : it.status === 'done' ? ' ok' : '')}><i style=${{ transform: `scaleX(${it.status === 'err' ? 1 : it.progress})` }}></i></div> |
| +добавлено | <div class="faint xs">${it.status === 'err' ? html`<span class="danger-t">${it.error}</span>` : `${humanBytes(it.file.size * it.progress)} из ${humanBytes(it.file.size)}`}</div> |
| +добавлено | </div> |
| +добавлено | ${it.status === 'up' ? html`<button type="button" class="ibtn sm" title="Отменить" aria-label=${'Отменить загрузку ' + it.file.name} onClick=${onCancel}><${Icon} name="x" size=${14} /></button>` : null} |
| +добавлено | ${it.status === 'err' ? html`<${Fragment}><button type="button" class="ibtn sm" title="Повторить" aria-label="Повторить" onClick=${onRetry}><${Icon} name="refresh" size=${14} /></button> |
| +добавлено | <button type="button" class="ibtn sm" title="Убрать" aria-label="Убрать" onClick=${onDismiss}><${Icon} name="x" size=${14} /></button><//>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function download(s, method, params, name) { |
| +добавлено | const [r, err] = await act(method, { teamId: s.teamId, ...params }); |
| +добавлено | if (err || !r) return; |
| +добавлено | toast(html`Сохранено: <b>${r.name || name}</b>`, { kind: 'ok', timeout: 6000, action: { label: 'Показать в папке', onClick: () => act('revealPath', { path: r.path }) } }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function FileRow({ s, f, i, myId, canDel, leaving }) { |
| +добавлено | const mine = f.createdBy?.id === myId; |
| +добавлено | const toMe = f.recipient?.id === myId; |
| +добавлено | const del = async () => { |
| +добавлено | if (!(await confirmDialog({ title: `Удалить «${f.name}»?`, text: 'Файл исчезнет у всех получателей.', ok: 'Удалить' }))) return; |
| +добавлено | mutateRes(keyFor.files(s.teamId), (list) => list?.filter((x) => x.id !== f.id)); |
| +добавлено | const [, err] = await act('deleteFile', { teamId: s.teamId, fileId: f.id }, { ok: 'Файл удалён' }); |
| +добавлено | if (err) invalidate('files'); |
| +добавлено | }; |
| +добавлено | const expiresSoon = f.expiresAt && new Date(f.expiresAt).getTime() - Date.now() < 86400000; |
| +добавлено | return html`<div class=${'li ' + (leaving ? 'leave-item' : 'enter-item')} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms', alignItems: 'flex-start', paddingTop: '10px', paddingBottom: '10px' }}> |
| +добавлено | <span class="file-ic"><${Icon} name=${fileIconFor(f.name)} size=${15} /></span> |
| +добавлено | <div class="grow stack-s" style="gap:2px"> |
| +добавлено | <div class="row" style="gap:6px"><span class="ell b" style="font-weight:500" title=${f.name}>${f.name}</span>${toMe && !mine ? html`<span class="pill brand" style="height:18px">вам</span>` : null}</div> |
| +добавлено | <div class="faint xs row wrap" style="gap:2px 6px"> |
| +добавлено | <span>${humanBytes(f.bytes)}</span><span>·</span> |
| +добавлено | <span>${mine ? 'вы' : f.createdBy?.name} → ${f.recipient ? (toMe ? 'вам' : f.recipient.name) : 'всей команде'}</span><span>·</span> |
| +добавлено | <span title=${fmtDateTime(f.createdAt)}>${relTime(f.createdAt)}</span> |
| +добавлено | ${f.expiresAt ? html`<span>·</span><span class=${expiresSoon ? 'warn-t' : ''} title=${'Удалится ' + fmtDateTime(f.expiresAt)}>до ${fmtDateTime(f.expiresAt)}</span>` : null} |
| +добавлено | </div> |
| +добавлено | ${f.note ? html`<div class="muted small" style="margin-top:3px">${f.note}</div>` : null} |
| +добавлено | </div> |
| +добавлено | <button type="button" class="btn sm" onClick=${() => download(s, 'downloadFile', { fileId: f.id }, f.name)}><${Icon} name="download" size=${13} />Скачать</button> |
| +добавлено | ${mine || canDel ? html`<${MenuButton} label="Ещё" items=${[{ label: 'Удалить', icon: 'trash', danger: true, onClick: del }]} />` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function ArchivesSection({ s, uploads, canEdit, canDel }) { |
| +добавлено | const archives = useRes(keyFor.archives(s.teamId), () => rpc('archives', { teamId: s.teamId })); |
| +добавлено | const limits = useRes(keyFor.limits(s.teamId), () => rpc('limits', { teamId: s.teamId })); |
| +добавлено | const [project, setProject] = useState(''); |
| +добавлено | const input = useRef(null); |
| +добавлено | const del = async (a) => { |
| +добавлено | if (!(await confirmDialog({ title: `Удалить архив «${a.projectName}»?`, ok: 'Удалить' }))) return; |
| +добавлено | mutateRes(keyFor.archives(s.teamId), (list) => list?.filter((x) => x.id !== a.id)); |
| +добавлено | const [, err] = await act('deleteArchive', { teamId: s.teamId, archiveId: a.id }, { ok: 'Архив удалён' }); |
| +добавлено | if (err) invalidate('archives'); |
| +добавлено | }; |
| +добавлено | const pick = (files) => { |
| +добавлено | for (const f of files) uploads.start(f, { kind: 'archive', projectName: project.trim() || f.name.replace(/\.(zip|rar|7z|tar\.gz|tgz)$/i, '') }); |
| +добавлено | setProject(''); |
| +добавлено | }; |
| +добавлено | const list = archives.data ?? []; |
| +добавлено | return html`<section class="stack-s"> |
| +добавлено | <div class="row"><div class="sec-title"><${Icon} name="archive" size=${14} />Архивы проектов</div><span class="grow"></span> |
| +добавлено | ${limits.data ? html`<span class="faint xs">до ${humanBytes(limits.data.archiveMaxBytes)} · хранятся ${limits.data.archiveTtlDays} ${plural(limits.data.archiveTtlDays, 'день', 'дня', 'дней')}</span>` : null}</div> |
| +добавлено | ${canEdit ? html`<div class="row"> |
| +добавлено | <input class="inp sm grow" value=${project} placeholder="Проект (необязательно)" aria-label="Название проекта" onInput=${(e) => setProject(e.currentTarget.value)} /> |
| +добавлено | <button type="button" class="btn sq" onClick=${() => input.current?.click()}><${Icon} name="upload" size=${14} />Загрузить архив</button> |
| +добавлено | <input ref=${input} type="file" accept=".zip,.rar,.7z,.tar,.gz,.tgz" hidden data-kind="archive" onChange=${(e) => { pick([...e.currentTarget.files]); e.currentTarget.value = ''; }} /> |
| +добавлено | </div>` : null} |
| +добавлено | ${!archives.data ? html`<${SkelList} rows=${2} />` |
| +добавлено | : !list.length ? html`<div class="card"><${Empty} icon="archive" title="Архивов нет" text="Загрузите zip проекта, чтобы коллеги могли быстро развернуть его у себя." /></div>` |
| +добавлено | : html`<div class="card list">${list.map((a, i) => html`<div class="li enter-item" key=${a.id} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }}> |
| +добавлено | <span class="file-ic"><${Icon} name="file-archive" size=${15} /></span> |
| +добавлено | <div class="grow"><div class="ell" style="font-weight:500">${a.projectName}</div> |
| +добавлено | <div class="faint xs ell">${humanBytes(a.bytes)} · ${a.createdBy?.name || a.createdBy || '—'} · ${relTime(a.createdAt)}${a.expiresAt ? ' · до ' + fmtDateTime(a.expiresAt) : ''}</div></div> |
| +добавлено | <button type="button" class="btn sm" onClick=${() => download(s, 'downloadArchive', { archiveId: a.id, targetDir: svc.state?.workspace || undefined }, a.projectName)}><${Icon} name="download" size=${13} />Скачать</button> |
| +добавлено | ${canDel ? html`<${MenuButton} label="Ещё" items=${[{ label: 'Удалить', icon: 'trash', danger: true, onClick: () => del(a) }]} />` : null} |
| +добавлено | </div>`)}</div>`} |
| +добавлено | </section>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function FilesTab({ s, files, board, active }) { |
| +добавлено | const role = myRole(s); |
| +добавлено | const canEdit = roleAtLeast(role, 'dev'); |
| +добавлено | const canDel = roleAtLeast(role, 'maintainer'); |
| +добавлено | const user = me(s); |
| +добавлено | const uploads = useUploads(s); |
| +добавлено | const [recipient, setRecipient] = useState(''); |
| +добавлено | const [note, setNote] = useState(''); |
| +добавлено | const [view, setView] = useState(svc.state?.ui?.filesView || 'in'); |
| +добавлено | const [hot, setHot] = useState(false); |
| +добавлено | const input = useRef(null); |
| +добавлено | const root = useRef(null); |
| +добавлено | const depth = useRef(0); |
| +добавлено | const members = (board.data?.members ?? []).filter((m) => m.id !== user?.id); |
| +добавлено | |
| +добавлено | const send = (list) => { |
| +добавлено | if (!canEdit) { toast('Наблюдатель не может отправлять файлы', { kind: 'err' }); return; } |
| +добавлено | if (!list.length) return; |
| +добавлено | for (const f of list) uploads.start(f, { kind: 'file', recipientId: recipient || undefined, note: note.trim() || undefined }); |
| +добавлено | setNote(''); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // Перетаскивание файлов в любую точку вкладки. |
| +добавлено | useEffect(() => { |
| +добавлено | const pane = root.current?.closest('.pane'); |
| +добавлено | if (!pane) return; |
| +добавлено | const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files'); |
| +добавлено | const enter = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth.current++; setHot(true); }; |
| +добавлено | const over = (e) => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }; |
| +добавлено | const leave = (e) => { if (!hasFiles(e)) return; depth.current = Math.max(0, depth.current - 1); if (!depth.current) setHot(false); }; |
| +добавлено | const drop = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth.current = 0; setHot(false); send([...e.dataTransfer.files]); }; |
| +добавлено | pane.addEventListener('dragenter', enter); |
| +добавлено | pane.addEventListener('dragover', over); |
| +добавлено | pane.addEventListener('dragleave', leave); |
| +добавлено | pane.addEventListener('drop', drop); |
| +добавлено | return () => { pane.removeEventListener('dragenter', enter); pane.removeEventListener('dragover', over); pane.removeEventListener('dragleave', leave); pane.removeEventListener('drop', drop); }; |
| +добавлено | }); |
| +добавлено | |
| +добавлено | const all = files.data ?? []; |
| +добавлено | const list = useMemo(() => all.filter((f) => { |
| +добавлено | const mine = f.createdBy?.id === user?.id; |
| +добавлено | if (view === 'in') return !mine && (!f.recipient || f.recipient.id === user?.id); |
| +добавлено | if (view === 'out') return mine; |
| +добавлено | return true; |
| +добавлено | }).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))), [all, view, user?.id]); |
| +добавлено | const inCount = all.filter((f) => f.createdBy?.id !== user?.id && (!f.recipient || f.recipient.id === user?.id)).length; |
| +добавлено | const outCount = all.filter((f) => f.createdBy?.id === user?.id).length; |
| +добавлено | |
| +добавлено | return html`<div class="pad stack" ref=${root} style="gap:18px"> |
| +добавлено | ${hot ? html`<div class="drop-overlay"><div class="inner"><${Icon} name="upload" size=${28} />Отпустите, чтобы отправить${recipient ? ' — ' + (members.find((m) => m.id === recipient)?.displayName || '') : ' всей команде'}</div></div>` : null} |
| +добавлено | |
| +добавлено | ${canEdit ? html`<section class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="send" size=${14} />Отправить файлы</div> |
| +добавлено | <div class="card pad stack-s"> |
| +добавлено | <div class=${'dropzone' + (hot ? ' hot' : '')}> |
| +добавлено | <${Icon} name="upload" size=${22} /> |
| +добавлено | <div><span style="color:var(--zt-fg)">Перетащите файлы сюда</span> или</div> |
| +добавлено | <button type="button" class="btn primary" onClick=${() => input.current?.click()}>Выбрать файлы</button> |
| +добавлено | <input ref=${input} type="file" multiple hidden data-kind="file" onChange=${(e) => { send([...e.currentTarget.files]); e.currentTarget.value = ''; }} /> |
| +добавлено | </div> |
| +добавлено | <div class="row"> |
| +добавлено | <span class="muted small" style="flex:none">Кому</span> |
| +добавлено | <${Select} sm value=${recipient} label="Получатель" class="grow" onChange=${setRecipient} |
| +добавлено | options=${[{ id: '', label: 'Всей команде' }, ...members.map((m) => ({ id: m.id, label: m.displayName }))]} /> |
| +добавлено | </div> |
| +добавлено | <input class="inp sm" value=${note} maxlength="280" placeholder="Комментарий (необязательно)" aria-label="Комментарий" onInput=${(e) => setNote(e.currentTarget.value)} /> |
| +добавлено | </div> |
| +добавлено | ${uploads.items.length ? html`<div class="card list">${uploads.items.map((it) => html`<${UploadRow} key=${it.id} it=${it} |
| +добавлено | onCancel=${() => uploads.cancel(it.id)} onRetry=${() => uploads.retry(it.id)} onDismiss=${() => uploads.dismiss(it.id)} />`)}</div>` : null} |
| +добавлено | </section>` : null} |
| +добавлено | |
| +добавлено | <section class="stack-s"> |
| +добавлено | <div class="row"> |
| +добавлено | <${Seg} value=${view} onChange=${(v) => { setView(v); saveUi({ filesView: v }); }} label="Список файлов" |
| +добавлено | options=${[{ id: 'in', label: `Входящие${inCount ? ' ' + inCount : ''}` }, { id: 'out', label: `Отправленные${outCount ? ' ' + outCount : ''}` }, { id: 'all', label: 'Все' }]} /> |
| +добавлено | </div> |
| +добавлено | ${!files.data ? html`<${SkelList} rows=${3} />` |
| +добавлено | : !list.length ? html`<div class="card"><${Empty} icon="inbox" title=${view === 'out' ? 'Вы ещё ничего не отправляли' : 'Входящих нет'} text="Файлы хранятся на сервере команды ограниченное время и удаляются автоматически." /></div>` |
| +добавлено | : html`<div class="card list">${list.map((f, i) => html`<${FileRow} key=${f.id} s=${s} f=${f} i=${i} myId=${user?.id} canDel=${canDel} />`)}</div>`} |
| +добавлено | </section> |
| +добавлено | |
| +добавлено | <${ArchivesSection} s=${s} uploads=${uploads} canEdit=${canEdit} canDel=${canDel} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | // Вкладка «Git»: изменения + diff, коммит, история с графом, ветки. |
| +добавлено | import { Fragment } from 'preact'; |
| +добавлено | import { useEffect, useMemo, useRef, useState, useCallback } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, useRes, invalidate, mutateRes, peekRes, humanError, svc, saveSettings, saveUi, relTime, fmtDateTime, |
| +добавлено | copyText, shortId, plural, initials, colorFor, STATUS_LABEL, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | import { Avatar, Select, Empty, Skel, SkelList, AsyncButton, Field, MenuButton, confirmDialog, Seg, Layer, Popover, Spinner } from './ui.js'; |
| +добавлено | import { keyFor, myRole, app } from './app-state.js'; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- diff |
| +добавлено | |
| +добавлено | export function parseDiff(text = '') { |
| +добавлено | const rows = []; |
| +добавлено | let a = 0; |
| +добавлено | let b = 0; |
| +добавлено | for (const line of String(text).split('\n')) { |
| +добавлено | if (line.startsWith('diff --git')) { |
| +добавлено | const m = /^diff --git a\/(.+?) b\/(.+)$/.exec(line); |
| +добавлено | rows.push({ t: 'fhead', text: m ? m[2] : line }); |
| +добавлено | } else if (line.startsWith('@@')) { |
| +добавлено | const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/.exec(line); |
| +добавлено | if (m) { a = +m[1]; b = +m[2]; } |
| +добавлено | rows.push({ t: 'hunk', text: line }); |
| +добавлено | } else if (/^(index |--- |\+\+\+ |new file|deleted file|similarity|rename |old mode|new mode|Binary files)/.test(line)) { |
| +добавлено | rows.push({ t: 'meta', text: line }); |
| +добавлено | } else if (line.startsWith('+')) { |
| +добавлено | rows.push({ t: 'add', a: '', b: b++, text: line.slice(1) }); |
| +добавлено | } else if (line.startsWith('-')) { |
| +добавлено | rows.push({ t: 'del', a: a++, b: '', text: line.slice(1) }); |
| +добавлено | } else if (line.startsWith('\\')) { |
| +добавлено | rows.push({ t: 'meta', text: line }); |
| +добавлено | } else if (rows.length) { |
| +добавлено | rows.push({ t: 'ctx', a: a++, b: b++, text: line.startsWith(' ') ? line.slice(1) : line }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | while (rows.length && rows[rows.length - 1].t === 'ctx' && rows[rows.length - 1].text === '') rows.pop(); |
| +добавлено | return rows; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function DiffView({ diff, maxRows = 3000, showFileHeads = true }) { |
| +добавлено | const rows = useMemo(() => parseDiff(diff), [diff]); |
| +добавлено | if (!diff || !rows.length) return html`<div class="faint small" style="padding:12px">Нет изменений для показа.</div>`; |
| +добавлено | const shown = rows.slice(0, maxRows); |
| +добавлено | return html`<div class="diff selectable" role="region" aria-label="Изменения"> |
| +добавлено | <table><tbody> |
| +добавлено | ${shown.map((r, i) => r.t === 'fhead' ? (showFileHeads ? html`<tr class="fhead" key=${i}><td colspan="4">${r.text}</td></tr>` : null) |
| +добавлено | : r.t === 'hunk' ? html`<tr class="hunk" key=${i}><td class="ln"></td><td class="ln"></td><td colspan="2" style="padding-left:8px">${r.text}</td></tr>` |
| +добавлено | : r.t === 'meta' ? (showFileHeads ? null : null) |
| +добавлено | : html`<tr class=${r.t} key=${i}><td class="ln">${r.a}</td><td class="ln">${r.b}</td><td class="sg">${r.t === 'add' ? '+' : r.t === 'del' ? '−' : ' '}</td><td class="code">${r.text}</td></tr>`)} |
| +добавлено | </tbody></table> |
| +добавлено | ${rows.length > maxRows ? html`<div class="faint xs" style="padding:8px 12px">Показаны первые ${maxRows} строк из ${rows.length}.</div>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- утилиты |
| +добавлено | |
| +добавлено | const splitPath = (p) => { |
| +добавлено | const i = p.lastIndexOf('/'); |
| +добавлено | return i < 0 ? { name: p, dir: '' } : { name: p.slice(i + 1), dir: p.slice(0, i) }; |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function useDir(s) { |
| +добавлено | const st = app.get().state || svc.state; |
| +добавлено | return st?.workspace || st?.ide?.cwd || null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function gitAct(method, params, okMsg) { |
| +добавлено | const [r, err] = await act(method, params, { ok: okMsg }); |
| +добавлено | invalidate('git', 'gitLog', 'gitBranches', 'gitDiff'); |
| +добавлено | return [r, err]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- выбор рабочей папки |
| +добавлено | |
| +добавлено | function WorkspacePicker({ dir, onPick }) { |
| +добавлено | const [open, setOpen] = useState(false); |
| +добавлено | const [custom, setCustom] = useState(''); |
| +добавлено | const ref = useRef(null); |
| +добавлено | const st = svc.state || {}; |
| +добавлено | const recent = [...new Set([st.workspace, st.ide?.cwd, ...(st.recentWorkspaces || [])].filter(Boolean))]; |
| +добавлено | const label = dir ? dir.split(/[\\/]/).filter(Boolean).pop() : 'Папка не выбрана'; |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <button type="button" class="team-sw" ref=${ref} style="max-width:none;flex:1;min-width:0;padding-left:6px" aria-haspopup="menu" aria-expanded=${String(open)} onClick=${() => setOpen((o) => !o)} title=${dir || ''}> |
| +добавлено | <${Icon} name="folder" size=${15} /> |
| +добавлено | <span class="name" style="font-size:13px">${label}</span> |
| +добавлено | <span class="faint xs ell" style="flex:1;text-align:left">${dir && dir !== label ? dir : ''}</span> |
| +добавлено | <${Icon} name="chevrons-up-down" size=${14} /> |
| +добавлено | </button> |
| +добавлено | ${open ? html`<${Popover} anchor=${ref.current} onClose=${() => setOpen(false)} width=${320}> |
| +добавлено | <div class="lbl">Рабочая папка</div> |
| +добавлено | ${recent.map((p) => html`<button type="button" class="mi" key=${p} onClick=${() => { setOpen(false); onPick(p); }}> |
| +добавлено | <${Icon} name="folder" /><span class="grow ell" title=${p}>${p}</span>${p === dir ? html`<${Icon} name="check" class="chk-ic" />` : null} |
| +добавлено | ${p === st.ide?.cwd ? html`<span class="faint xs">IDE</span>` : null}</button>`)} |
| +добавлено | <div class="sep"></div> |
| +добавлено | <div style="padding:4px" class="row"> |
| +добавлено | <input class="inp sm mono" value=${custom} placeholder="Выбрать путь… C:\\path\\repo" aria-label="Путь к репозиторию" onInput=${(e) => setCustom(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter' && custom.trim()) { setOpen(false); onPick(custom.trim()); } }} /> |
| +добавлено | <button type="button" class="btn sm" disabled=${!custom.trim()} onClick=${() => { setOpen(false); onPick(custom.trim()); }}>OK</button> |
| +добавлено | </div> |
| +добавлено | <//>` : null} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- изменения |
| +добавлено | |
| +добавлено | function FileRowGit({ path, status, group, selected, onSelect, onStage, onUnstage, onDiscard, readOnly }) { |
| +добавлено | const { name, dir } = splitPath(path); |
| +добавлено | const letter = group === 'untracked' ? 'U' : group === 'conflicts' ? 'C' : (status || 'M')[0]; |
| +добавлено | return html`<div class=${'git-file' + (selected ? ' sel' : '')} tabindex="0" role="button" data-path=${path} data-group=${group} |
| +добавлено | onClick=${onSelect} onKeyDown=${(e) => { if (e.key === 'Enter') onSelect(); }} title=${path}> |
| +добавлено | <span class=${'st-badge st-' + letter}>${letter}</span> |
| +добавлено | <span class="nm">${name}</span> |
| +добавлено | <span class="dir">${dir ? '\u200E' + dir : ''}</span> |
| +добавлено | ${readOnly ? null : html`<span class="acts" onClick=${(e) => e.stopPropagation()}> |
| +добавлено | ${onDiscard ? html`<button type="button" class="ibtn sm danger" title="Отменить изменения" aria-label=${'Отменить изменения ' + path} onClick=${onDiscard}><${Icon} name="undo" size=${14} /></button>` : null} |
| +добавлено | ${onStage ? html`<button type="button" class="ibtn sm" title="Подготовить" aria-label=${'Подготовить ' + path} data-act="stage" onClick=${onStage}><${Icon} name="plus" size=${14} /></button>` : null} |
| +добавлено | ${onUnstage ? html`<button type="button" class="ibtn sm" title="Убрать из подготовленных" aria-label=${'Убрать ' + path} data-act="unstage" onClick=${onUnstage}><${Icon} name="minus" size=${14} /></button>` : null} |
| +добавлено | </span>`} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function GitSection({ title, count, actions, children, open: initOpen = true }) { |
| +добавлено | const [open, setOpen] = useState(initOpen); |
| +добавлено | if (!count) return null; |
| +добавлено | return html`<div> |
| +добавлено | <div class="git-sec-h"> |
| +добавлено | <button type="button" class="collapse-btn" aria-expanded=${String(open)} onClick=${() => setOpen((o) => !o)} style="font-weight:600"> |
| +добавлено | <span style=${{ display: 'grid', transform: open ? 'none' : 'rotate(-90deg)', transition: 'transform .2s cubic-bezier(.22,1,.36,1)' }}><${Icon} name="chevron" size=${13} /></span>${title}</button> |
| +добавлено | <span class="badge">${count}</span> |
| +добавлено | <span class="grow"></span> |
| +добавлено | ${actions} |
| +добавлено | </div> |
| +добавлено | ${open ? children : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function TaskLinkPicker({ board, onPick }) { |
| +добавлено | const [open, setOpen] = useState(false); |
| +добавлено | const [q, setQ] = useState(''); |
| +добавлено | const ref = useRef(null); |
| +добавлено | const tasks = (board.data?.tasks ?? []).filter((t) => t.status !== 'done' && (!q || t.title.toLowerCase().includes(q.toLowerCase()) || shortId(t.id).startsWith(q.replace('#', '')))); |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <button type="button" class="btn sm" ref=${ref} onClick=${() => setOpen((o) => !o)} aria-haspopup="menu" aria-expanded=${String(open)}><${Icon} name="hash" size=${13} />Привязать задачу</button> |
| +добавлено | ${open ? html`<${Popover} anchor=${ref.current} onClose=${() => setOpen(false)} width=${300}> |
| +добавлено | <div style="padding:4px"><input class="inp sm" value=${q} placeholder="Найти задачу…" aria-label="Поиск задачи" onInput=${(e) => setQ(e.currentTarget.value)} /></div> |
| +добавлено | <div style="max-height:220px;overflow:auto"> |
| +добавлено | ${tasks.slice(0, 30).map((t) => html`<button type="button" class="mi" key=${t.id} onClick=${() => { setOpen(false); onPick(t); }}> |
| +добавлено | <span class="mono faint xs">#${shortId(t.id)}</span><span class="grow ell">${t.title}</span></button>`)} |
| +добавлено | ${!tasks.length ? html`<div class="mi faint" style="cursor:default">${board.data ? 'Ничего не найдено' : 'Команда не выбрана'}</div>` : null} |
| +добавлено | </div> |
| +добавлено | <//>` : null} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function CommitBox({ dir, git, board }) { |
| +добавлено | const [msg, setMsg] = useState(svc.state?.ui?.commitDraft || ''); |
| +добавлено | const [amend, setAmend] = useState(false); |
| +добавлено | const [busy, setBusy] = useState(false); |
| +добавлено | const ta = useRef(null); |
| +добавлено | const subject = msg.split('\n')[0]; |
| +добавлено | const staged = git.staged?.length || 0; |
| +добавлено | const can = !busy && msg.trim() && (staged > 0 || amend); |
| +добавлено | useEffect(() => { const t = setTimeout(() => saveUi({ commitDraft: msg }), 500); return () => clearTimeout(t); }, [msg]); |
| +добавлено | const commit = async (push) => { |
| +добавлено | if (!msg.trim()) { toast('Введите сообщение коммита', { kind: 'err' }); ta.current?.focus(); return; } |
| +добавлено | if (!staged && !amend) { toast('Нет подготовленных изменений', { kind: 'err' }); return; } |
| +добавлено | setBusy(true); |
| +добавлено | const [r, err] = await act('gitCommit', { dir, message: msg.trim(), amend: amend || undefined, push: push || undefined }); |
| +добавлено | setBusy(false); |
| +добавлено | invalidate('git', 'gitLog', 'gitBranches'); |
| +добавлено | if (err) return; |
| +добавлено | setMsg(''); |
| +добавлено | setAmend(false); |
| +добавлено | saveUi({ commitDraft: '' }); |
| +добавлено | toast(html`Коммит <span class="mono">${String(r?.hash || '').slice(0, 7)}</span> ${push ? (r?.pushed ? 'создан и отправлен' : 'создан, push не удался') : 'создан'}`, { kind: push && !r?.pushed ? 'err' : 'ok' }); |
| +добавлено | }; |
| +добавлено | const insertTask = (t) => { |
| +добавлено | const tag = '#' + shortId(t.id); |
| +добавлено | const el = ta.current; |
| +добавлено | if (!msg.trim()) { setMsg(`${t.title} ${tag}`); return; } |
| +добавлено | const pos = el?.selectionEnd ?? msg.length; |
| +добавлено | const next = msg.slice(0, pos) + (msg[pos - 1] && msg[pos - 1] !== ' ' && msg[pos - 1] !== '\n' ? ' ' : '') + tag + msg.slice(pos); |
| +добавлено | setMsg(next); |
| +добавлено | requestAnimationFrame(() => el?.focus()); |
| +добавлено | }; |
| +добавлено | return html`<div class="commit-box"> |
| +добавлено | <div style="position:relative"> |
| +добавлено | <textarea ref=${ta} class="ta" value=${msg} placeholder=${staged ? `Сообщение коммита (${staged} ${plural(staged, 'файл', 'файла', 'файлов')}) · Ctrl+Enter` : 'Сообщение коммита · Ctrl+Enter'} aria-label="Сообщение коммита" |
| +добавлено | onInput=${(e) => setMsg(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); commit(false); } }}></textarea> |
| +добавлено | <span class=${'cnt72' + (subject.length > 72 ? ' over' : '')} style="position:absolute;right:8px;bottom:6px" title="Длина первой строки">${subject.length}/72</span> |
| +добавлено | </div> |
| +добавлено | <div class="row wrap" style="gap:6px"> |
| +добавлено | <${TaskLinkPicker} board=${board} onPick=${insertTask} /> |
| +добавлено | <label class="chk-row small muted"><input type="checkbox" class="chk" checked=${amend} onChange=${(e) => setAmend(e.currentTarget.checked)} />Amend</label> |
| +добавлено | </div> |
| +добавлено | <div class="row" style="gap:6px;justify-content:flex-end"> |
| +добавлено | <button type="button" class="btn" disabled=${!can} onClick=${() => commit(true)}><${Icon} name="arrow-up-line" size=${13} />Коммит и Push</button> |
| +добавлено | <button type="button" class="btn primary" disabled=${!can} onClick=${() => commit(false)}>${busy ? html`<span class="spin"></span>` : html`<${Icon} name="check" size=${14} />`}Коммит</button> |
| +добавлено | </div> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function ChangesView({ dir, gitKey, git, board, readOnly }) { |
| +добавлено | const [sel, setSel] = useState(null); // {path, staged} |
| +добавлено | const diff = useRes(sel ? `gitDiff:${dir}:${sel.path}:${sel.staged ? 1 : 0}` : null, () => rpc('gitDiff', { dir, file: sel.path, staged: sel.staged || undefined })); |
| +добавлено | const optimistic = (fn) => mutateRes(gitKey, (g) => g && fn(g)); |
| +добавлено | const stage = async (files) => { |
| +добавлено | optimistic((g) => { |
| +добавлено | const set = new Set(files); |
| +добавлено | const moved = [...g.unstaged.filter((x) => set.has(x.path)), ...g.untracked.filter((p) => set.has(p)).map((p) => ({ path: p, status: 'A' }))]; |
| +добавлено | return { ...g, unstaged: g.unstaged.filter((x) => !set.has(x.path)), untracked: g.untracked.filter((p) => !set.has(p)), staged: [...g.staged.filter((x) => !set.has(x.path)), ...moved] }; |
| +добавлено | }); |
| +добавлено | await gitAct('gitStage', { dir, files }); |
| +добавлено | }; |
| +добавлено | const unstage = async (files) => { |
| +добавлено | optimistic((g) => { |
| +добавлено | const set = new Set(files); |
| +добавлено | const moved = g.staged.filter((x) => set.has(x.path)); |
| +добавлено | return { ...g, staged: g.staged.filter((x) => !set.has(x.path)), unstaged: [...g.unstaged, ...moved.filter((x) => x.status !== 'A')], untracked: [...g.untracked, ...moved.filter((x) => x.status === 'A').map((x) => x.path)] }; |
| +добавлено | }); |
| +добавлено | await gitAct('gitUnstage', { dir, files }); |
| +добавлено | }; |
| +добавлено | const discard = async (files, untracked) => { |
| +добавлено | if (!(await confirmDialog({ title: files.length === 1 ? `Отменить изменения в ${splitPath(files[0]).name}?` : `Отменить изменения в ${files.length} ${plural(files.length, 'файле', 'файлах', 'файлах')}?`, text: untracked ? 'Новые файлы будут удалены с диска. Это нельзя отменить.' : 'Несохранённые в коммите правки будут потеряны. Это нельзя отменить.', ok: 'Отменить изменения' }))) return; |
| +добавлено | await gitAct('gitDiscard', { dir, files }, 'Изменения отменены'); |
| +добавлено | if (sel && files.includes(sel.path)) setSel(null); |
| +добавлено | }; |
| +добавлено | const stageAll = () => gitAct('gitStageAll', { dir }); |
| +добавлено | |
| +добавлено | const total = (git.staged?.length || 0) + (git.unstaged?.length || 0) + (git.untracked?.length || 0) + (git.conflicts?.length || 0); |
| +добавлено | return html`<div style="display:flex;flex-direction:column;min-height:100%"> |
| +добавлено | <div class="grow" style="padding:4px 0 8px"> |
| +добавлено | ${!total ? html`<${Empty} icon="check" title="Рабочее дерево чистое" text="Изменений нет — можно переключать ветки и тянуть обновления." />` : null} |
| +добавлено | <${GitSection} title="Конфликты" count=${git.conflicts?.length}> |
| +добавлено | ${git.conflicts?.map((p) => html`<${FileRowGit} key=${'c' + p} path=${p} group="conflicts" readOnly=${readOnly} selected=${sel?.path === p} |
| +добавлено | onSelect=${() => setSel({ path: p })} onStage=${() => stage([p])} />`)} |
| +добавлено | <//> |
| +добавлено | <${GitSection} title="Подготовлено" count=${git.staged?.length} |
| +добавлено | actions=${readOnly ? null : html`<button type="button" class="ibtn sm" title="Убрать всё" aria-label="Убрать все из подготовленных" onClick=${() => unstage(git.staged.map((x) => x.path))}><${Icon} name="minus" size=${14} /></button>`}> |
| +добавлено | ${git.staged?.map((f) => html`<${FileRowGit} key=${'s' + f.path} path=${f.path} status=${f.status} group="staged" readOnly=${readOnly} selected=${sel?.path === f.path && sel.staged} |
| +добавлено | onSelect=${() => setSel({ path: f.path, staged: true })} onUnstage=${() => unstage([f.path])} />`)} |
| +добавлено | <//> |
| +добавлено | <${GitSection} title="Изменено" count=${git.unstaged?.length} |
| +добавлено | actions=${readOnly ? null : html`<button type="button" class="ibtn sm danger" title="Отменить все" aria-label="Отменить все изменения" onClick=${() => discard(git.unstaged.map((x) => x.path))}><${Icon} name="undo" size=${14} /></button> |
| +добавлено | <button type="button" class="ibtn sm" title="Подготовить всё" aria-label="Подготовить все изменённые" onClick=${() => stage(git.unstaged.map((x) => x.path))}><${Icon} name="plus" size=${14} /></button>`}> |
| +добавлено | ${git.unstaged?.map((f) => html`<${FileRowGit} key=${'u' + f.path} path=${f.path} status=${f.status} group="unstaged" readOnly=${readOnly} selected=${sel?.path === f.path && !sel.staged} |
| +добавлено | onSelect=${() => setSel({ path: f.path, staged: false })} onStage=${() => stage([f.path])} onDiscard=${() => discard([f.path])} />`)} |
| +добавлено | <//> |
| +добавлено | <${GitSection} title="Новые" count=${git.untracked?.length} |
| +добавлено | actions=${readOnly ? null : html`<button type="button" class="ibtn sm" title="Подготовить все" aria-label="Подготовить все новые" onClick=${() => stage(git.untracked)}><${Icon} name="plus" size=${14} /></button>`}> |
| +добавлено | ${git.untracked?.map((p) => html`<${FileRowGit} key=${'n' + p} path=${p} group="untracked" readOnly=${readOnly} selected=${sel?.path === p} |
| +добавлено | onSelect=${() => setSel({ path: p })} onStage=${() => stage([p])} onDiscard=${() => discard([p], true)} />`)} |
| +добавлено | <//> |
| +добавлено | ${total && !readOnly && (git.unstaged?.length || git.untracked?.length) ? html`<div style="padding:8px 12px"><${AsyncButton} class="btn sm" onClick=${stageAll}><${Icon} name="plus" size=${13} />Подготовить всё<//></div>` : null} |
| +добавлено | </div> |
| +добавлено | <${CommitBox} dir=${dir} git=${git} board=${board} /> |
| +добавлено | <${Layer} open=${!!sel} onClose=${() => setSel(null)} wide title=${sel ? html`<span class="row" style="gap:6px"><${Icon} name="file-code" size=${15} /><span class="ell">${sel.path}</span>${sel.staged ? html`<span class="pill">подготовлено</span>` : null}</span>` : ''} label="Изменения файла" |
| +добавлено | headExtra=${sel && !readOnly ? (sel.staged |
| +добавлено | ? html`<button type="button" class="btn sm" onClick=${() => { unstage([sel.path]); setSel(null); }}><${Icon} name="minus" size=${13} />Убрать</button>` |
| +добавлено | : html`<button type="button" class="btn sm" onClick=${() => { stage([sel.path]); setSel(null); }}><${Icon} name="plus" size=${13} />Подготовить</button>`) : null}> |
| +добавлено | ${diff.loading && !diff.data ? html`<div class="stack-s">${[80, 60, 90, 40, 70].map((w, i) => html`<${Skel} key=${i} w=${w + '%'} hgt=${12} />`)}</div>` |
| +добавлено | : html`<${DiffView} diff=${diff.data?.diff} showFileHeads=${false} />`} |
| +добавлено | <//> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- история |
| +добавлено | |
| +добавлено | function refPills(refs) { |
| +добавлено | if (!refs) return []; |
| +добавлено | const list = (Array.isArray(refs) ? refs : String(refs).split(',')).map((x) => x.trim()).filter(Boolean); |
| +добавлено | const out = []; |
| +добавлено | for (const r of list) { |
| +добавлено | if (r.startsWith('HEAD -> ')) { out.push({ cls: 'head', label: 'HEAD' }); out.push({ cls: 'head', label: r.slice(8), icon: 'git-branch' }); } |
| +добавлено | else if (r === 'HEAD') out.push({ cls: 'head', label: 'HEAD' }); |
| +добавлено | else if (r.startsWith('tag: ')) out.push({ cls: 'tag', label: r.slice(5), icon: 'tag' }); |
| +добавлено | else if (r.includes('/')) out.push({ cls: 'remote', label: r, icon: 'globe' }); |
| +добавлено | else out.push({ cls: '', label: r, icon: 'git-branch' }); |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const PAGE = 30; |
| +добавлено | |
| +добавлено | function HistoryView({ dir }) { |
| +добавлено | const [pages, setPages] = useState(1); |
| +добавлено | const [items, setItems] = useState(null); |
| +добавлено | const [more, setMore] = useState(true); |
| +добавлено | const [loadingMore, setLoadingMore] = useState(false); |
| +добавлено | const [open, setOpen] = useState(null); |
| +добавлено | const sentinel = useRef(null); |
| +добавлено | const first = useRes(`gitLog:${dir}`, () => rpc('gitLog', { dir, limit: PAGE, skip: 0 })); |
| +добавлено | useEffect(() => { if (first.data) { setItems(first.data); setMore(first.data.length >= PAGE); } }, [first.data]); |
| +добавлено | const loadMore = useCallback(async () => { |
| +добавлено | if (loadingMore || !more || !items) return; |
| +добавлено | setLoadingMore(true); |
| +добавлено | try { |
| +добавлено | const next = await rpc('gitLog', { dir, limit: PAGE, skip: items.length }); |
| +добавлено | setItems((x) => [...x, ...next.filter((c) => !x.some((y) => y.hash === c.hash))]); |
| +добавлено | setMore(next.length >= PAGE); |
| +добавлено | } catch (e) { toast(humanError(e), { kind: 'err' }); setMore(false); } |
| +добавлено | setLoadingMore(false); |
| +добавлено | }, [items, more, loadingMore, dir]); |
| +добавлено | useEffect(() => { |
| +добавлено | const el = sentinel.current; |
| +добавлено | if (!el) return; |
| +добавлено | const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) loadMore(); }, { root: el.closest('.pane'), rootMargin: '200px' }); |
| +добавлено | io.observe(el); |
| +добавлено | return () => io.disconnect(); |
| +добавлено | }, [loadMore]); |
| +добавлено | if (!items) return html`<div style="padding:8px 0">${Array.from({ length: 8 }, (_, i) => html`<div class="commit-row" key=${i} style="cursor:default"><span class="node"></span><div class="grow stack-s" style="gap:5px"><${Skel} w=${`${50 + ((i * 13) % 40)}%`} hgt=${11} /><${Skel} w="30%" hgt=${9} /></div></div>`)}</div>`; |
| +добавлено | if (!items.length) return html`<${Empty} icon="git-commit" title="Коммитов пока нет" />`; |
| +добавлено | return html`<div class="graph" style="padding:6px 0"> |
| +добавлено | ${items.map((c, i) => { |
| +добавлено | const merge = (c.parents?.length || 0) > 1; |
| +добавлено | const refs = refPills(c.refs); |
| +добавлено | const head = refs.some((r) => r.label === 'HEAD'); |
| +добавлено | return html`<div class=${'commit-row' + (merge ? ' merge' : '') + (head ? ' head' : '')} key=${c.hash} tabindex="0" role="button" data-hash=${c.hash} |
| +добавлено | onClick=${() => setOpen(c.hash)} onKeyDown=${(e) => e.key === 'Enter' && setOpen(c.hash)}> |
| +добавлено | <span class="node"></span> |
| +добавлено | <div class="grow" style="min-width:0"> |
| +добавлено | <div class="row" style="gap:6px"> |
| +добавлено | <span class="subj grow">${c.subject}</span> |
| +добавлено | </div> |
| +добавлено | <div class="sub"> |
| +добавлено | <span class="av s18" style=${{ background: colorFor(c.email || c.author) }} title=${c.author}>${initials(c.author)}</span> |
| +добавлено | <span class="ell" style="max-width:120px">${c.author}</span> |
| +добавлено | <span class="mono">${c.short || c.hash.slice(0, 7)}</span> |
| +добавлено | <span title=${fmtDateTime(c.date)}>${relTime(c.date)}</span> |
| +добавлено | ${merge ? html`<span class="ref remote" style="background:rgba(167,139,250,.14)"><${Icon} name="git-merge" size=${10} />merge</span>` : null} |
| +добавлено | ${refs.map((r, k) => html`<span class=${'ref ' + r.cls} key=${k}>${r.icon ? html`<${Icon} name=${r.icon} size=${10} />` : null}${r.label}</span>`)} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | </div>`; |
| +добавлено | })} |
| +добавлено | <div ref=${sentinel} style="height:1px"></div> |
| +добавлено | ${loadingMore ? html`<div class="row" style="justify-content:center;padding:10px"><${Spinner} size=${14} /></div>` : !more ? html`<div class="faint xs" style="text-align:center;padding:10px">Начало истории</div>` : null} |
| +добавлено | <${CommitDrawer} dir=${dir} hash=${open} onClose=${() => setOpen(null)} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function CommitDrawer({ dir, hash, onClose }) { |
| +добавлено | const [last, setLast] = useState(hash); |
| +добавлено | useEffect(() => { if (hash) setLast(hash); }, [hash]); |
| +добавлено | const h = hash || last; |
| +добавлено | const show = useRes(h ? `gitShow:${dir}:${h}` : null, () => rpc('gitShow', { dir, hash: h })); |
| +добавлено | const c = show.data; |
| +добавлено | const adds = c?.files?.reduce((a, f) => a + (f.additions || 0), 0) || 0; |
| +добавлено | const dels = c?.files?.reduce((a, f) => a + (f.deletions || 0), 0) || 0; |
| +добавлено | const scrollTo = (path) => { |
| +добавлено | const rows = document.querySelectorAll('.drawer .diff tr.fhead td'); |
| +добавлено | for (const td of rows) if (td.textContent === path) { td.scrollIntoView({ block: 'start', behavior: 'smooth' }); break; } |
| +добавлено | }; |
| +добавлено | return html`<${Layer} open=${!!hash} onClose=${onClose} wide label="Коммит" |
| +добавлено | title=${html`<span class="row" style="gap:6px"><${Icon} name="git-commit" size=${15} /><span class="mono">${(h || '').slice(0, 10)}</span></span>`} |
| +добавлено | headExtra=${html`<button type="button" class="btn sm" onClick=${() => copyText(h, 'Хэш скопирован')}><${Icon} name="copy" size=${13} />Хэш</button>`}> |
| +добавлено | ${!c ? html`<div class="stack-s"><${Skel} w="70%" hgt=${16} /><${Skel} w="40%" hgt=${11} /><${Skel} hgt=${120} /></div>` : html`<div class="stack"> |
| +добавлено | <div> |
| +добавлено | <div class="h2 sel-text" style="font-size:15px;line-height:1.4">${c.subject}</div> |
| +добавлено | ${c.body ? html`<pre class="sel-text muted" style="white-space:pre-wrap;font:12.5px/1.5 var(--font);margin:8px 0 0">${c.body}</pre>` : null} |
| +добавлено | </div> |
| +добавлено | <div class="card"> |
| +добавлено | <div class="info-row"><span class="k">Автор</span><span class="v row" style="justify-content:flex-end;gap:6px"><span class="av s18" style=${{ background: colorFor(c.email || c.author) }}>${initials(c.author)}</span>${c.author}${c.email ? html`<span class="faint">${c.email}</span>` : null}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Дата</span><span class="v">${fmtDateTime(c.date)} · ${relTime(c.date)}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Родители</span><span class="v mono">${(c.parents || []).map((p) => p.slice(0, 7)).join(', ') || '—'}${(c.parents || []).length > 1 ? html` <span class="ref remote">merge</span>` : null}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Изменения</span><span class="v">${c.files?.length || 0} ${plural(c.files?.length || 0, 'файл', 'файла', 'файлов')} <span class="stat-add">+${adds}</span> <span class="stat-del">−${dels}</span></span></div> |
| +добавлено | </div> |
| +добавлено | ${c.files?.length ? html`<div class="card list">${c.files.map((f) => html`<div class="git-file" key=${f.path} onClick=${() => scrollTo(f.path)} tabindex="0" role="button" onKeyDown=${(e) => e.key === 'Enter' && scrollTo(f.path)}> |
| +добавлено | <span class=${'st-badge st-' + (f.status || 'M')[0]}>${(f.status || 'M')[0]}</span> |
| +добавлено | <span class="nm">${splitPath(f.path).name}</span><span class="dir">${splitPath(f.path).dir ? '\u200E' + splitPath(f.path).dir : ''}</span> |
| +добавлено | <span class="stat-add">+${f.additions ?? 0}</span><span class="stat-del">−${f.deletions ?? 0}</span> |
| +добавлено | </div>`)}</div>` : null} |
| +добавлено | <${DiffView} diff=${c.patch} /> |
| +добавлено | ${c.truncated ? html`<div class="faint xs">Патч обрезан — слишком большой для показа.</div>` : null} |
| +добавлено | </div>`} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- ветки |
| +добавлено | |
| +добавлено | function slug(s) { |
| +добавлено | const map = { а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch', ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya' }; |
| +добавлено | return String(s).toLowerCase().split('').map((ch) => map[ch] ?? ch).join('').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function BranchesView({ dir, git, board, readOnly }) { |
| +добавлено | const br = useRes(`gitBranches:${dir}`, () => rpc('gitBranches', { dir })); |
| +добавлено | const [creating, setCreating] = useState(false); |
| +добавлено | const [name, setName] = useState(''); |
| +добавлено | const [taskId, setTaskId] = useState(''); |
| +добавлено | const tasks = (board.data?.tasks ?? []).filter((t) => t.status !== 'done'); |
| +добавлено | useEffect(() => { |
| +добавлено | if (!taskId) return; |
| +добавлено | const t = tasks.find((x) => x.id === taskId); |
| +добавлено | if (t) setName(`feat/${shortId(t.id)}-${slug(t.title)}`); |
| +добавлено | }, [taskId]); |
| +добавлено | const checkout = async (b) => { |
| +добавлено | const dirty = (git.unstaged?.length || 0) + (git.staged?.length || 0); |
| +добавлено | if (dirty && !(await confirmDialog({ title: `Переключиться на ${b.name}?`, text: `В рабочем дереве ${dirty} ${plural(dirty, 'изменённый файл', 'изменённых файла', 'изменённых файлов')}. Git может отказать, если они конфликтуют.`, ok: 'Переключить', danger: false }))) return; |
| +добавлено | await gitAct('gitCheckout', { dir, branch: b.name }, `Ветка ${b.name}`); |
| +добавлено | }; |
| +добавлено | const create = async () => { |
| +добавлено | const n = name.trim(); |
| +добавлено | if (!n) return; |
| +добавлено | const [, err] = await gitAct('gitCheckout', { dir, branch: n, create: true }, `Создана ветка ${n}`); |
| +добавлено | if (!err) { setCreating(false); setName(''); setTaskId(''); } |
| +добавлено | }; |
| +добавлено | return html`<div class="pad stack-s"> |
| +добавлено | ${readOnly ? null : creating ? html`<div class="card pad stack-s reveal"> |
| +добавлено | <${Field} label="Из задачи (необязательно)"><${Select} sm value=${taskId} label="Задача" onChange=${setTaskId} |
| +добавлено | options=${[{ id: '', label: '— без задачи —' }, ...tasks.map((t) => ({ id: t.id, label: `#${shortId(t.id)} ${t.title}` }))]} /><//> |
| +добавлено | <${Field} label="Имя ветки"><input class="inp sm mono" value=${name} placeholder="feat/…" data-autofocus ref=${(el) => el && !name && requestAnimationFrame(() => el.focus())} |
| +добавлено | onInput=${(e) => setName(e.currentTarget.value)} onKeyDown=${(e) => { if (e.key === 'Enter') create(); if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setCreating(false); } }} /><//> |
| +добавлено | <div class="row" style="justify-content:flex-end"><button type="button" class="btn" onClick=${() => setCreating(false)}>Отмена</button><${AsyncButton} class="btn primary" onClick=${create} disabled=${!name.trim()}>Создать и переключиться<//></div> |
| +добавлено | </div>` : html`<div class="row"><span class="grow"></span><button type="button" class="btn sm" onClick=${() => setCreating(true)}><${Icon} name="plus" size=${13} />Новая ветка</button></div>`} |
| +добавлено | ${!br.data ? html`<${SkelList} rows=${4} />` : html`<div class="card list">${br.data.map((b, i) => html`<div class=${'li enter-item' + (b.current ? '' : ' click')} key=${b.name} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }} |
| +добавлено | tabindex=${b.current ? undefined : '0'} role=${b.current ? undefined : 'button'} onClick=${() => !b.current && !readOnly && checkout(b)} onKeyDown=${(e) => e.key === 'Enter' && !b.current && checkout(b)}> |
| +добавлено | <span style=${{ color: b.current ? 'var(--zt-brand)' : 'var(--zt-fg3)', display: 'grid' }}><${Icon} name=${b.current ? 'check' : 'git-branch'} size=${15} /></span> |
| +добавлено | <div class="grow"> |
| +добавлено | <div class="row" style="gap:6px"><span class=${'ell mono' + (b.current ? ' b' : '')} style="font-size:12.5px">${b.name}</span> |
| +добавлено | ${b.ahead ? html`<span class="pill" style="height:18px;padding:0 6px"><${Icon} name="arrow-up" size=${11} />${b.ahead}</span>` : null} |
| +добавлено | ${b.behind ? html`<span class="pill" style="height:18px;padding:0 6px"><${Icon} name="arrow-down" size=${11} />${b.behind}</span>` : null}</div> |
| +добавлено | <div class="faint xs ell">${b.upstream ? '↗ ' + b.upstream + ' · ' : 'без upstream · '}${b.lastCommit?.subject || b.lastCommit || ''}${b.lastCommit?.date ? ' · ' + relTime(b.lastCommit.date) : ''}</div> |
| +добавлено | </div> |
| +добавлено | ${b.current ? html`<span class="pill brand">текущая</span>` : readOnly ? null : html`<span class="pill" style="height:26px;padding:0 12px;color:var(--zt-fg)">Перейти</span>`} |
| +добавлено | </div>`)}</div>`} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вкладка |
| +добавлено | |
| +добавлено | export function GitTab({ s, board }) { |
| +добавлено | const [dir, setDir] = useState(useDir(s)); |
| +добавлено | const [sub, setSub] = useState(svc.state?.ui?.gitTab || 'changes'); |
| +добавлено | const gitKey = `git:${dir || ''}`; |
| +добавлено | const g = useRes(gitKey, () => rpc('git', { dir: dir || undefined })); |
| +добавлено | const git = g.data; |
| +добавлено | const [syncing, setSyncing] = useState(null); |
| +добавлено | const pick = async (p) => { |
| +добавлено | setDir(p); |
| +добавлено | await saveSettings({ workspace: p }).catch(() => {}); |
| +добавлено | invalidate('git'); |
| +добавлено | }; |
| +добавлено | const effDir = dir || git?.cwd || undefined; |
| +добавлено | const run = async (kind) => { |
| +добавлено | setSyncing(kind); |
| +добавлено | let params = { dir: effDir }; |
| +добавлено | if (kind === 'gitPush' && !git?.upstream) { |
| +добавлено | const ok = await confirmDialog({ title: `Опубликовать ветку ${git?.branch}?`, text: 'У ветки нет upstream. Она будет отправлена в origin и связана с origin/' + git?.branch + '.', ok: 'Опубликовать', danger: false }); |
| +добавлено | if (!ok) { setSyncing(null); return; } |
| +добавлено | params = { ...params, setUpstream: true }; |
| +добавлено | } |
| +добавлено | const labels = { gitFetch: 'Fetch выполнен', gitPull: 'Pull выполнен', gitPush: 'Push выполнен' }; |
| +добавлено | await gitAct(kind, params, labels[kind]); |
| +добавлено | setSyncing(null); |
| +добавлено | }; |
| +добавлено | const onSub = (v) => { setSub(v); saveUi({ gitTab: v }); }; |
| +добавлено | const readOnly = false; |
| +добавлено | |
| +добавлено | return html`<div style="display:flex;flex-direction:column;min-height:100%"> |
| +добавлено | <div class="git-top"> |
| +добавлено | <div class="row"><${WorkspacePicker} dir=${git?.cwd || dir} onPick=${pick} /></div> |
| +добавлено | ${git?.isRepo ? html`<div class="row wrap" style="gap:6px"> |
| +добавлено | <span class="branch-pill" title=${git.upstream ? 'upstream: ' + git.upstream : 'нет upstream'}> |
| +добавлено | <${Icon} name="git-branch" size=${14} /><span class="ell mono" style="font-size:12px">${git.detached ? 'detached HEAD' : git.branch}</span> |
| +добавлено | ${git.ahead ? html`<span class="ab" title=${git.ahead + ' к отправке'}><${Icon} name="arrow-up" size=${12} />${git.ahead}</span>` : null} |
| +добавлено | ${git.behind ? html`<span class="ab" title=${git.behind + ' к получению'}><${Icon} name="arrow-down" size=${12} />${git.behind}</span>` : null} |
| +добавлено | </span> |
| +добавлено | <span class="grow"></span> |
| +добавлено | <button type="button" class="btn sm" disabled=${!!syncing} onClick=${() => run('gitFetch')} title="git fetch">${syncing === 'gitFetch' ? html`<span class="spin"></span>` : html`<${Icon} name="refresh" size=${13} />`}Fetch</button> |
| +добавлено | <button type="button" class="btn sm" disabled=${!!syncing} onClick=${() => run('gitPull')} title="git pull">${syncing === 'gitPull' ? html`<span class="spin"></span>` : html`<${Icon} name="arrow-down-line" size=${13} />`}Pull${git.behind ? ' ' + git.behind : ''}</button> |
| +добавлено | <button type="button" class="btn sm" disabled=${!!syncing} onClick=${() => run('gitPush')} title=${git.upstream ? 'git push' : 'git push --set-upstream'}>${syncing === 'gitPush' ? html`<span class="spin"></span>` : html`<${Icon} name="arrow-up-line" size=${13} />`}${git.upstream ? 'Push' + (git.ahead ? ' ' + git.ahead : '') : 'Опубликовать'}</button> |
| +добавлено | </div> |
| +добавлено | <${Seg} block value=${sub} onChange=${onSub} label="Раздел Git" options=${[ |
| +добавлено | { id: 'changes', label: `Изменения${git.counts?.total ?? ((git.staged?.length || 0) + (git.unstaged?.length || 0) + (git.untracked?.length || 0)) ? ' ' + (git.counts?.total ?? ((git.staged?.length || 0) + (git.unstaged?.length || 0) + (git.untracked?.length || 0))) : ''}` }, |
| +добавлено | { id: 'history', label: 'История' }, |
| +добавлено | { id: 'branches', label: 'Ветки' }, |
| +добавлено | ]} />` : null} |
| +добавлено | </div> |
| +добавлено | ${!git ? (g.error ? html`<${Empty} icon="alert" title="Git недоступен" text=${humanError(g.error)}><button class="btn" onClick=${g.reload}>Повторить</button><//>` |
| +добавлено | : html`<div class="pad"><${SkelList} rows=${5} card=${false} /></div>`) |
| +добавлено | : !git.isRepo ? html`<div class="pad stack" style="padding-top:24px"> |
| +добавлено | <${Empty} icon="git-branch" title="Здесь нет git-репозитория" text=${(git.cwd || dir || 'Папка не выбрана') + ' — выберите другую папку выше или откройте проект в ZCode.'} /> |
| +добавлено | </div>` |
| +добавлено | : sub === 'changes' ? html`<${ChangesView} dir=${effDir} gitKey=${gitKey} git=${git} board=${board} readOnly=${readOnly} />` |
| +добавлено | : sub === 'history' ? html`<${HistoryView} dir=${effDir} />` |
| +добавлено | : html`<${BranchesView} dir=${effDir} git=${git} board=${board} readOnly=${readOnly} />`} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | // Вкладка «Ключи»: общие ключи команды, мои провайдеры ZCode, подключение ключей команды, расход, токены. |
| +добавлено | import { Fragment } from 'preact'; |
| +добавлено | import { useEffect, useMemo, useRef, useState } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, useRes, invalidate, mutateRes, humanError, ROLE_RU, roleAtLeast, relTime, fmtDate, |
| +добавлено | hostOf, copyText, plural, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | import { Avatar, Layer, Select, Empty, Skel, SkelList, AsyncButton, Field, MenuButton, confirmDialog, Seg } from './ui.js'; |
| +добавлено | import { keyFor, myRole } from './app-state.js'; |
| +добавлено | |
| +добавлено | const ACCESS_OPTS = [ |
| +добавлено | { id: 'viewer', label: 'Все (от наблюдателя)' }, |
| +добавлено | { id: 'dev', label: 'Разработчики и выше' }, |
| +добавлено | { id: 'maintainer', label: 'Мейнтейнеры и выше' }, |
| +добавлено | { id: 'owner', label: 'Только владелец' }, |
| +добавлено | ]; |
| +добавлено | const ACCESS_SHORT = { viewer: 'все', dev: 'dev+', maintainer: 'maintainer+', owner: 'владелец' }; |
| +добавлено | |
| +добавлено | function keyHealth(k) { |
| +добавлено | if (k.disabledAt) return { cls: '', label: 'отключён' }; |
| +добавлено | if (k.ok === true && (k.lastStatus === 'limited' || k.lastStatus === 429)) return { cls: 'warn', label: 'лимит' }; |
| +добавлено | if (k.ok === true) return { cls: 'ok', label: 'работает' }; |
| +добавлено | if (k.ok === false && (k.lastStatus === 'limited' || k.lastStatus === 429)) return { cls: 'warn', label: 'лимит' }; |
| +добавлено | if (k.ok === false) return { cls: 'err', label: 'ошибка' }; |
| +добавлено | return { cls: '', label: 'не проверен' }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- редактор списка моделей |
| +добавлено | |
| +добавлено | function ModelsEditor({ value = [], onChange, suggestions = [] }) { |
| +добавлено | const [text, setText] = useState(''); |
| +добавлено | const add = (raw) => { |
| +добавлено | const parts = raw.split(/[\s,]+/).map((x) => x.trim()).filter(Boolean); |
| +добавлено | const next = [...value]; |
| +добавлено | for (const p of parts) if (!next.includes(p)) next.push(p); |
| +добавлено | onChange(next); |
| +добавлено | setText(''); |
| +добавлено | }; |
| +добавлено | return html`<div class="labels-ed"> |
| +добавлено | ${value.map((m) => html`<span class="tag mono" key=${m} style="font-size:11px">${m}<button type="button" aria-label=${'Убрать ' + m} onClick=${() => onChange(value.filter((x) => x !== m))}><${Icon} name="x" size=${11} /></button></span>`)} |
| +добавлено | <input value=${text} placeholder=${value.length ? '' : 'Пусто — любые модели'} aria-label="Добавить модель" list="model-sugg" |
| +добавлено | onInput=${(e) => setText(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(text); } else if (e.key === 'Backspace' && !text && value.length) onChange(value.slice(0, -1)); }} |
| +добавлено | onBlur=${() => text && add(text)} /> |
| +добавлено | <datalist id="model-sugg">${suggestions.map((m) => html`<option key=${m} value=${m} />`)}</datalist> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- лист ключа (добавить/изменить) |
| +добавлено | |
| +добавлено | function KeySheet({ s, open, onClose, keyItem, providers }) { |
| +добавлено | const editing = !!keyItem; |
| +добавлено | const blank = { provider: providers?.[0]?.id || 'openai', label: '', value: '', baseUrl: '', models: [], dailyLimit: '', accessRole: 'dev', priority: 100 }; |
| +добавлено | const [v, setV] = useState(blank); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | const [rotate, setRotate] = useState(false); |
| +добавлено | useEffect(() => { |
| +добавлено | if (!open) return; |
| +добавлено | setErr(''); |
| +добавлено | setRotate(false); |
| +добавлено | setV(keyItem ? { |
| +добавлено | provider: keyItem.provider, label: keyItem.label || '', value: '', baseUrl: keyItem.baseUrl || '', |
| +добавлено | models: keyItem.models?.length ? keyItem.models : keyItem.model ? [keyItem.model] : [], |
| +добавлено | dailyLimit: keyItem.dailyLimit == null ? '' : String(keyItem.dailyLimit), accessRole: keyItem.accessRole || 'dev', priority: keyItem.priority ?? 100, |
| +добавлено | } : { ...blank, provider: providers?.[0]?.id || 'openai' }); |
| +добавлено | }, [open, keyItem?.id]); |
| +добавлено | const set = (p) => setV((x) => ({ ...x, ...p })); |
| +добавлено | const prov = providers?.find((p) => p.id === v.provider); |
| +добавлено | const submit = async () => { |
| +добавлено | setErr(''); |
| +добавлено | const limit = v.dailyLimit.trim() === '' ? null : Math.floor(Number(v.dailyLimit)); |
| +добавлено | if (limit !== null && (!Number.isFinite(limit) || limit < 0)) { setErr('Лимит — целое число или пусто'); return; } |
| +добавлено | if (v.baseUrl && !/^https?:\/\//i.test(v.baseUrl.trim())) { setErr('Base URL должен начинаться с http(s)://'); return; } |
| +добавлено | try { |
| +добавлено | if (editing) { |
| +добавлено | const changes = { label: v.label.trim() || null, models: v.models, model: v.models[0] ?? null, dailyLimit: limit, accessRole: v.accessRole, baseUrl: v.baseUrl.trim() || null, priority: Number(v.priority) || 100 }; |
| +добавлено | if (rotate) { |
| +добавлено | if (!v.value.trim()) { setErr('Введите новый секрет'); return; } |
| +добавлено | changes.value = v.value.trim(); |
| +добавлено | } |
| +добавлено | await rpc('updateKey', { teamId: s.teamId, keyId: keyItem.id, changes }); |
| +добавлено | toast('Ключ обновлён', { kind: 'ok' }); |
| +добавлено | } else { |
| +добавлено | if (!v.value.trim()) { setErr('Введите секрет ключа'); return; } |
| +добавлено | await rpc('addKey', { teamId: s.teamId, provider: v.provider, value: v.value.trim(), accessRole: v.accessRole, label: v.label.trim() || prov?.name || v.provider, priority: Number(v.priority) || 100, baseUrl: v.baseUrl.trim() || undefined, model: v.models[0], models: v.models, dailyLimit: limit }); |
| +добавлено | toast('Ключ добавлен', { kind: 'ok' }); |
| +добавлено | } |
| +добавлено | invalidate('keys'); |
| +добавлено | onClose(); |
| +добавлено | } catch (e) { setErr(e.status === 403 ? 'Недостаточно прав' : humanError(e)); } |
| +добавлено | }; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title=${editing ? 'Изменить ключ' : 'Добавить ключ'} |
| +добавлено | footer=${html`<button type="button" class="btn" onClick=${onClose}>Отмена</button><${AsyncButton} class="btn primary" onClick=${submit}>${editing ? 'Сохранить' : 'Добавить ключ'}<//>`}> |
| +добавлено | <div class="stack"> |
| +добавлено | ${editing ? html`<div class="row small"><span class="pill">${keyItem.provider}</span><span class="mono faint">${keyItem.keyHint}</span></div>` |
| +добавлено | : html`<${Field} label="Провайдер"><${Select} value=${v.provider} label="Провайдер" onChange=${(x) => set({ provider: x })} |
| +добавлено | options=${(providers?.length ? providers : [{ id: 'openai', name: 'OpenAI' }, { id: 'anthropic', name: 'Anthropic' }]).map((p) => ({ id: p.id, label: p.name + (p.builtin === false ? ' · свой' : '') }))} /><//>`} |
| +добавлено | <${Field} label="Название"><input class="inp" value=${v.label} placeholder=${prov?.name || 'Например, «OpenAI основной»'} onInput=${(e) => set({ label: e.currentTarget.value })} data-autofocus /><//> |
| +добавлено | ${!editing || rotate ? html`<${Field} label=${editing ? 'Новый секрет' : 'Секрет'} hint="Хранится зашифрованным на сервере команды. Участники используют его через прокси и не видят значение."> |
| +добавлено | <input class="inp mono" type="password" autocomplete="off" value=${v.value} placeholder="sk-…" onInput=${(e) => set({ value: e.currentTarget.value })} /><//>` |
| +добавлено | : html`<button type="button" class="btn sq" style="align-self:flex-start" onClick=${() => setRotate(true)}><${Icon} name="refresh" size=${14} />Заменить секрет (ротация)</button>`} |
| +добавлено | <${Field} label="Base URL" hint=${prov?.origin ? 'По умолчанию: ' + prov.origin : 'Оставьте пустым для адреса провайдера'}> |
| +добавлено | <input class="inp mono" value=${v.baseUrl} placeholder=${prov?.origin || 'https://api.example.com/v1'} onInput=${(e) => set({ baseUrl: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Модели" hint="Enter или запятая — добавить. Пусто — ключ подходит для любых моделей."> |
| +добавлено | <${ModelsEditor} value=${v.models} onChange=${(m) => set({ models: m })} /><//> |
| +добавлено | <div class="row top" style="gap:10px"> |
| +добавлено | <${Field} label="Лимит в день" style="flex:1"><input class="inp" type="number" min="0" value=${v.dailyLimit} placeholder="без лимита" onInput=${(e) => set({ dailyLimit: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Приоритет" style="width:96px" hint="меньше — раньше"><input class="inp" type="number" min="0" value=${v.priority} onInput=${(e) => set({ priority: e.currentTarget.value })} /><//> |
| +добавлено | </div> |
| +добавлено | <${Field} label="Кто может пользоваться"><${Select} value=${v.accessRole} options=${ACCESS_OPTS} label="Доступ" onChange=${(x) => set({ accessRole: x })} /><//> |
| +добавлено | ${err ? html`<div class="err-box"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | </div> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- карточка ключа |
| +добавлено | |
| +добавлено | function RevealBox({ value, onHide }) { |
| +добавлено | const [left, setLeft] = useState(30); |
| +добавлено | useEffect(() => { |
| +добавлено | const i = setInterval(() => setLeft((x) => { if (x <= 1) { clearInterval(i); onHide(); return 0; } return x - 1; }), 1000); |
| +добавлено | return () => clearInterval(i); |
| +добавлено | }, []); |
| +добавлено | return html`<div class="reveal-box reveal"> |
| +добавлено | <span class="mono sel-text">${value}</span> |
| +добавлено | <span class="faint xs" title="Скроется автоматически">${left} с</span> |
| +добавлено | <button type="button" class="ibtn sm" title="Скопировать" aria-label="Скопировать ключ" onClick=${() => copyText(value, 'Ключ скопирован')}><${Icon} name="copy" size=${14} /></button> |
| +добавлено | <button type="button" class="ibtn sm" title="Скрыть" aria-label="Скрыть ключ" onClick=${onHide}><${Icon} name="eye-off" size=${14} /></button> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function KeyCard({ s, k, canManage, onEdit, i }) { |
| +добавлено | const [revealed, setRevealed] = useState(null); |
| +добавлено | const [checking, setChecking] = useState(false); |
| +добавлено | const h = keyHealth(k); |
| +добавлено | const ping = async () => { |
| +добавлено | setChecking(true); |
| +добавлено | const [r, err] = await act('pingKey', { teamId: s.teamId, keyId: k.id }); |
| +добавлено | setChecking(false); |
| +добавлено | if (r) { |
| +добавлено | mutateRes(keyFor.keys(s.teamId), (list) => list?.map((x) => (x.id === k.id ? { ...x, ok: r.ok, pingMs: r.pingMs, lastStatus: r.limited ? 'limited' : r.status, lastError: r.error ?? null, lastCheckedAt: new Date().toISOString() } : x))); |
| +добавлено | toast(r.ok ? `«${k.label}» работает${r.pingMs ? ' · ' + r.pingMs + ' мс' : ''}` : `«${k.label}»: ${r.limited ? 'исчерпан лимит' : r.error || 'ошибка'}`, { kind: r.ok ? 'ok' : 'err' }); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | const reveal = async () => { |
| +добавлено | const [r] = await act('revealKey', { teamId: s.teamId, keyId: k.id }); |
| +добавлено | if (r?.value) setRevealed(r.value); |
| +добавлено | }; |
| +добавлено | const toggle = async () => { |
| +добавлено | const m = k.disabledAt ? 'enableKey' : 'disableKey'; |
| +добавлено | mutateRes(keyFor.keys(s.teamId), (list) => list?.map((x) => (x.id === k.id ? { ...x, disabledAt: k.disabledAt ? null : new Date().toISOString() } : x))); |
| +добавлено | const [, err] = await act(m, { teamId: s.teamId, keyId: k.id }, { ok: k.disabledAt ? 'Ключ включён' : 'Ключ отключён' }); |
| +добавлено | if (err) invalidate('keys'); |
| +добавлено | }; |
| +добавлено | const del = async () => { |
| +добавлено | if (!(await confirmDialog({ title: `Удалить ключ «${k.label}»?`, text: 'Запросы участников через этот ключ перестанут работать. Действие необратимо.', ok: 'Удалить' }))) return; |
| +добавлено | mutateRes(keyFor.keys(s.teamId), (list) => list?.filter((x) => x.id !== k.id)); |
| +добавлено | const [, err] = await act('deleteKey', { teamId: s.teamId, keyId: k.id }, { ok: 'Ключ удалён' }); |
| +добавлено | if (err) invalidate('keys'); |
| +добавлено | }; |
| +добавлено | const models = k.models?.length ? k.models : k.model ? [k.model] : []; |
| +добавлено | const pct = k.dailyLimit ? Math.min(1, (k.usedToday || 0) / k.dailyLimit) : 0; |
| +добавлено | return html`<div class=${'key-card enter-item' + (k.disabledAt ? ' off' : '')} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }}> |
| +добавлено | <div class="row"> |
| +добавлено | <span class=${'dot ' + h.cls} title=${h.label + (k.lastError ? ': ' + k.lastError : '')}></span> |
| +добавлено | <span class="b ell">${k.label || k.provider}</span> |
| +добавлено | <span class="pill">${k.provider}</span> |
| +добавлено | <span class="grow"></span> |
| +добавлено | ${checking ? html`<span class="spin" style="width:14px;height:14px"></span>` : null} |
| +добавлено | ${canManage ? html`<${MenuButton} label=${'Действия: ' + k.label} items=${[ |
| +добавлено | { label: 'Проверить', icon: 'zap', onClick: ping }, |
| +добавлено | { label: 'Показать ключ', icon: 'eye', onClick: reveal }, |
| +добавлено | { label: 'Изменить…', icon: 'pencil', onClick: () => onEdit(k) }, |
| +добавлено | { label: k.disabledAt ? 'Включить' : 'Отключить', icon: 'power', onClick: toggle }, |
| +добавлено | { sep: true }, |
| +добавлено | { label: 'Удалить', icon: 'trash', danger: true, onClick: del }, |
| +добавлено | ]} />` : html`<button type="button" class="ibtn sm" title="Проверить" aria-label="Проверить ключ" onClick=${ping}><${Icon} name="zap" size=${14} /></button>`} |
| +добавлено | </div> |
| +добавлено | <div class="row wrap faint xs" style="gap:4px 8px"> |
| +добавлено | <span class="mono">${k.keyHint}</span> |
| +добавлено | <span>·</span><span class="ell" style="max-width:180px">${hostOf(k.baseUrl) || 'адрес провайдера'}</span> |
| +добавлено | <span>·</span><span>${h.label}${k.pingMs ? ' ' + k.pingMs + ' мс' : ''}</span> |
| +добавлено | <span>·</span><span title="Кто может пользоваться">доступ: ${ACCESS_SHORT[k.accessRole] || k.accessRole}</span> |
| +добавлено | ${k.groupId ? html`<span>·</span><span>группа</span>` : null} |
| +добавлено | ${k.lastCheckedAt ? html`<span>·</span><span>проверен ${relTime(k.lastCheckedAt)}</span>` : null} |
| +добавлено | </div> |
| +добавлено | ${k.ok === false && k.lastError ? html`<div class="danger-t xs ell" title=${k.lastError}>${k.lastError}</div>` : null} |
| +добавлено | <div class="models">${models.length ? models.slice(0, 8).map((m) => html`<span class="model-chip" key=${m}>${m}</span>`) : html`<span class="model-chip" style="font-family:var(--font)">любые модели</span>`} |
| +добавлено | ${models.length > 8 ? html`<span class="model-chip">+${models.length - 8}</span>` : null}</div> |
| +добавлено | <div class="meter"> |
| +добавлено | <div class="row muted"><span>Сегодня</span><span class="grow"></span><span><b style="color:var(--zt-fg)">${k.usedToday ?? 0}</b>${k.dailyLimit ? ' / ' + k.dailyLimit : ''} ${k.dailyLimit ? '' : 'запросов · без лимита'}</span></div> |
| +добавлено | ${k.dailyLimit ? html`<div class=${'progress' + (pct >= 1 ? ' err' : pct > 0.8 ? ' warn' : '')}><i style=${{ transform: `scaleX(${pct})` }}></i></div>` : null} |
| +добавлено | </div> |
| +добавлено | ${revealed ? html`<${RevealBox} value=${revealed} onHide=${() => setRevealed(null)} />` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- мои провайдеры |
| +добавлено | |
| +добавлено | function LocalProviderCard({ s, p, i }) { |
| +добавлено | const [sel, setSel] = useState(() => new Set(p.models)); |
| +добавлено | const [limit, setLimit] = useState(''); |
| +добавлено | const [access, setAccess] = useState('dev'); |
| +добавлено | const [allKeys, setAllKeys] = useState(false); |
| +добавлено | const toggle = (m) => setSel((x) => { const n = new Set(x); n.has(m) ? n.delete(m) : n.add(m); return n; }); |
| +добавлено | const share = async () => { |
| +добавлено | const lim = limit.trim() === '' ? null : Math.floor(Number(limit)); |
| +добавлено | const [r, err] = await act('shareLocalProvider', { teamId: s.teamId, providerId: p.providerId, models: [...sel], dailyLimit: lim, accessRole: access, label: p.name, allKeys }); |
| +добавлено | if (!err) { |
| +добавлено | toast(r?.created ? `Поделились: ${r.created} ${plural(r.created, 'ключ', 'ключа', 'ключей')}${r.skipped ? `, пропущено ${r.skipped}` : ''}` : 'Эти ключи уже есть у команды', { kind: 'ok' }); |
| +добавлено | invalidate('keys'); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | return html`<div class="key-card enter-item" style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }}> |
| +добавлено | <div class="row"> |
| +добавлено | <span class="file-ic" style="width:28px;height:28px"><${Icon} name="plug" size=${14} /></span> |
| +добавлено | <div class="grow"><div class="b ell">${p.name}</div><div class="faint xs ell mono">${hostOf(p.baseUrl) || p.apiType}</div></div> |
| +добавлено | ${p.teamManaged ? html`<span class="pill brand" title="Этот провайдер подключён из ключей команды">из команды</span>` : html`<span class="pill">${p.keyCount > 1 ? `${p.keyCount} ${plural(p.keyCount, 'ключ', 'ключа', 'ключей')}` : p.keyHint || '1 ключ'}</span>`} |
| +добавлено | </div> |
| +добавлено | ${p.teamManaged ? html`<div class="faint xs">Ключи этого провайдера уже принадлежат команде — делиться ими не нужно.</div>` : html`<${Fragment}> |
| +добавлено | <div class="models">${p.models.map((m) => html`<label class=${'model-chip' + (sel.has(m) ? ' on' : '')} key=${m}> |
| +добавлено | <input type="checkbox" class="chk" checked=${sel.has(m)} onChange=${() => toggle(m)} />${m}</label>`)} |
| +добавлено | ${!p.models.length ? html`<span class="faint xs">Модели не указаны — будут доступны любые</span>` : null}</div> |
| +добавлено | <div class="row wrap" style="gap:8px"> |
| +добавлено | <input class="inp sm" type="number" min="0" style="width:120px" value=${limit} placeholder="лимит/день" aria-label="Лимит в день" onInput=${(e) => setLimit(e.currentTarget.value)} /> |
| +добавлено | <${Select} sm value=${access} options=${ACCESS_OPTS} label="Доступ" class="grow" onChange=${setAccess} /> |
| +добавлено | </div> |
| +добавлено | <div class="row"> |
| +добавлено | ${p.keyCount > 1 ? html`<label class="chk-row small muted"><input type="checkbox" class="chk" checked=${allKeys} onChange=${(e) => setAllKeys(e.currentTarget.checked)} />Все ${p.keyCount} ключа</label>` : null} |
| +добавлено | <span class="grow"></span> |
| +добавлено | <${AsyncButton} class="btn primary sm" disabled=${p.models.length > 0 && sel.size === 0} onClick=${share}><${Icon} name="share" size=${13} />Поделиться с командой<//> |
| +добавлено | </div> |
| +добавлено | <//>`} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- подключить к ZCode |
| +добавлено | |
| +добавлено | function ConnectSection({ s, keys, local }) { |
| +добавлено | const [provider, setProvider] = useState('openai'); |
| +добавлено | const allModels = useMemo(() => { |
| +добавлено | const set = new Set(); |
| +добавлено | for (const k of keys ?? []) { |
| +добавлено | if (k.disabledAt) continue; |
| +добавлено | if (provider && k.provider !== provider) continue; |
| +добавлено | for (const m of k.models?.length ? k.models : k.model ? [k.model] : []) set.add(m); |
| +добавлено | } |
| +добавлено | return [...set].sort(); |
| +добавлено | }, [keys, provider]); |
| +добавлено | const [sel, setSel] = useState(new Set()); |
| +добавлено | useEffect(() => setSel(new Set(allModels)), [allModels.join('|')]); |
| +добавлено | const connected = (local ?? []).filter((p) => p.teamManaged); |
| +добавлено | const connect = async () => { |
| +добавлено | const [r, err] = await act('connectTeamProvider', { teamId: s.teamId, provider, models: [...sel] }); |
| +добавлено | if (!err) { toast('Провайдер появился в Settings → Model settings', { kind: 'ok', timeout: 5000 }); invalidate('localProviders'); } |
| +добавлено | }; |
| +добавлено | const disconnect = async (p) => { |
| +добавлено | if (!(await confirmDialog({ title: `Отключить «${p.name}»?`, text: 'Провайдер исчезнет из настроек моделей ZCode. Ключи команды останутся на сервере.', ok: 'Отключить' }))) return; |
| +добавлено | const [, err] = await act('disconnectTeamProvider', { teamId: s.teamId, providerId: p.providerId }, { ok: 'Провайдер отключён' }); |
| +добавлено | if (!err) invalidate('localProviders'); |
| +добавлено | }; |
| +добавлено | return html`<div class="card"> |
| +добавлено | <div class="card-b stack-s"> |
| +добавлено | <div class="muted small">Модели команды появятся в ZCode как обычный провайдер. Запросы идут через прокси команды с учётом лимитов — секреты на ваш компьютер не попадают.</div> |
| +добавлено | <div class="row"> |
| +добавлено | <${Seg} value=${provider} onChange=${setProvider} label="API" options=${[{ id: 'openai', label: 'OpenAI API' }, { id: 'anthropic', label: 'Anthropic API' }]} /> |
| +добавлено | </div> |
| +добавлено | ${allModels.length ? html`<div class="models">${allModels.map((m) => html`<label class=${'model-chip' + (sel.has(m) ? ' on' : '')} key=${m}> |
| +добавлено | <input type="checkbox" class="chk" checked=${sel.has(m)} onChange=${() => setSel((x) => { const n = new Set(x); n.has(m) ? n.delete(m) : n.add(m); return n; })} />${m}</label>`)}</div>` |
| +добавлено | : html`<div class="faint xs">У ключей этого типа не указаны модели — будут доступны любые.</div>`} |
| +добавлено | <div class="row"><span class="grow"></span><${AsyncButton} class="btn primary" onClick=${connect} disabled=${allModels.length > 0 && !sel.size}><${Icon} name="plug" size=${14} />Подключить к ZCode<//></div> |
| +добавлено | </div> |
| +добавлено | ${connected.length ? html`<div class="list" style="border-top:1px solid var(--zt-border)">${connected.map((p) => html`<div class="li" key=${p.providerId}> |
| +добавлено | <span class="dot ok"></span> |
| +добавлено | <div class="grow"><div class="ell">${p.name}</div><div class="faint xs ell">${p.models.length ? p.models.join(', ') : 'любые модели'}</div></div> |
| +добавлено | <${AsyncButton} class="btn sm" onClick=${() => disconnect(p)}>Отключить<//> |
| +добавлено | </div>`)}</div>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- расход |
| +добавлено | |
| +добавлено | function UsageSection({ s }) { |
| +добавлено | const [days, setDays] = useState(14); |
| +добавлено | const u = useRes(`usage:${s.teamId}:${days}`, () => rpc('usage', { teamId: s.teamId, days })); |
| +добавлено | const d = u.data; |
| +добавлено | if (!d) return html`<div class="card pad stack-s"><${Skel} hgt=${12} w="40%" /><${Skel} hgt=${64} /><${Skel} hgt=${12} w="70%" /></div>`; |
| +добавлено | const max = Math.max(1, ...d.perDay.map((x) => x.requests)); |
| +добавлено | const total = d.perDay.reduce((a, b) => a + b.requests, 0); |
| +добавлено | const lim = d.limitPerUserPerDay; |
| +добавлено | const usedPct = lim ? Math.min(1, d.usedToday / lim) : 0; |
| +добавлено | const maxUser = Math.max(1, ...d.perUser.map((x) => x.requests)); |
| +добавлено | const maxKey = Math.max(1, ...d.perKey.map((x) => x.requests)); |
| +добавлено | return html`<div class="card"> |
| +добавлено | <div class="card-b stack"> |
| +добавлено | <div class="row"> |
| +добавлено | <div class="grow"><div class="faint xs">Всего за ${days} ${plural(days, 'день', 'дня', 'дней')}</div><div class="h1">${total.toLocaleString('ru-RU')}</div></div> |
| +добавлено | <${Seg} value=${days} onChange=${setDays} label="Период" options=${[{ id: 7, label: '7 д' }, { id: 14, label: '14 д' }, { id: 30, label: '30 д' }]} /> |
| +добавлено | </div> |
| +добавлено | <div class="bars" role="img" aria-label="Запросы по дням"> |
| +добавлено | ${d.perDay.map((x, i) => html`<div key=${x.day} class=${'bar' + (i === d.perDay.length - 1 ? ' today' : '')} title=${fmtDate(x.day) + ': ' + x.requests} |
| +добавлено | style=${{ height: Math.max(3, (x.requests / max) * 100) + '%', animationDelay: Math.min(i, 30) * 12 + 'ms' }}></div>`)} |
| +добавлено | </div> |
| +добавлено | <div class="row faint xs"><span>${fmtDate(d.perDay[0]?.day)}</span><span class="grow"></span><span>сегодня</span></div> |
| +добавлено | <div class="meter"> |
| +добавлено | <div class="row small"><span class="muted">Мой лимит сегодня</span><span class="grow"></span> |
| +добавлено | <span>${lim ? html`<b>${d.usedToday}</b> / ${lim} · осталось ${d.remainingToday}` : html`<b>${d.usedToday}</b> · без лимита`}</span></div> |
| +добавлено | ${lim ? html`<div class=${'progress' + (usedPct >= 1 ? ' err' : usedPct > 0.8 ? ' warn' : '')}><i style=${{ transform: `scaleX(${usedPct})` }}></i></div>` : null} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | ${d.perUser.length ? html`<div class="card-b stack-s" style="border-top:1px solid var(--zt-border)"> |
| +добавлено | <div class="sec-title">По участникам</div> |
| +добавлено | ${d.perUser.map((x) => html`<div class="row small" key=${x.userId}> |
| +добавлено | <${Avatar} name=${x.name} id=${x.userId} size=${20} /> |
| +добавлено | <span class="ell" style="width:110px;flex:none">${x.name}</span> |
| +добавлено | <div class="progress grow"><i style=${{ transform: `scaleX(${x.requests / maxUser})` }}></i></div> |
| +добавлено | <span class="mono xs" style="width:44px;text-align:right">${x.requests}</span> |
| +добавлено | </div>`)} |
| +добавлено | </div>` : null} |
| +добавлено | ${d.perKey.length ? html`<div class="card-b stack-s" style="border-top:1px solid var(--zt-border)"> |
| +добавлено | <div class="sec-title">По ключам</div> |
| +добавлено | ${d.perKey.map((x) => html`<div class="row small" key=${x.keyId}> |
| +добавлено | <${Icon} name="key" size=${14} class="faint" /> |
| +добавлено | <span class="ell" style="width:126px;flex:none">${x.label}</span> |
| +добавлено | <div class="progress grow ok"><i style=${{ transform: `scaleX(${x.requests / maxKey})` }}></i></div> |
| +добавлено | <span class="mono xs" style="width:44px;text-align:right">${x.requests}</span> |
| +добавлено | </div>`)} |
| +добавлено | </div>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- токены |
| +добавлено | |
| +добавлено | function TokensSection({ s, canManage }) { |
| +добавлено | const t = useRes(keyFor.proxyTokens(s.teamId), () => rpc('proxyTokens', { teamId: s.teamId })); |
| +добавлено | const revoke = async (x) => { |
| +добавлено | if (!(await confirmDialog({ title: 'Отозвать токен?', text: `Клиент, использующий этот токен (${x.provider}${x.model ? ' · ' + x.model : ''}), перестанет работать.`, ok: 'Отозвать' }))) return; |
| +добавлено | const [, err] = await act('revokeProxyToken', { teamId: s.teamId, tokenId: x.id }, { ok: 'Токен отозван' }); |
| +добавлено | if (!err) invalidate('proxyTokens'); |
| +добавлено | }; |
| +добавлено | if (!t.data) return html`<${SkelList} rows=${2} />`; |
| +добавлено | const list = t.data; |
| +добавлено | if (!list.length) return html`<div class="card"><${Empty} icon="lock" title="Токенов нет" text="Токены выпускаются, когда вы подключаете ключи команды к ZCode." /></div>`; |
| +добавлено | return html`<div class="card list">${list.map((x) => html`<div class=${'li' + (x.revokedAt ? ' faint' : '')} key=${x.id}> |
| +добавлено | <${Icon} name="lock" size=${15} class="faint" /> |
| +добавлено | <div class="grow"><div class="ell">${x.provider}${x.model ? html` · <span class="mono">${x.model}</span>` : ''}</div> |
| +добавлено | <div class="faint xs ell">${x.userName || '—'} · выдан ${relTime(x.createdAt)}${x.revokedAt ? ' · отозван ' + relTime(x.revokedAt) : ''}</div></div> |
| +добавлено | ${x.revokedAt ? html`<span class="pill">отозван</span>` : html`<${AsyncButton} class="btn sm danger" onClick=${() => revoke(x)}>Отозвать<//>`} |
| +добавлено | </div>`)}</div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вкладка |
| +добавлено | |
| +добавлено | function Section({ icon, title, extra, children, id }) { |
| +добавлено | return html`<section class="stack-s" id=${id}> |
| +добавлено | <div class="row" style="min-height:28px"><div class="sec-title"><${Icon} name=${icon} size=${14} />${title}</div><span class="grow"></span>${extra}</div> |
| +добавлено | ${children} |
| +добавлено | </section>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function KeysTab({ s }) { |
| +добавлено | const role = myRole(s); |
| +добавлено | const canManage = roleAtLeast(role, 'maintainer'); |
| +добавлено | const keys = useRes(keyFor.keys(s.teamId), () => rpc('keys', { teamId: s.teamId })); |
| +добавлено | const providers = useRes(keyFor.providers(s.teamId), () => rpc('providers', { teamId: s.teamId })); |
| +добавлено | const local = useRes('localProviders', () => rpc('localProviders', {})); |
| +добавлено | const [sheet, setSheet] = useState(null); // {key?} |
| +добавлено | const [checking, setChecking] = useState(false); |
| +добавлено | |
| +добавлено | const checkAll = async () => { |
| +добавлено | setChecking(true); |
| +добавлено | const [r, err] = await act('checkAllKeys', { teamId: s.teamId }); |
| +добавлено | setChecking(false); |
| +добавлено | if (r) { |
| +добавлено | const ok = r.filter((x) => x.ok).length; |
| +добавлено | toast(`Работают ${ok} из ${r.length}`, { kind: ok === r.length ? 'ok' : 'err' }); |
| +добавлено | invalidate('keys'); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | const list = keys.data ?? []; |
| +добавлено | const active = list.filter((k) => !k.disabledAt); |
| +добавлено | const okCount = active.filter((k) => k.ok === true).length; |
| +добавлено | |
| +добавлено | return html`<div class="pad stack" style="gap:20px"> |
| +добавлено | <${Section} icon="key" title=${'Общие ключи команды' + (list.length ? ` · ${okCount}/${active.length} в строю` : '')} |
| +добавлено | extra=${html`${list.length ? html`<button type="button" class="btn sm" disabled=${checking} onClick=${checkAll}>${checking ? html`<span class="spin"></span>` : html`<${Icon} name="zap" size=${13} />`}Проверить все</button>` : null} |
| +добавлено | ${canManage ? html`<button type="button" class="btn sm primary" onClick=${() => setSheet({})}><${Icon} name="plus" size=${13} />Добавить</button>` : null}`}> |
| +добавлено | ${!keys.data ? html`<${SkelList} rows=${3} />` |
| +добавлено | : !list.length ? html`<div class="card"><${Empty} icon="key" title="Ключей пока нет" text=${canManage ? 'Добавьте ключ провайдера или поделитесь своими провайдерами из ZCode ниже.' : 'Попросите мейнтейнера добавить ключ.'} /></div>` |
| +добавлено | : html`<div class="card">${list.map((k, i) => html`<${KeyCard} key=${k.id} s=${s} k=${k} i=${i} canManage=${canManage} onEdit=${(key) => setSheet({ key })} />`)}</div>`} |
| +добавлено | <//> |
| +добавлено | |
| +добавлено | ${canManage ? html`<${Section} icon="share" title="Поделиться моими провайдерами"> |
| +добавлено | ${!local.data ? html`<${SkelList} rows=${2} />` |
| +добавлено | : !local.data.length ? html`<div class="card"><${Empty} icon="plug" title="В ZCode нет провайдеров" text="Добавьте провайдера в Settings → Model settings, и он появится здесь." /></div>` |
| +добавлено | : html`<div class="card">${local.data.map((p, i) => html`<${LocalProviderCard} key=${p.providerId} s=${s} p=${p} i=${i} />`)}</div>`} |
| +добавлено | <//>` : null} |
| +добавлено | |
| +добавлено | <${Section} icon="plug" title="Подключить ключи команды к ZCode"> |
| +добавлено | <${ConnectSection} s=${s} keys=${keys.data} local=${local.data} /> |
| +добавлено | <//> |
| +добавлено | |
| +добавлено | <${Section} icon="chart" title="Расход"> |
| +добавлено | <${UsageSection} s=${s} /> |
| +добавлено | <//> |
| +добавлено | |
| +добавлено | <${Section} icon="lock" title="Токены доступа"> |
| +добавлено | <${TokensSection} s=${s} canManage=${canManage} /> |
| +добавлено | <//> |
| +добавлено | |
| +добавлено | <${KeySheet} s=${s} open=${!!sheet} onClose=${() => setSheet(null)} keyItem=${sheet?.key} providers=${providers.data} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | // Вкладка «Профиль»: аватар, имя, о себе, статус, пароль, сервер, выход, состояние плагина и IDE. |
| +добавлено | import { useEffect, useState } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, humanError, svc, saveSettings, AVATAR_COLORS, STATUS_RU, fmtDate, relTime, initials, colorFor, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | import { Avatar, Select, Field, AsyncButton, confirmDialog, AutoTextarea } from './ui.js'; |
| +добавлено | import { app, me, signOut, refreshSession } from './app-state.js'; |
| +добавлено | |
| +добавлено | const STATUS_OPTS = [ |
| +добавлено | { id: 'online', label: 'В сети' }, |
| +добавлено | { id: 'away', label: 'Отошёл' }, |
| +добавлено | { id: 'busy', label: 'Занят' }, |
| +добавлено | { id: 'dnd', label: 'Не беспокоить' }, |
| +добавлено | ]; |
| +добавлено | |
| +добавлено | export function ProfileTab({ s }) { |
| +добавлено | const user = me(s); |
| +добавлено | const [v, setV] = useState(() => ({ displayName: user?.displayName || '', bio: user?.bio || '', avatarColor: user?.avatarColor || colorFor(user?.id), status: user?.status || 'online' })); |
| +добавлено | const [dirty, setDirty] = useState(false); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | useEffect(() => { |
| +добавлено | if (!dirty && user) setV({ displayName: user.displayName || '', bio: user.bio || '', avatarColor: user.avatarColor || colorFor(user.id), status: user.status || 'online' }); |
| +добавлено | }, [user?.displayName, user?.bio, user?.avatarColor, user?.status]); |
| +добавлено | const set = (p) => { setV((x) => ({ ...x, ...p })); setDirty(true); setErr(''); }; |
| +добавлено | |
| +добавлено | const save = async () => { |
| +добавлено | if (!v.displayName.trim()) { setErr('Имя не может быть пустым'); return; } |
| +добавлено | try { |
| +добавлено | const updated = await rpc('updateProfile', { displayName: v.displayName.trim(), bio: v.bio.trim(), avatarColor: v.avatarColor, status: v.status }); |
| +добавлено | app.set((x) => ({ ...x, session: { ...x.session, user: { ...x.session.user, ...(updated?.user || updated || {}) } } })); |
| +добавлено | setDirty(false); |
| +добавлено | toast('Профиль сохранён', { kind: 'ok' }); |
| +добавлено | } catch (e) { setErr(humanError(e)); } |
| +добавлено | }; |
| +добавлено | const quickStatus = async (st) => { |
| +добавлено | set({ status: st }); |
| +добавлено | const [r, e] = await act('updateProfile', { status: st }, { ok: 'Статус: ' + STATUS_RU[st] }); |
| +добавлено | if (r) app.set((x) => ({ ...x, session: { ...x.session, user: { ...x.session.user, status: st } } })); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // пароль |
| +добавлено | const [pw, setPw] = useState({ cur: '', next: '', rep: '' }); |
| +добавлено | const [pwErr, setPwErr] = useState(''); |
| +добавлено | const [pwOpen, setPwOpen] = useState(false); |
| +добавлено | const changePw = async () => { |
| +добавлено | setPwErr(''); |
| +добавлено | if (!pw.cur || !pw.next) { setPwErr('Заполните оба поля'); return; } |
| +добавлено | if (pw.next.length < 8) { setPwErr('Новый пароль — минимум 8 символов'); return; } |
| +добавлено | if (pw.next !== pw.rep) { setPwErr('Пароли не совпадают'); return; } |
| +добавлено | try { |
| +добавлено | await rpc('changePassword', { currentPassword: pw.cur, newPassword: pw.next }); |
| +добавлено | setPw({ cur: '', next: '', rep: '' }); |
| +добавлено | setPwOpen(false); |
| +добавлено | toast('Пароль изменён', { kind: 'ok' }); |
| +добавлено | } catch (e) { setPwErr(e.status === 401 || e.status === 403 ? 'Текущий пароль неверный' : humanError(e)); } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // сервер |
| +добавлено | const [server, setServer] = useState(svc.state?.serverUrl || ''); |
| +добавлено | const saveServer = async () => { |
| +добавлено | const url = server.trim().replace(/\/+$/, ''); |
| +добавлено | if (!/^https?:\/\/.+/i.test(url)) { toast('Адрес должен начинаться с http(s)://', { kind: 'err' }); return; } |
| +добавлено | if (url === svc.state?.serverUrl) return; |
| +добавлено | if (!(await confirmDialog({ title: 'Сменить сервер?', text: 'Сессия на новом сервере может потребовать повторного входа.', ok: 'Сменить', danger: false }))) return; |
| +добавлено | await saveSettings({ serverUrl: url }); |
| +добавлено | toast('Сервер сохранён', { kind: 'ok' }); |
| +добавлено | refreshSession(); |
| +добавлено | }; |
| +добавлено | const logout = async () => { |
| +добавлено | if (!(await confirmDialog({ title: 'Выйти из аккаунта?', text: 'Панель забудет токены на этом компьютере. Aura IDE это не затронет.', ok: 'Выйти' }))) return; |
| +добавлено | await signOut(); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const st = s.state || svc.state || {}; |
| +добавлено | const plugin = st.plugin; |
| +добавлено | const ide = st.ide; |
| +добавлено | return html`<div class="pad stack" style="gap:18px;max-width:640px;margin:0 auto"> |
| +добавлено | <div class="card pad stack"> |
| +добавлено | <div class="profile-hero"> |
| +добавлено | <${Avatar} name=${v.displayName || user?.email} id=${user?.id} color=${v.avatarColor} size=${64} /> |
| +добавлено | <div class="grow"> |
| +добавлено | <div class="h1 ell">${v.displayName || '—'}</div> |
| +добавлено | <div class="muted small ell sel-text">${user?.email}</div> |
| +добавлено | <div class="faint xs">В Aura с ${fmtDate(user?.createdAt, true)}</div> |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | <${Field} label="Цвет аватара"> |
| +добавлено | <div class="palette" role="radiogroup" aria-label="Цвет аватара"> |
| +добавлено | ${AVATAR_COLORS.map((c) => html`<button type="button" class="swatch" key=${c} style=${{ background: c }} aria-pressed=${String(v.avatarColor?.toLowerCase() === c)} aria-label=${'Цвет ' + c} onClick=${() => set({ avatarColor: c })}></button>`)} |
| +добавлено | </div> |
| +добавлено | <//> |
| +добавлено | <${Field} label="Отображаемое имя"><input class="inp" value=${v.displayName} maxlength="60" onInput=${(e) => set({ displayName: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Email" hint="Email меняется в аккаунте Aura."><input class="inp" value=${user?.email || ''} disabled /><//> |
| +добавлено | <${Field} label="О себе"><${AutoTextarea} class="ta" value=${v.bio} maxlength="280" max=${160} placeholder="Чем занимаетесь в команде" onInput=${(e) => set({ bio: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Статус"><${Select} value=${v.status} options=${STATUS_OPTS} label="Статус" onChange=${(x) => (dirty ? set({ status: x }) : quickStatus(x))} /><//> |
| +добавлено | ${err ? html`<div class="err-box"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | <div class="row"><span class="faint xs grow">${dirty ? 'Есть несохранённые изменения' : ''}</span> |
| +добавлено | <button type="button" class="btn" disabled=${!dirty} onClick=${() => { setDirty(false); setV({ displayName: user.displayName || '', bio: user.bio || '', avatarColor: user.avatarColor || colorFor(user.id), status: user.status || 'online' }); }}>Сбросить</button> |
| +добавлено | <${AsyncButton} class="btn primary" disabled=${!dirty} onClick=${save}>Сохранить<//></div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="card"> |
| +добавлено | <button type="button" class="li click" style="width:100%;border:0;background:transparent;text-align:left" aria-expanded=${String(pwOpen)} onClick=${() => setPwOpen((o) => !o)}> |
| +добавлено | <${Icon} name="lock" size=${15} class="faint" /><span class="grow">Сменить пароль</span> |
| +добавлено | <span style=${{ display: 'grid', transition: 'transform .2s cubic-bezier(.22,1,.36,1)', transform: pwOpen ? 'rotate(180deg)' : 'none' }}><${Icon} name="chevron" size=${14} /></span> |
| +добавлено | </button> |
| +добавлено | ${pwOpen ? html`<div class="card-b stack-s reveal" style="border-top:1px solid var(--zt-border)"> |
| +добавлено | <${Field} label="Текущий пароль"><input class="inp" type="password" autocomplete="current-password" value=${pw.cur} onInput=${(e) => setPw({ ...pw, cur: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Новый пароль"><input class="inp" type="password" autocomplete="new-password" placeholder="Минимум 8 символов" value=${pw.next} onInput=${(e) => setPw({ ...pw, next: e.currentTarget.value })} /><//> |
| +добавлено | <${Field} label="Повторите"><input class="inp" type="password" autocomplete="new-password" value=${pw.rep} onInput=${(e) => setPw({ ...pw, rep: e.currentTarget.value })} /><//> |
| +добавлено | ${pwErr ? html`<div class="err-box"><${Icon} name="alert" />${pwErr}</div>` : null} |
| +добавлено | <div class="row" style="justify-content:flex-end"><${AsyncButton} class="btn primary" onClick=${changePw}>Сменить пароль<//></div> |
| +добавлено | </div>` : null} |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="server" size=${14} />Сервер</div> |
| +добавлено | <div class="row"><input class="inp sm mono grow" value=${server} aria-label="Адрес сервера" onInput=${(e) => setServer(e.currentTarget.value)} onKeyDown=${(e) => e.key === 'Enter' && saveServer()} /> |
| +добавлено | <button type="button" class="btn sq" disabled=${server.trim().replace(/\/+$/, '') === (svc.state?.serverUrl || '')} onClick=${saveServer}>Сохранить</button></div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="monitor" size=${14} />Окружение</div> |
| +добавлено | <div class="card"> |
| +добавлено | <div class="info-row"><span class="k">Плагин Aura Team</span><span class="v">${plugin ? (plugin.installed ? (plugin.enabled ? html`<span class="ok-t">в маркете: включён</span>` : html`<span class="warn-t">в маркете: выключен</span>`) : html`<span class="faint">не установлен</span>`) : html`<span class="faint">нет данных</span>`}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Папка в IDE</span><span class="v mono xs" title=${ide?.cwd || ''}>${ide?.cwd || '—'}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Ветка в IDE</span><span class="v mono xs">${ide?.branch || '—'}${ide?.at ? html` <span class="faint">· ${relTime(ide.at)}</span>` : null}</span></div> |
| +добавлено | <div class="info-row"><span class="k">Версия панели</span><span class="v faint">${st.version || '—'}</span></div> |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="card pad row danger-zone"> |
| +добавлено | <div class="grow"><div class="b">Выйти</div><div class="muted xs">Тот же аккаунт, что в Aura IDE — выход только из панели.</div></div> |
| +добавлено | <button type="button" class="btn danger" onClick=${logout}><${Icon} name="log-out" size=${14} />Выйти</button> |
| +добавлено | </div> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | // Вкладка «Задачи»: канбан с перетаскиванием на Pointer Events, фильтры, шторка задачи, корзина. |
| +добавлено | import { Fragment } from 'preact'; |
| +добавлено | import { useEffect, useLayoutEffect, useMemo, useRef, useState, useCallback } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, mutateRes, peekRes, invalidate, useRes, saveUi, svc, humanError, |
| +добавлено | TASK_STATUSES, STATUS_LABEL, PRIORITIES, PRIORITY_LABEL, shortId, copyText, fmtDate, fmtDateTime, relTime, |
| +добавлено | isOverdue, toDateInput, roleAtLeast, describeAction, reducedMotion, useTick, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | import { |
| +добавлено | Avatar, Seg, Select, Layer, AutoTextarea, Empty, Skel, MenuButton, AsyncButton, Field, confirmDialog, |
| +добавлено | } from './ui.js'; |
| +добавлено | import { keyFor, myRole, me } from './app-state.js'; |
| +добавлено | |
| +добавлено | const EASE = 'cubic-bezier(.22,1,.36,1)'; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- операции с задачами |
| +добавлено | |
| +добавлено | function boardKey(s) { return keyFor.board(s.teamId); } |
| +добавлено | |
| +добавлено | export async function updateTask(s, taskId, changes, members = []) { |
| +добавлено | const key = boardKey(s); |
| +добавлено | const snapshot = peekRes(key); |
| +добавлено | const patch = { ...changes }; |
| +добавлено | if ('assigneeId' in changes) patch.assigneeName = members.find((m) => m.id === changes.assigneeId)?.displayName ?? null; |
| +добавлено | mutateRes(key, (d) => d && { ...d, tasks: d.tasks.map((t) => (t.id === taskId ? { ...t, ...patch, updatedAt: new Date().toISOString() } : t)) }); |
| +добавлено | try { |
| +добавлено | await rpc('updateTask', { teamId: s.teamId, taskId, changes }); |
| +добавлено | invalidate(`taskHistory:${taskId}`); |
| +добавлено | return true; |
| +добавлено | } catch (e) { |
| +добавлено | mutateRes(key, snapshot); |
| +добавлено | toast(e.status === 403 ? 'Недостаточно прав' : 'Не удалось сохранить: ' + humanError(e), { kind: 'err' }); |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function deleteTaskWithUndo(s, task) { |
| +добавлено | const key = boardKey(s); |
| +добавлено | const snapshot = peekRes(key); |
| +добавлено | mutateRes(key, (d) => d && { ...d, tasks: d.tasks.filter((t) => t.id !== task.id) }); |
| +добавлено | try { |
| +добавлено | await rpc('deleteTask', { teamId: s.teamId, taskId: task.id }); |
| +добавлено | invalidate('trash'); |
| +добавлено | toast('Задача удалена', { |
| +добавлено | timeout: 6000, |
| +добавлено | action: { |
| +добавлено | label: 'Отменить', |
| +добавлено | onClick: async () => { |
| +добавлено | mutateRes(key, (d) => d && (d.tasks.some((t) => t.id === task.id) ? d : { ...d, tasks: [...d.tasks, task] })); |
| +добавлено | const [, err] = await act('restoreTask', { teamId: s.teamId, taskId: task.id }); |
| +добавлено | if (err) mutateRes(key, (d) => d && { ...d, tasks: d.tasks.filter((t) => t.id !== task.id) }); |
| +добавлено | invalidate('board', 'trash'); |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | } catch (e) { |
| +добавлено | mutateRes(key, snapshot); |
| +добавлено | toast(e.status === 403 ? 'Недостаточно прав' : humanError(e), { kind: 'err' }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Новый порядок колонки status: dragged вставляется перед видимой задачей beforeId (или в конец). */ |
| +добавлено | function computeOrder(tasks, status, draggedId, beforeId) { |
| +добавлено | const col = tasks.filter((t) => t.status === status && t.id !== draggedId).sort((a, b) => a.position - b.position).map((t) => t.id); |
| +добавлено | const at = beforeId ? col.indexOf(beforeId) : -1; |
| +добавлено | if (at < 0) col.push(draggedId); |
| +добавлено | else col.splice(at, 0, draggedId); |
| +добавлено | return col; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function reorder(s, status, orderedIds) { |
| +добавлено | const key = boardKey(s); |
| +добавлено | const snapshot = peekRes(key); |
| +добавлено | const pos = new Map(orderedIds.map((id, i) => [id, i])); |
| +добавлено | mutateRes(key, (d) => d && { ...d, tasks: d.tasks.map((t) => (pos.has(t.id) ? { ...t, status, position: pos.get(t.id) } : t)) }); |
| +добавлено | try { |
| +добавлено | await rpc('reorderTasks', { teamId: s.teamId, status, orderedIds }); |
| +добавлено | return true; |
| +добавлено | } catch (e) { |
| +добавлено | mutateRes(key, snapshot); |
| +добавлено | toast(e.status === 403 ? 'Недостаточно прав для перемещения' : 'Не удалось переместить: ' + humanError(e), { kind: 'err' }); |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- маленькие куски |
| +добавлено | |
| +добавлено | function PriorityFlag({ p }) { |
| +добавлено | if (!p || p === 'normal') return null; |
| +добавлено | return html`<span class=${'flag ' + p} title=${'Приоритет: ' + PRIORITY_LABEL[p]}><${Icon} name="flag" size=${13} stroke=${p === 'low' ? 1.75 : 2} /></span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function DueBadge({ due, status }) { |
| +добавлено | if (!due) return null; |
| +добавлено | const over = isOverdue(due, status); |
| +добавлено | return html`<span class=${'due' + (over ? ' over' : '')} title=${over ? 'Просрочено' : 'Срок'}><${Icon} name="calendar" size=${12} />${fmtDate(due)}</span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function LabelsEditor({ value = [], onChange, disabled, suggestions = [] }) { |
| +добавлено | const [text, setText] = useState(''); |
| +добавлено | const add = (raw) => { |
| +добавлено | const v = raw.trim().slice(0, 24); |
| +добавлено | if (!v || value.includes(v) || value.length >= 8) { setText(''); return; } |
| +добавлено | onChange([...value, v]); |
| +добавлено | setText(''); |
| +добавлено | }; |
| +добавлено | const listId = useMemo(() => 'lbls' + Math.random().toString(36).slice(2, 7), []); |
| +добавлено | return html`<div class="labels-ed"> |
| +добавлено | ${value.map((l) => html`<span class="tag" key=${l}>${l}${!disabled ? html`<button type="button" aria-label=${'Убрать метку ' + l} onClick=${() => onChange(value.filter((x) => x !== l))}><${Icon} name="x" size=${11} /></button>` : null}</span>`)} |
| +добавлено | ${!disabled && value.length < 8 ? html`<input value=${text} list=${listId} placeholder=${value.length ? '' : 'Добавить метку…'} aria-label="Новая метка" |
| +добавлено | onInput=${(e) => setText(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { |
| +добавлено | if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(text); } |
| +добавлено | else if (e.key === 'Backspace' && !text && value.length) onChange(value.slice(0, -1)); |
| +добавлено | }} |
| +добавлено | onBlur=${() => text && add(text)} /> |
| +добавлено | <datalist id=${listId}>${suggestions.filter((x) => !value.includes(x)).map((x) => html`<option value=${x} key=${x} />`)}</datalist>` : null} |
| +добавлено | ${disabled && !value.length ? html`<span class="faint small" style="padding:0 4px">Нет меток</span>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function DueInput({ value, onChange, disabled }) { |
| +добавлено | const v = toDateInput(value); |
| +добавлено | return html`<div class="row" style="gap:4px"> |
| +добавлено | <input type="date" class=${'inp sm' + (v ? '' : ' empty')} value=${v} disabled=${disabled} aria-label="Срок" |
| +добавлено | onChange=${(e) => { const x = e.currentTarget.value; onChange(x ? new Date(x + 'T12:00:00').toISOString() : null); }} /> |
| +добавлено | ${v && !disabled ? html`<button type="button" class="ibtn sm" title="Убрать срок" aria-label="Убрать срок" onClick=${() => onChange(null)}><${Icon} name="x" size=${14} /></button>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const memberOptions = (members) => [{ id: '', label: 'Не назначен' }, ...members.map((m) => ({ id: m.id, label: m.displayName }))]; |
| +добавлено | const prioOptions = PRIORITIES.map((p) => ({ id: p.id, label: p.label })); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- карточка |
| +добавлено | |
| +добавлено | function TaskCard({ t, member, readOnly, dragging, onPointerDown, onOpen, onKey }) { |
| +добавлено | return html`<div class=${'kcard prio-' + (t.priority || 'normal') + (readOnly ? ' ro' : '') + (dragging ? ' dragging' : '')} |
| +добавлено | style=${dragging ? { display: 'none' } : undefined} |
| +добавлено | data-id=${t.id} tabindex="0" role="button" aria-label=${t.title + ', ' + STATUS_LABEL[t.status]} |
| +добавлено | aria-roledescription=${readOnly ? undefined : 'перетаскиваемая карточка'} |
| +добавлено | onPointerDown=${onPointerDown} onKeyDown=${onKey} |
| +добавлено | onClick=${(e) => { if (readOnly || e.detail === 0) onOpen(); }}> |
| +добавлено | <div class="ttl">${t.title}</div> |
| +добавлено | ${t.labels?.length ? html`<div class="labels">${t.labels.slice(0, 4).map((l) => html`<span class="tag" key=${l}>${l}</span>`)}${t.labels.length > 4 ? html`<span class="tag">+${t.labels.length - 4}</span>` : null}</div>` : null} |
| +добавлено | <div class="meta"> |
| +добавлено | <${PriorityFlag} p=${t.priority} /> |
| +добавлено | <button type="button" class="sid" title="Скопировать #id" onPointerDown=${(e) => e.stopPropagation()} |
| +добавлено | onClick=${(e) => { e.stopPropagation(); copyText('#' + shortId(t.id), `Скопировано #${shortId(t.id)}`); }}>#${shortId(t.id)}</button> |
| +добавлено | <${DueBadge} due=${t.dueAt} status=${t.status} /> |
| +добавлено | ${member ? html`<${Avatar} name=${member.displayName} id=${member.id} color=${member.avatarColor} size=${20} title=${'Исполнитель: ' + member.displayName} />` |
| +добавлено | : t.assigneeName ? html`<${Avatar} name=${t.assigneeName} id=${t.assigneeId} size=${20} />` |
| +добавлено | : html`<span class="av s20 none" title="Без исполнителя"><${Icon} name="user" size=${11} /></span>`} |
| +добавлено | </div> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- быстрое добавление |
| +добавлено | |
| +добавлено | function QuickAdd({ s, status, onCreated }) { |
| +добавлено | const [open, setOpen] = useState(false); |
| +добавлено | const [text, setText] = useState(''); |
| +добавлено | const [busy, setBusy] = useState(false); |
| +добавлено | const ref = useRef(null); |
| +добавлено | useEffect(() => { if (open) ref.current?.focus(); }, [open]); |
| +добавлено | const submit = async () => { |
| +добавлено | const title = text.trim(); |
| +добавлено | if (!title || busy) return; |
| +добавлено | setBusy(true); |
| +добавлено | const [r, err] = await act('createTask', { teamId: s.teamId, title, status, priority: 'normal', labels: [] }); |
| +добавлено | setBusy(false); |
| +добавлено | if (err) return; |
| +добавлено | setText(''); |
| +добавлено | if (r?.id) { |
| +добавлено | mutateRes(boardKey(s), (d) => d && (d.tasks.some((t) => t.id === r.id) ? d : { ...d, tasks: [...d.tasks, { labels: [], priority: 'normal', position: 1e9, ...r }] })); |
| +добавлено | } |
| +добавлено | invalidate('board'); |
| +добавлено | onCreated?.(r); |
| +добавлено | ref.current?.focus(); |
| +добавлено | }; |
| +добавлено | if (!open) { |
| +добавлено | return html`<div class="kb-quick"><button type="button" class="kb-add" onClick=${() => setOpen(true)}><${Icon} name="plus" size=${14} />Добавить</button></div>`; |
| +добавлено | } |
| +добавлено | return html`<div class="kb-quick reveal"> |
| +добавлено | <input ref=${ref} class="inp" value=${text} placeholder="Название и Enter" disabled=${busy} aria-label=${'Новая задача: ' + STATUS_LABEL[status]} |
| +добавлено | onInput=${(e) => setText(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { |
| +добавлено | if (e.key === 'Enter') { e.preventDefault(); submit(); } |
| +добавлено | if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setOpen(false); setText(''); } |
| +добавлено | }} |
| +добавлено | onBlur=${() => { if (!text.trim()) setOpen(false); }} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- фильтры |
| +добавлено | |
| +добавлено | function useFilters() { |
| +добавлено | const saved = svc.state?.ui?.taskFilters || {}; |
| +добавлено | const [f, setF] = useState({ q: '', mode: saved.mode || 'all', assignees: saved.assignees || [], priorities: saved.priorities || [] }); |
| +добавлено | const update = (patch) => setF((cur) => { |
| +добавлено | const next = { ...cur, ...patch }; |
| +добавлено | saveUi({ taskFilters: { mode: next.mode, assignees: next.assignees, priorities: next.priorities } }); |
| +добавлено | return next; |
| +добавлено | }); |
| +добавлено | return [f, update]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function applyFilters(tasks, f, myId) { |
| +добавлено | const q = f.q.trim().toLowerCase().replace(/^#/, ''); |
| +добавлено | return tasks.filter((t) => { |
| +добавлено | if (f.mode === 'mine' && t.assigneeId !== myId) return false; |
| +добавлено | if (f.mode === 'unassigned' && t.assigneeId) return false; |
| +добавлено | if (f.assignees.length && !f.assignees.includes(t.assigneeId || '')) return false; |
| +добавлено | if (f.priorities.length && !f.priorities.includes(t.priority || 'normal')) return false; |
| +добавлено | if (q) { |
| +добавлено | const hay = (t.title + ' ' + (t.description || '') + ' ' + (t.labels || []).join(' ') + ' ' + shortId(t.id)).toLowerCase(); |
| +добавлено | if (!hay.includes(q)) return false; |
| +добавлено | } |
| +добавлено | return true; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- основной компонент |
| +добавлено | |
| +добавлено | export function TasksTab({ s, board, narrow }) { |
| +добавлено | const role = myRole(s); |
| +добавлено | const canEdit = roleAtLeast(role, 'dev'); |
| +добавлено | const user = me(s); |
| +добавлено | const [f, setF] = useFilters(); |
| +добавлено | const [openId, setOpenId] = useState(null); |
| +добавлено | const [creating, setCreating] = useState(false); |
| +добавлено | const [trashOpen, setTrashOpen] = useState(false); |
| +добавлено | const [drag, setDrag] = useState(null); // {id, status, index, height} |
| +добавлено | const dragRef = useRef(null); |
| +добавлено | const colsRef = useRef(null); |
| +добавлено | const scrollRef = useRef(null); |
| +добавлено | const focusAfter = useRef(null); |
| +добавлено | const prevPos = useRef(new Map()); |
| +добавлено | useTick(60000); |
| +добавлено | |
| +добавлено | const data = board.data; |
| +добавлено | const members = data?.members ?? []; |
| +добавлено | const memberById = useMemo(() => new Map(members.map((m) => [m.id, m])), [members]); |
| +добавлено | const visible = useMemo(() => (data ? applyFilters(data.tasks, f, user?.id) : []), [data, f, user?.id]); |
| +добавлено | const columns = useMemo(() => { |
| +добавлено | const by = Object.fromEntries(TASK_STATUSES.map((c) => [c.id, []])); |
| +добавлено | for (const t of visible) (by[t.status] ?? by.todo).push(t); |
| +добавлено | for (const k in by) by[k].sort((a, b) => a.position - b.position || String(a.createdAt).localeCompare(String(b.createdAt))); |
| +добавлено | return by; |
| +добавлено | }, [visible]); |
| +добавлено | const allLabels = useMemo(() => [...new Set((data?.tasks ?? []).flatMap((t) => t.labels || []))].sort(), [data]); |
| +добавлено | const filtersActive = f.mode !== 'all' || f.assignees.length || f.priorities.length || f.q.trim(); |
| +добавлено | |
| +добавлено | // FLIP: после каждого рендера сравниваем положения карточек (offset внутри .kb-cols — не зависит от прокрутки). |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | const root = colsRef.current; |
| +добавлено | if (!root) return; |
| +добавлено | const next = new Map(); |
| +добавлено | const animate = !reducedMotion(); |
| +добавлено | for (const el of root.querySelectorAll('.kcard[data-id]')) { |
| +добавлено | if (el.offsetParent === null) continue; |
| +добавлено | const id = el.dataset.id; |
| +добавлено | // offsetParent карточки — .kb-cols (position:relative), поэтому координаты не зависят от прокрутки. |
| +добавлено | const p = { x: el.offsetLeft, y: el.offsetTop }; |
| +добавлено | next.set(id, p); |
| +добавлено | const old = prevPos.current.get(id); |
| +добавлено | if (!animate) continue; |
| +добавлено | if (old) { |
| +добавлено | const dx = old.x - p.x; |
| +добавлено | const dy = old.y - p.y; |
| +добавлено | if (dx || dy) el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: 200, easing: EASE }); |
| +добавлено | } else if (prevPos.current.size) { |
| +добавлено | el.animate([{ opacity: 0, transform: 'translateY(4px)' }, { opacity: 1, transform: 'none' }], { duration: 220, easing: EASE }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | prevPos.current = next; |
| +добавлено | if (focusAfter.current) { |
| +добавлено | const el = root.querySelector(`.kcard[data-id="${focusAfter.current}"]`); |
| +добавлено | focusAfter.current = null; |
| +добавлено | el?.focus({ preventScroll: false }); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // ------------------------------------------------ drag |
| +добавлено | |
| +добавлено | const computeOver = (x, y) => { |
| +добавлено | const st = dragRef.current; |
| +добавлено | if (!st) return; |
| +добавлено | const hit = document.elementFromPoint(x, y); |
| +добавлено | const colEl = hit?.closest?.('.kb-col'); |
| +добавлено | if (!colEl || !colsRef.current?.contains(colEl)) return; |
| +добавлено | const status = colEl.dataset.status; |
| +добавлено | const cards = [...colEl.querySelectorAll('.kcard[data-id]')].filter((el) => el.dataset.id !== st.id); |
| +добавлено | let index = cards.length; |
| +добавлено | for (let i = 0; i < cards.length; i++) { |
| +добавлено | const r = cards[i].getBoundingClientRect(); |
| +добавлено | if (y < r.top + r.height / 2) { index = i; break; } |
| +добавлено | } |
| +добавлено | if (st.over?.status !== status || st.over?.index !== index) { |
| +добавлено | st.over = { status, index, beforeId: cards[index]?.dataset.id ?? null }; |
| +добавлено | setDrag((d) => d && { ...d, status, index }); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const autoScroll = () => { |
| +добавлено | const st = dragRef.current; |
| +добавлено | if (!st || st.dropping) return; |
| +добавлено | const { x, y } = st.last; |
| +добавлено | const sx = scrollRef.current; |
| +добавлено | const pane = sx?.closest('.pane'); |
| +добавлено | let moved = false; |
| +добавлено | if (sx) { |
| +добавлено | const r = sx.getBoundingClientRect(); |
| +добавлено | const edge = 48; |
| +добавлено | if (x < r.left + edge && sx.scrollLeft > 0) { sx.scrollLeft -= Math.ceil((r.left + edge - x) / 4); moved = true; } |
| +добавлено | else if (x > r.right - edge && sx.scrollLeft < sx.scrollWidth - sx.clientWidth) { sx.scrollLeft += Math.ceil((x - (r.right - edge)) / 4); moved = true; } |
| +добавлено | } |
| +добавлено | if (pane) { |
| +добавлено | const r = pane.getBoundingClientRect(); |
| +добавлено | const top = (sx?.getBoundingClientRect().top ?? r.top); |
| +добавлено | const edge = 40; |
| +добавлено | if (y < Math.max(r.top, top) + edge && pane.scrollTop > 0) { pane.scrollTop -= Math.ceil((Math.max(r.top, top) + edge - y) / 4); moved = true; } |
| +добавлено | else if (y > r.bottom - edge && pane.scrollTop < pane.scrollHeight - pane.clientHeight) { pane.scrollTop += Math.ceil((y - (r.bottom - edge)) / 4); moved = true; } |
| +добавлено | } |
| +добавлено | if (moved) computeOver(x, y); |
| +добавлено | st.raf = requestAnimationFrame(autoScroll); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const startDrag = (st) => { |
| +добавлено | const rect = st.el.getBoundingClientRect(); |
| +добавлено | const ghost = st.el.cloneNode(true); |
| +добавлено | ghost.classList.add('kb-ghost'); |
| +добавлено | if (!reducedMotion()) ghost.classList.add('lift'); |
| +добавлено | ghost.removeAttribute('tabindex'); |
| +добавлено | ghost.setAttribute('aria-hidden', 'true'); |
| +добавлено | Object.assign(ghost.style, { left: rect.left + 'px', top: rect.top + 'px', width: rect.width + 'px', height: rect.height + 'px', display: '' }); |
| +добавлено | document.body.append(ghost); |
| +добавлено | document.body.classList.add('dragging'); |
| +добавлено | st.ghost = ghost; |
| +добавлено | st.rect = rect; |
| +добавлено | st.active = true; |
| +добавлено | const status = st.task.status; |
| +добавлено | const colTasks = columns[status] ?? []; |
| +добавлено | const index = colTasks.findIndex((t) => t.id === st.id); |
| +добавлено | st.origin = { status, index }; |
| +добавлено | st.over = { status, index, beforeId: colTasks[index + 1]?.id ?? null }; |
| +добавлено | setDrag({ id: st.id, status, index, height: rect.height }); |
| +добавлено | st.raf = requestAnimationFrame(autoScroll); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const endDrag = (cancel) => { |
| +добавлено | const st = dragRef.current; |
| +добавлено | if (!st) return; |
| +добавлено | cancelAnimationFrame(st.raf); |
| +добавлено | window.removeEventListener('pointermove', st.onMove); |
| +добавлено | window.removeEventListener('pointerup', st.onUp); |
| +добавлено | window.removeEventListener('pointercancel', st.onCancel); |
| +добавлено | window.removeEventListener('keydown', st.onKeyDown, true); |
| +добавлено | if (!st.active) { dragRef.current = null; return; } |
| +добавлено | st.dropping = true; |
| +добавлено | const finish = () => { |
| +добавлено | st.ghost?.remove(); |
| +добавлено | document.body.classList.remove('dragging'); |
| +добавлено | dragRef.current = null; |
| +добавлено | const over = st.over; |
| +добавлено | const same = cancel || !over || (over.status === st.origin.status && over.index === st.origin.index); |
| +добавлено | if (!same) { |
| +добавлено | const order = computeOrder(data.tasks, over.status, st.id, over.beforeId); |
| +добавлено | reorder(s, over.status, order); |
| +добавлено | } |
| +добавлено | setDrag(null); |
| +добавлено | }; |
| +добавлено | const ph = colsRef.current?.querySelector('.kb-ph'); |
| +добавлено | if (ph && st.ghost && !reducedMotion() && !cancel) { |
| +добавлено | const tr = ph.getBoundingClientRect(); |
| +добавлено | st.ghost.classList.remove('lift'); |
| +добавлено | st.ghost.classList.add('drop'); |
| +добавлено | st.ghost.style.transform = `translate(${tr.left - st.rect.left}px, ${tr.top - st.rect.top}px)`; |
| +добавлено | setTimeout(finish, 180); |
| +добавлено | } else finish(); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const onCardPointerDown = (t) => (e) => { |
| +добавлено | if (e.button !== 0 || !canEdit || dragRef.current) return; |
| +добавлено | if (e.target.closest('button, a, input')) return; |
| +добавлено | const el = e.currentTarget; |
| +добавлено | const st = { id: t.id, task: t, el, startX: e.clientX, startY: e.clientY, last: { x: e.clientX, y: e.clientY }, active: false, pointerId: e.pointerId }; |
| +добавлено | st.onMove = (ev) => { |
| +добавлено | if (ev.pointerId !== st.pointerId) return; |
| +добавлено | st.last = { x: ev.clientX, y: ev.clientY }; |
| +добавлено | if (!st.active) { |
| +добавлено | if (Math.hypot(ev.clientX - st.startX, ev.clientY - st.startY) < 5) return; |
| +добавлено | startDrag(st); |
| +добавлено | } |
| +добавлено | ev.preventDefault(); |
| +добавлено | st.ghost.style.transform = `translate(${ev.clientX - st.startX}px, ${ev.clientY - st.startY}px)`; |
| +добавлено | computeOver(ev.clientX, ev.clientY); |
| +добавлено | }; |
| +добавлено | st.onUp = (ev) => { |
| +добавлено | if (ev.pointerId !== st.pointerId) return; |
| +добавлено | if (!st.active) { endDrag(true); setOpenId(t.id); return; } |
| +добавлено | endDrag(false); |
| +добавлено | }; |
| +добавлено | st.onCancel = () => endDrag(true); |
| +добавлено | st.onKeyDown = (ev) => { if (ev.key === 'Escape' && st.active) { ev.preventDefault(); ev.stopPropagation(); endDrag(true); } }; |
| +добавлено | dragRef.current = st; |
| +добавлено | window.addEventListener('pointermove', st.onMove, { passive: false }); |
| +добавлено | window.addEventListener('pointerup', st.onUp); |
| +добавлено | window.addEventListener('pointercancel', st.onCancel); |
| +добавлено | window.addEventListener('keydown', st.onKeyDown, true); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | useEffect(() => () => { const st = dragRef.current; if (st) { st.ghost?.remove(); document.body.classList.remove('dragging'); cancelAnimationFrame(st.raf); } }, []); |
| +добавлено | |
| +добавлено | // ------------------------------------------------ клавиатура |
| +добавлено | |
| +добавлено | const onCardKey = (t) => (e) => { |
| +добавлено | if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpenId(t.id); return; } |
| +добавлено | const ci = TASK_STATUSES.findIndex((c) => c.id === t.status); |
| +добавлено | const col = columns[t.status] ?? []; |
| +добавлено | const i = col.findIndex((x) => x.id === t.id); |
| +добавлено | if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { |
| +добавлено | if (e.altKey && canEdit) { |
| +добавлено | e.preventDefault(); |
| +добавлено | const j = e.key === 'ArrowDown' ? i + 1 : i - 1; |
| +добавлено | if (j < 0 || j >= col.length) return; |
| +добавлено | const before = e.key === 'ArrowDown' ? col[j + 1]?.id ?? null : col[j].id; |
| +добавлено | focusAfter.current = t.id; |
| +добавлено | reorder(s, t.status, computeOrder(data.tasks, t.status, t.id, before)); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | e.preventDefault(); |
| +добавлено | const n = col[e.key === 'ArrowDown' ? i + 1 : i - 1]; |
| +добавлено | if (n) colsRef.current?.querySelector(`.kcard[data-id="${n.id}"]`)?.focus(); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { |
| +добавлено | e.preventDefault(); |
| +добавлено | const dir = e.key === 'ArrowRight' ? 1 : -1; |
| +добавлено | for (let k = ci + dir; k >= 0 && k < TASK_STATUSES.length; k += dir) { |
| +добавлено | const target = columns[TASK_STATUSES[k].id]?.[Math.min(i, (columns[TASK_STATUSES[k].id]?.length ?? 1) - 1)]; |
| +добавлено | if (target) { colsRef.current?.querySelector(`.kcard[data-id="${target.id}"]`)?.focus(); return; } |
| +добавлено | } |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if ((e.key === '[' || e.key === ']') && canEdit) { |
| +добавлено | e.preventDefault(); |
| +добавлено | const ni = ci + (e.key === ']' ? 1 : -1); |
| +добавлено | if (ni < 0 || ni >= TASK_STATUSES.length) return; |
| +добавлено | const ns = TASK_STATUSES[ni].id; |
| +добавлено | focusAfter.current = t.id; |
| +добавлено | reorder(s, ns, computeOrder(data.tasks, ns, t.id, null)); |
| +добавлено | toast(`Перемещено в «${STATUS_LABEL[ns]}»`, { timeout: 1800 }); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // ------------------------------------------------ рендер |
| +добавлено | |
| +добавлено | const openTask = data?.tasks.find((t) => t.id === openId) ?? null; |
| +добавлено | |
| +добавлено | const prioItems = PRIORITIES.map((p) => ({ |
| +добавлено | label: p.label, icon: 'flag', checked: f.priorities.includes(p.id), |
| +добавлено | onClick: () => setF({ priorities: f.priorities.includes(p.id) ? f.priorities.filter((x) => x !== p.id) : [...f.priorities, p.id] }), |
| +добавлено | })); |
| +добавлено | const assigneeItems = [ |
| +добавлено | ...members.map((m) => ({ |
| +добавлено | label: m.displayName, icon: 'user', checked: f.assignees.includes(m.id), |
| +добавлено | onClick: () => setF({ assignees: f.assignees.includes(m.id) ? f.assignees.filter((x) => x !== m.id) : [...f.assignees, m.id] }), |
| +добавлено | })), |
| +добавлено | { sep: true, hidden: !f.assignees.length }, |
| +добавлено | { label: 'Сбросить', icon: 'x', hidden: !f.assignees.length, onClick: () => setF({ assignees: [] }) }, |
| +добавлено | ]; |
| +добавлено | const selAssignees = f.assignees.map((id) => memberById.get(id)).filter(Boolean); |
| +добавлено | |
| +добавлено | return html`<div class="kb"> |
| +добавлено | <div class="kb-tools"> |
| +добавлено | <div class="row"> |
| +добавлено | <div class="inp-icon grow"> |
| +добавлено | <${Icon} name="search" size=${14} /> |
| +добавлено | <input class="inp sm" value=${f.q} placeholder="Поиск по задачам или #id" aria-label="Поиск задач" |
| +добавлено | onInput=${(e) => setF({ q: e.currentTarget.value })} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Escape' && f.q) { e.preventDefault(); e.stopPropagation(); setF({ q: '' }); } }} /> |
| +добавлено | ${f.q ? html`<button type="button" class="ibtn sm clr" aria-label="Очистить поиск" onClick=${() => setF({ q: '' })}><${Icon} name="x" size=${13} /></button>` : null} |
| +добавлено | </div> |
| +добавлено | <button type="button" class="ibtn" title="Корзина" aria-label="Корзина" onClick=${() => setTrashOpen(true)}><${Icon} name="trash" /></button> |
| +добавлено | ${canEdit ? html`<button type="button" class="btn primary" onClick=${() => setCreating(true)}><${Icon} name="plus" size=${14} />${narrow ? '' : 'Задача'}</button>` : null} |
| +добавлено | </div> |
| +добавлено | <div class="row" style="gap:6px;overflow-x:auto;scrollbar-width:none"> |
| +добавлено | <div class="chips" style="flex-wrap:nowrap"> |
| +добавлено | ${[{ id: 'all', label: 'Все' }, { id: 'mine', label: 'Мои' }, { id: 'unassigned', label: 'Без исполнителя' }].map((c) => html`<button type="button" class="chip" key=${c.id} |
| +добавлено | aria-pressed=${String(f.mode === c.id)} onClick=${() => setF({ mode: c.id })}>${c.label}</button>`)} |
| +добавлено | </div> |
| +добавлено | <span class="grow"></span> |
| +добавлено | <${MenuButton} class=${'chip' + (f.assignees.length ? '' : '')} items=${assigneeItems} label="Фильтр по исполнителю" width=${220}> |
| +добавлено | ${selAssignees.length ? html`<span class="av-stack" style="padding-left:5px">${selAssignees.slice(0, 3).map((m) => html`<${Avatar} key=${m.id} name=${m.displayName} id=${m.id} color=${m.avatarColor} size=${18} />`)}</span>` : html`<${Icon} name="users" size=${13} />`} |
| +добавлено | ${narrow ? '' : 'Исполнитель'} |
| +добавлено | <//> |
| +добавлено | <${MenuButton} class="chip" items=${prioItems} label="Фильтр по приоритету" width=${190}> |
| +добавлено | <${Icon} name="flag" size=${13} />${narrow ? '' : 'Приоритет'}${f.priorities.length ? html`<span class="badge">${f.priorities.length}</span>` : null} |
| +добавлено | <//> |
| +добавлено | ${filtersActive ? html`<button type="button" class="ibtn sm" title="Сбросить фильтры" aria-label="Сбросить фильтры" onClick=${() => setF({ q: '', mode: 'all', assignees: [], priorities: [] })}><${Icon} name="x" size=${14} /></button>` : null} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | ${!data ? html`<div class="kb-scroll"><div class="kb-cols">${TASK_STATUSES.map((c, i) => html`<div class="kb-col" key=${c.id}> |
| +добавлено | <div class="kb-col-h"><${Skel} w=${80} hgt=${12} /></div> |
| +добавлено | <div class="kb-list">${Array.from({ length: 3 - (i % 2) }, (_, k) => html`<${Skel} key=${k} hgt=${68 - k * 8} r=${10} />`)}</div> |
| +добавлено | </div>`)}</div></div>` |
| +добавлено | : board.error && !data ? html`<${Empty} icon="alert" title="Не удалось загрузить доску" text=${humanError(board.error)}><button class="btn" onClick=${board.reload}>Повторить</button><//>` |
| +добавлено | : html`<div class="kb-scroll" ref=${scrollRef}> |
| +добавлено | <div class="kb-cols" ref=${colsRef} role="list"> |
| +добавлено | ${TASK_STATUSES.map((c) => { |
| +добавлено | const list = columns[c.id] ?? []; |
| +добавлено | const hot = drag && drag.status === c.id; |
| +добавлено | const visibleCount = list.filter((t) => t.id !== drag?.id).length; |
| +добавлено | let k = 0; |
| +добавлено | const items = []; |
| +добавлено | list.forEach((t) => { |
| +добавлено | const isDragged = drag?.id === t.id; |
| +добавлено | if (hot && !isDragged && k === drag.index) items.push(html`<div class="kb-ph" key="__ph" style=${{ height: drag.height + 'px' }}></div>`); |
| +добавлено | if (!isDragged) k++; |
| +добавлено | const m = memberById.get(t.assigneeId); |
| +добавлено | items.push(html`<${TaskCard} key=${t.id} t=${t} member=${m} readOnly=${!canEdit} dragging=${isDragged} |
| +добавлено | onPointerDown=${onCardPointerDown(t)} onOpen=${() => setOpenId(t.id)} onKey=${onCardKey(t)} />`); |
| +добавлено | }); |
| +добавлено | if (hot && drag.index >= k) items.push(html`<div class="kb-ph" key="__ph" style=${{ height: drag.height + 'px' }}></div>`); |
| +добавлено | return html`<section class=${'kb-col' + (hot ? ' hot' : '')} key=${c.id} data-status=${c.id} role="listitem" aria-label=${c.label}> |
| +добавлено | <div class="kb-col-h"><span class=${'st ' + c.id}></span><span class="ell">${c.label}</span><span class="cnt">${visibleCount}</span></div> |
| +добавлено | <div class="kb-list"> |
| +добавлено | ${items} |
| +добавлено | ${!list.length && !hot ? html`<div class="kb-empty-col">${filtersActive ? 'Нет задач по фильтру' : 'Пусто'}</div>` : null} |
| +добавлено | </div> |
| +добавлено | ${canEdit ? html`<${QuickAdd} s=${s} status=${c.id} />` : null} |
| +добавлено | </section>`; |
| +добавлено | })} |
| +добавлено | </div> |
| +добавлено | ${canEdit ? html`<div class="faint xs" style="padding:10px 2px 0">Перетащите карточку или используйте <span class="kbd">[</span> <span class="kbd">]</span> для смены колонки, <span class="kbd">Alt</span>+<span class="kbd">↑↓</span> — порядок.</div>` |
| +добавлено | : html`<div class="faint xs" style="padding:10px 2px 0"><${Icon} name="eye" size=${12} /> Режим наблюдателя: доска только для чтения.</div>`} |
| +добавлено | </div>`} |
| +добавлено | |
| +добавлено | <${TaskDrawer} s=${s} task=${openTask} open=${!!openTask} onClose=${() => setOpenId(null)} members=${members} canEdit=${canEdit} allLabels=${allLabels} /> |
| +добавлено | <${NewTaskSheet} s=${s} open=${creating} onClose=${() => setCreating(false)} members=${members} allLabels=${allLabels} onCreated=${(t) => t?.id && setOpenId(null)} /> |
| +добавлено | <${TrashSheet} s=${s} open=${trashOpen} onClose=${() => setTrashOpen(false)} canEdit=${canEdit} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- шторка задачи |
| +добавлено | |
| +добавлено | function TaskDrawer({ s, task, open, onClose, members, canEdit, allLabels }) { |
| +добавлено | const [last, setLast] = useState(task); |
| +добавлено | useEffect(() => { if (task) setLast(task); }, [task]); |
| +добавлено | const t = task || last; |
| +добавлено | const [title, setTitle] = useState(t?.title ?? ''); |
| +добавлено | const [desc, setDesc] = useState(t?.description ?? ''); |
| +добавлено | const editing = useRef({ title: false, desc: false }); |
| +добавлено | useEffect(() => { |
| +добавлено | if (!t) return; |
| +добавлено | if (!editing.current.title) setTitle(t.title); |
| +добавлено | if (!editing.current.desc) setDesc(t.description ?? ''); |
| +добавлено | }, [t?.id, t?.title, t?.description]); |
| +добавлено | |
| +добавлено | const history = useRes(open && t ? `taskHistory:${t.id}` : null, () => rpc('taskHistory', { teamId: s.teamId, taskId: t.id })); |
| +добавлено | const commits = useRes(open && t ? `taskCommits:${t.id}` : null, () => rpc('taskCommits', { teamId: s.teamId, taskId: t.id })); |
| +добавлено | |
| +добавлено | const save = (changes) => t && updateTask(s, t.id, changes, members); |
| +добавлено | const commitTitle = () => { |
| +добавлено | editing.current.title = false; |
| +добавлено | const v = title.trim(); |
| +добавлено | if (!t) return; |
| +добавлено | if (!v) { setTitle(t.title); return; } |
| +добавлено | if (v !== t.title) save({ title: v }); |
| +добавлено | }; |
| +добавлено | const commitDesc = () => { |
| +добавлено | editing.current.desc = false; |
| +добавлено | if (t && desc !== (t.description ?? '')) save({ description: desc }); |
| +добавлено | }; |
| +добавлено | const close = () => { if (editing.current.title) commitTitle(); if (editing.current.desc) commitDesc(); onClose(); }; |
| +добавлено | |
| +добавлено | if (!t) return null; |
| +добавлено | const creator = members.find((m) => m.id === t.createdBy); |
| +добавлено | return html`<${Layer} open=${open} onClose=${close} title=${html`<span class="mono faint" style="font-size:12px">#${shortId(t.id)}</span>`} label="Задача" |
| +добавлено | headExtra=${html`<${Fragment}> |
| +добавлено | <button type="button" class="ibtn" title="Скопировать #id" aria-label="Скопировать id" onClick=${() => copyText('#' + shortId(t.id))}><${Icon} name="copy" /></button> |
| +добавлено | ${canEdit ? html`<button type="button" class="ibtn danger" title="Удалить задачу" aria-label="Удалить задачу" onClick=${() => { onClose(); deleteTaskWithUndo(s, t); }}><${Icon} name="trash" /></button>` : null} |
| +добавлено | <//>`}> |
| +добавлено | <div class="stack" style="gap:16px"> |
| +добавлено | <${AutoTextarea} class="title-edit" value=${title} rows="1" disabled=${!canEdit} aria-label="Название задачи" max=${200} |
| +добавлено | onFocus=${() => { editing.current.title = true; }} |
| +добавлено | onInput=${(e) => setTitle(e.currentTarget.value.replace(/\n/g, ' '))} |
| +добавлено | onBlur=${commitTitle} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); } }} /> |
| +добавлено | <${Seg} block value=${t.status} disabled=${!canEdit} label="Статус" onChange=${(v) => save({ status: v })} |
| +добавлено | options=${TASK_STATUSES.map((x) => ({ id: x.id, label: x.label }))} /> |
| +добавлено | <div class="props"> |
| +добавлено | <span class="k">Приоритет</span> |
| +добавлено | <${Select} sm value=${t.priority || 'normal'} disabled=${!canEdit} label="Приоритет" options=${prioOptions} onChange=${(v) => save({ priority: v })} /> |
| +добавлено | <span class="k">Исполнитель</span> |
| +добавлено | <div class="row" style="gap:6px"> |
| +добавлено | ${t.assigneeId ? html`<${Avatar} name=${members.find((m) => m.id === t.assigneeId)?.displayName || t.assigneeName || '?'} id=${t.assigneeId} color=${members.find((m) => m.id === t.assigneeId)?.avatarColor} size=${24} />` : null} |
| +добавлено | <${Select} sm value=${t.assigneeId || ''} disabled=${!canEdit} label="Исполнитель" options=${memberOptions(members)} onChange=${(v) => save({ assigneeId: v || null })} /> |
| +добавлено | </div> |
| +добавлено | <span class="k">Срок</span> |
| +добавлено | <${DueInput} value=${t.dueAt} disabled=${!canEdit} onChange=${(v) => save({ dueAt: v })} /> |
| +добавлено | <span class="k" style="align-self:start;padding-top:7px">Метки</span> |
| +добавлено | <${LabelsEditor} value=${t.labels || []} disabled=${!canEdit} suggestions=${allLabels} onChange=${(v) => save({ labels: v })} /> |
| +добавлено | </div> |
| +добавлено | <${Field} label="Описание"> |
| +добавлено | <${AutoTextarea} class="ta" value=${desc} disabled=${!canEdit} max=${360} placeholder=${canEdit ? 'Добавьте описание… Поддерживается Markdown.' : 'Без описания'} |
| +добавлено | onFocus=${() => { editing.current.desc = true; }} |
| +добавлено | onInput=${(e) => setDesc(e.currentTarget.value)} onBlur=${commitDesc} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); e.currentTarget.blur(); } }} /> |
| +добавлено | <//> |
| +добавлено | <div class="faint xs">Создал(а) ${creator?.displayName || '—'} · ${fmtDateTime(t.createdAt)}${t.updatedAt && t.updatedAt !== t.createdAt ? ' · изменено ' + relTime(t.updatedAt) : ''}</div> |
| +добавлено | |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="git-commit" size=${14} />Связанные коммиты</div> |
| +добавлено | ${commits.loading && !commits.data ? html`<${Skel} hgt=${36} />` |
| +добавлено | : !commits.data?.length ? html`<div class="faint small">Нет коммитов. Упомяните <span class="mono">#${shortId(t.id)}</span> в сообщении коммита.</div>` |
| +добавлено | : html`<div class="card list">${commits.data.map((c) => html`<div class="li" key=${c.hash} style="min-height:38px"> |
| +добавлено | <${Icon} name="git-commit" size=${14} class="faint" /> |
| +добавлено | <span class="mono">${c.hash.slice(0, 7)}</span> |
| +добавлено | <span class="muted small grow ell">${c.author || ''}</span> |
| +добавлено | <span class="faint xs">${relTime(c.createdAt)}</span> |
| +добавлено | ${/^https?:\/\//.test(c.repositoryUrl || '') ? html`<a class="ibtn sm" href=${c.repositoryUrl.replace(/\.git$/, '') + '/commit/' + c.hash} target="_blank" rel="noopener" title="Открыть" aria-label="Открыть коммит"><${Icon} name="external" size=${13} /></a>` : null} |
| +добавлено | <button type="button" class="ibtn sm" title="Скопировать хэш" aria-label="Скопировать хэш" onClick=${() => copyText(c.hash, 'Хэш скопирован')}><${Icon} name="copy" size=${13} /></button> |
| +добавлено | </div>`)}</div>`} |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="history" size=${14} />История</div> |
| +добавлено | ${history.loading && !history.data ? html`<div class="stack-s"><${Skel} hgt=${12} w="70%" /><${Skel} hgt=${12} w="55%" /></div>` |
| +добавлено | : !history.data?.length ? html`<div class="faint small">Изменений пока нет.</div>` |
| +добавлено | : html`<div class="timeline">${history.data.map((h, i) => html`<div class="tl-item" key=${i}> |
| +добавлено | <div><b>${h.userName}</b> <span class="muted">${describeAction({ ...h, taskTitle: '' }).replace(/ «»/g, '')}</span></div> |
| +добавлено | <div class="when">${fmtDateTime(h.createdAt)}</div> |
| +добавлено | </div>`)}</div>`} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- новая задача |
| +добавлено | |
| +добавлено | function NewTaskSheet({ s, open, onClose, members, allLabels }) { |
| +добавлено | const empty = { title: '', description: '', status: 'todo', priority: 'normal', assigneeId: '', labels: [], dueAt: null }; |
| +добавлено | const [v, setV] = useState(empty); |
| +добавлено | const [err, setErr] = useState(''); |
| +добавлено | useEffect(() => { if (open) { setV({ ...empty, assigneeId: me(s)?.id || '' }); setErr(''); } }, [open]); |
| +добавлено | const set = (patch) => setV((x) => ({ ...x, ...patch })); |
| +добавлено | const submit = async (e) => { |
| +добавлено | e?.preventDefault?.(); |
| +добавлено | if (!v.title.trim()) { setErr('Введите название'); return; } |
| +добавлено | try { |
| +добавлено | const r = await rpc('createTask', { teamId: s.teamId, ...v, title: v.title.trim(), assigneeId: v.assigneeId || null }); |
| +добавлено | if (r?.id) mutateRes(boardKey(s), (d) => d && (d.tasks.some((t) => t.id === r.id) ? d : { ...d, tasks: [...d.tasks, { position: 1e9, ...v, ...r }] })); |
| +добавлено | invalidate('board'); |
| +добавлено | toast('Задача создана', { kind: 'ok' }); |
| +добавлено | onClose(); |
| +добавлено | } catch (ex) { setErr(humanError(ex)); } |
| +добавлено | }; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title="Новая задача" initialFocus="input" |
| +добавлено | footer=${html`<button type="button" class="btn" onClick=${onClose}>Отмена</button><${AsyncButton} class="btn primary" onClick=${submit}>Создать задачу<//>`}> |
| +добавлено | <form class="stack" onSubmit=${submit}> |
| +добавлено | <${Field} label="Название"><input class=${'inp' + (err ? ' err' : '')} value=${v.title} maxlength="200" placeholder="Что нужно сделать?" onInput=${(e) => { set({ title: e.currentTarget.value }); setErr(''); }} /><//> |
| +добавлено | <${Field} label="Описание"><${AutoTextarea} class="ta" value=${v.description} max=${220} placeholder="Подробности, ссылки, критерии готовности" onInput=${(e) => set({ description: e.currentTarget.value })} /><//> |
| +добавлено | <${Seg} block value=${v.status} label="Статус" onChange=${(x) => set({ status: x })} options=${TASK_STATUSES} /> |
| +добавлено | <div class="props"> |
| +добавлено | <span class="k">Приоритет</span><${Select} sm value=${v.priority} options=${prioOptions} label="Приоритет" onChange=${(x) => set({ priority: x })} /> |
| +добавлено | <span class="k">Исполнитель</span><${Select} sm value=${v.assigneeId} options=${memberOptions(members)} label="Исполнитель" onChange=${(x) => set({ assigneeId: x })} /> |
| +добавлено | <span class="k">Срок</span><${DueInput} value=${v.dueAt} onChange=${(x) => set({ dueAt: x })} /> |
| +добавлено | <span class="k" style="align-self:start;padding-top:7px">Метки</span><${LabelsEditor} value=${v.labels} suggestions=${allLabels} onChange=${(x) => set({ labels: x })} /> |
| +добавлено | </div> |
| +добавлено | ${err ? html`<div class="err-box"><${Icon} name="alert" />${err}</div>` : null} |
| +добавлено | <button type="submit" hidden></button> |
| +добавлено | </form> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- корзина |
| +добавлено | |
| +добавлено | function TrashSheet({ s, open, onClose, canEdit }) { |
| +добавлено | const trash = useRes(open ? keyFor.trash(s.teamId) : null, () => rpc('trash', { teamId: s.teamId })); |
| +добавлено | const restore = async (t) => { |
| +добавлено | mutateRes(keyFor.trash(s.teamId), (d) => d && d.filter((x) => x.id !== t.id)); |
| +добавлено | const [, err] = await act('restoreTask', { teamId: s.teamId, taskId: t.id }, { ok: `Задача «${t.title}» восстановлена` }); |
| +добавлено | invalidate('board', 'trash'); |
| +добавлено | if (err) invalidate('trash'); |
| +добавлено | }; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title="Корзина"> |
| +добавлено | ${trash.loading && !trash.data ? html`<div class="stack-s">${[0, 1, 2].map((i) => html`<${Skel} key=${i} hgt=${40} />`)}</div>` |
| +добавлено | : !trash.data?.length ? html`<${Empty} icon="trash" title="Корзина пуста" text="Удалённые задачи появятся здесь — их можно восстановить." />` |
| +добавлено | : html`<div class="card list">${trash.data.map((t, i) => html`<div class="li enter-item" key=${t.id} style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms' }}> |
| +добавлено | <div class="grow"><div class="ell">${t.title}</div><div class="faint xs">${STATUS_LABEL[t.status] || t.status} · удалено ${relTime(t.deletedAt)}</div></div> |
| +добавлено | ${canEdit ? html`<${AsyncButton} class="btn sm" onClick=${() => restore(t)}><${Icon} name="restore" size=${13} />Восстановить<//>` : null} |
| +добавлено | </div>`)}</div>`} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | // Вкладка «Команда»: участники, роли, квоты, приглашения, каталог, выход. |
| +добавлено | import { Fragment } from 'preact'; |
| +добавлено | import { useEffect, useMemo, useState, useRef } from 'preact/hooks'; |
| +добавлено | import { |
| +добавлено | html, rpc, act, toast, useRes, invalidate, mutateRes, humanError, ROLE_RU, STATUS_RU, roleAtLeast, relTime, |
| +добавлено | fmtDateTime, copyText, plural, debounce, |
| +добавлено | } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | import { Avatar, Layer, Select, Empty, SkelList, RoleBadge, AsyncButton, Field, MenuButton, confirmDialog, Seg } from './ui.js'; |
| +добавлено | import { keyFor, myRole, me, currentTeam, refreshSession, selectTeam } from './app-state.js'; |
| +добавлено | |
| +добавлено | const ROLE_DESC = { |
| +добавлено | owner: 'Всё, включая роли и удаление команды', |
| +добавлено | maintainer: 'Участники, ключи, приглашения', |
| +добавлено | dev: 'Задачи, файлы, общие ключи', |
| +добавлено | viewer: 'Только просмотр', |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function QuotaEditor({ s, m, onDone }) { |
| +добавлено | const [v, setV] = useState(m.dailyQuota == null ? '' : String(m.dailyQuota)); |
| +добавлено | const ref = useRef(null); |
| +добавлено | useEffect(() => { ref.current?.focus(); ref.current?.select(); }, []); |
| +добавлено | const save = async () => { |
| +добавлено | const n = v.trim() === '' ? null : Math.max(0, Math.floor(Number(v))); |
| +добавлено | if (n !== null && !Number.isFinite(n)) { toast('Введите число', { kind: 'err' }); return; } |
| +добавлено | const [, err] = await act('setQuota', { teamId: s.teamId, memberId: m.id, dailyRequests: n }, { ok: n == null ? 'Лимит снят' : `Лимит: ${n} запросов в день` }); |
| +добавлено | if (!err) { invalidate('board'); onDone(); } |
| +добавлено | }; |
| +добавлено | return html`<div class="row reveal" style="gap:4px"> |
| +добавлено | <input ref=${ref} class="inp sm" type="number" min="0" style="width:96px" value=${v} placeholder="без лимита" aria-label="Запросов в день" |
| +добавлено | onInput=${(e) => setV(e.currentTarget.value)} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter') save(); if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); onDone(); } }} /> |
| +добавлено | <button type="button" class="ibtn sm" title="Сохранить" aria-label="Сохранить" onClick=${save}><${Icon} name="check" size=${14} /></button> |
| +добавлено | <button type="button" class="ibtn sm" title="Без лимита" aria-label="Без лимита" onClick=${() => { setV(''); }}><${Icon} name="x" size=${14} /></button> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function MemberRow({ s, m, i, tasksCount, myId, role }) { |
| +добавлено | const [quotaEdit, setQuotaEdit] = useState(false); |
| +добавлено | const isMe = m.id === myId; |
| +добавлено | const canManage = roleAtLeast(role, 'maintainer') && !isMe && m.role !== 'owner' && (role === 'owner' || m.role !== 'maintainer'); |
| +добавлено | const canRole = role === 'owner' && !isMe && m.role !== 'owner'; |
| +добавлено | const setRole = async (r) => { |
| +добавлено | if (r === m.role) return; |
| +добавлено | mutateRes(keyFor.board(s.teamId), (d) => d && { ...d, members: d.members.map((x) => (x.id === m.id ? { ...x, role: r } : x)) }); |
| +добавлено | const [, err] = await act('setRole', { teamId: s.teamId, memberId: m.id, role: r }, { ok: `${m.displayName}: ${ROLE_RU[r]}` }); |
| +добавлено | invalidate('board'); |
| +добавлено | }; |
| +добавлено | const remove = async () => { |
| +добавлено | if (!(await confirmDialog({ title: `Исключить ${m.displayName}?`, text: 'Участник потеряет доступ к задачам, ключам и файлам команды. Назначенные на него задачи останутся.', ok: 'Исключить' }))) return; |
| +добавлено | const [, err] = await act('removeMember', { teamId: s.teamId, memberId: m.id }, { ok: `${m.displayName} исключён(а)` }); |
| +добавлено | if (!err) invalidate('board'); |
| +добавлено | }; |
| +добавлено | const st = m.status && m.status !== 'online' ? STATUS_RU[m.status] : null; |
| +добавлено | return html`<div class="li enter-item" style=${{ animationDelay: Math.min(i, 5) * 18 + 'ms', alignItems: 'flex-start', paddingTop: '10px', paddingBottom: '10px' }}> |
| +добавлено | <${Avatar} name=${m.displayName} id=${m.id} color=${m.avatarColor} size=${32} online=${m.online} status=${m.status} /> |
| +добавлено | <div class="grow stack-s" style="gap:3px"> |
| +добавлено | <div class="row" style="gap:6px"> |
| +добавлено | <span class="b ell">${m.displayName}</span> |
| +добавлено | ${isMe ? html`<span class="pill" style="height:18px">вы</span>` : null} |
| +добавлено | <span class="grow"></span> |
| +добавлено | ${canRole ? html`<${Select} sm class="role-sel" value=${m.role} label=${'Роль ' + m.displayName} |
| +добавлено | options=${['maintainer', 'dev', 'viewer'].map((r) => ({ id: r, label: ROLE_RU[r] }))} onChange=${setRole} />` |
| +добавлено | : html`<${RoleBadge} role=${m.role} />`} |
| +добавлено | </div> |
| +добавлено | ${m.email ? html`<div class="muted xs ell sel-text">${m.email}</div>` : null} |
| +добавлено | <div class="row wrap faint xs" style="gap:4px 10px"> |
| +добавлено | <span>${m.online ? html`<span class="ok-t">в сети</span>` : m.lastSeenAt ? 'был(а) ' + relTime(m.lastSeenAt) : 'не заходил(а)'}</span> |
| +добавлено | ${st ? html`<span>· ${st}</span>` : null} |
| +добавлено | <span>· ${tasksCount} ${plural(tasksCount, 'задача', 'задачи', 'задач')}</span> |
| +добавлено | ${quotaEdit ? null : html`<span>· лимит: ${m.dailyQuota == null ? 'без лимита' : m.dailyQuota + '/день'}</span>`} |
| +добавлено | </div> |
| +добавлено | ${m.bio ? html`<div class="muted xs" style="margin-top:2px">${m.bio}</div>` : null} |
| +добавлено | ${quotaEdit ? html`<${QuotaEditor} s=${s} m=${m} onDone=${() => setQuotaEdit(false)} />` : null} |
| +добавлено | </div> |
| +добавлено | ${roleAtLeast(role, 'maintainer') ? html`<${MenuButton} label=${'Действия: ' + m.displayName} items=${[ |
| +добавлено | { label: 'Лимит запросов в день…', icon: 'zap', onClick: () => setQuotaEdit(true), hidden: m.role === 'owner' && role !== 'owner' }, |
| +добавлено | { sep: true, hidden: !canManage }, |
| +добавлено | { label: 'Исключить из команды', icon: 'log-out', danger: true, onClick: remove, hidden: !canManage }, |
| +добавлено | ]} />` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- приглашение |
| +добавлено | |
| +добавлено | function InviteSheet({ s, open, onClose }) { |
| +добавлено | const role = myRole(s); |
| +добавлено | const [inviteRole, setInviteRole] = useState('dev'); |
| +добавлено | const invite = useRes(open ? keyFor.invite(s.teamId) : null, () => rpc('invite', { teamId: s.teamId })); |
| +добавлено | const [q, setQ] = useState(''); |
| +добавлено | const [dirRole, setDirRole] = useState('dev'); |
| +добавлено | const [results, setResults] = useState(null); |
| +добавлено | const [searching, setSearching] = useState(false); |
| +добавлено | const search = useMemo(() => debounce(async (text) => { |
| +добавлено | if (!text.trim()) { setResults(null); setSearching(false); return; } |
| +добавлено | try { setResults(await rpc('directory', { teamId: s.teamId, q: text.trim() })); } catch (e) { setResults([]); toast(humanError(e), { kind: 'err' }); } |
| +добавлено | setSearching(false); |
| +добавлено | }, 280), [s.teamId]); |
| +добавлено | useEffect(() => { if (!open) { setQ(''); setResults(null); } }, [open]); |
| +добавлено | |
| +добавлено | const roleOpts = [ |
| +добавлено | ...(role === 'owner' ? [{ id: 'maintainer', label: ROLE_RU.maintainer }] : []), |
| +добавлено | { id: 'dev', label: ROLE_RU.dev }, |
| +добавлено | { id: 'viewer', label: ROLE_RU.viewer }, |
| +добавлено | ]; |
| +добавлено | const create = async () => { |
| +добавлено | const [r, err] = await act('createInvite', { teamId: s.teamId, role: inviteRole }); |
| +добавлено | if (!err) { mutateRes(keyFor.invite(s.teamId), { ...r, canRevoke: true }); toast('Код создан', { kind: 'ok' }); } |
| +добавлено | }; |
| +добавлено | const revoke = async () => { |
| +добавлено | const [, err] = await act('revokeInvite', { teamId: s.teamId }, { ok: 'Приглашение отозвано' }); |
| +добавлено | if (!err) mutateRes(keyFor.invite(s.teamId), { code: null, expiresAt: null, role: null, canRevoke: false }); |
| +добавлено | }; |
| +добавлено | const add = async (u) => { |
| +добавлено | const [, err] = await act('addMember', { teamId: s.teamId, userId: u.id, role: dirRole }, { ok: `${u.displayName} добавлен(а)` }); |
| +добавлено | if (!err) { setResults((r) => r?.map((x) => (x.id === u.id ? { ...x, inTeam: true } : x))); invalidate('board'); } |
| +добавлено | }; |
| +добавлено | const inv = invite.data; |
| +добавлено | return html`<${Layer} kind="sheet" open=${open} onClose=${onClose} title="Пригласить в команду"> |
| +добавлено | <div class="stack" style="gap:18px"> |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="link" size=${14} />Код приглашения</div> |
| +добавлено | ${invite.loading && !inv ? html`<div class="skel" style="height:58px;border-radius:10px"></div>` |
| +добавлено | : inv?.code ? html`<div class="stack-s reveal"> |
| +добавлено | <div class="invite-code"><span class="sel-text">${inv.code}</span> |
| +добавлено | <button type="button" class="ibtn" title="Скопировать код" aria-label="Скопировать код" onClick=${() => copyText(inv.code, 'Код скопирован')}><${Icon} name="copy" /></button></div> |
| +добавлено | <div class="row small muted"><span>Роль: <b style="color:var(--zt-fg)">${ROLE_RU[inv.role] || inv.role}</b></span><span>·</span><span>действует до ${fmtDateTime(inv.expiresAt)}</span> |
| +добавлено | <span class="grow"></span>${inv.canRevoke !== false ? html`<${AsyncButton} class="btn sm danger" onClick=${revoke}>Отозвать<//>` : null}</div> |
| +добавлено | </div>` |
| +добавлено | : html`<div class="muted small">Активного кода нет. Создайте код и отправьте его коллеге — он введёт его в «Вступить по коду».</div>`} |
| +добавлено | <div class="row wrap"> |
| +добавлено | <${Seg} value=${inviteRole} onChange=${setInviteRole} options=${roleOpts} label="Роль приглашения" /> |
| +добавлено | <span class="grow"></span> |
| +добавлено | <${AsyncButton} class="btn primary" onClick=${create}><${Icon} name="plus" size=${14} />${inv?.code ? 'Новый код' : 'Создать код'}<//> |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | <hr class="divider" /> |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="search" size=${14} />Добавить из каталога</div> |
| +добавлено | <div class="row"> |
| +добавлено | <div class="inp-icon grow"><${Icon} name="search" size=${14} /> |
| +добавлено | <input class="inp sm" value=${q} placeholder="Имя или email" aria-label="Поиск по каталогу" |
| +добавлено | onInput=${(e) => { setQ(e.currentTarget.value); setSearching(true); search(e.currentTarget.value); }} /></div> |
| +добавлено | <${Select} sm value=${dirRole} options=${roleOpts} label="Роль" class="role-sel" onChange=${setDirRole} /> |
| +добавлено | </div> |
| +добавлено | ${searching ? html`<${SkelList} rows=${2} />` |
| +добавлено | : results == null ? html`<div class="faint small">Найдите зарегистрированного пользователя Aura и добавьте его сразу, без кода.</div>` |
| +добавлено | : !results.length ? html`<div class="faint small">Никого не нашли по «${q}».</div>` |
| +добавлено | : html`<div class="card list">${results.map((u) => html`<div class="li" key=${u.id}> |
| +добавлено | <${Avatar} name=${u.displayName} id=${u.id} size=${24} /> |
| +добавлено | <div class="grow"><div class="ell">${u.displayName}</div>${u.email ? html`<div class="faint xs ell">${u.email}</div>` : null}</div> |
| +добавлено | ${u.inTeam ? html`<span class="pill ok"><${Icon} name="check" size=${12} />в команде</span>` : html`<${AsyncButton} class="btn sm" onClick=${() => add(u)}><${Icon} name="user-plus" size=${13} />Добавить<//>`} |
| +добавлено | </div>`)}</div>`} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- вкладка |
| +добавлено | |
| +добавлено | export function TeamTab({ s, board }) { |
| +добавлено | const team = currentTeam(s); |
| +добавлено | const role = myRole(s); |
| +добавлено | const user = me(s); |
| +добавлено | const [inviteOpen, setInviteOpen] = useState(false); |
| +добавлено | const [renaming, setRenaming] = useState(false); |
| +добавлено | const [name, setName] = useState(team?.name || ''); |
| +добавлено | useEffect(() => setName(team?.name || ''), [team?.name]); |
| +добавлено | const data = board.data; |
| +добавлено | const members = useMemo(() => { |
| +добавлено | const list = [...(data?.members ?? [])]; |
| +добавлено | const rank = { owner: 0, maintainer: 1, dev: 2, viewer: 3 }; |
| +добавлено | return list.sort((a, b) => (b.online - a.online) || (rank[a.role] - rank[b.role]) || a.displayName.localeCompare(b.displayName, 'ru')); |
| +добавлено | }, [data?.members]); |
| +добавлено | const counts = useMemo(() => { |
| +добавлено | const c = {}; |
| +добавлено | for (const t of data?.tasks ?? []) if (t.assigneeId && t.status !== 'done') c[t.assigneeId] = (c[t.assigneeId] || 0) + 1; |
| +добавлено | return c; |
| +добавлено | }, [data?.tasks]); |
| +добавлено | |
| +добавлено | const rename = async () => { |
| +добавлено | const v = name.trim(); |
| +добавлено | setRenaming(false); |
| +добавлено | if (!v || v === team.name) { setName(team.name); return; } |
| +добавлено | const [, err] = await act('renameTeam', { teamId: s.teamId, name: v }, { ok: 'Команда переименована' }); |
| +добавлено | if (err) setName(team.name); |
| +добавлено | refreshSession(); |
| +добавлено | }; |
| +добавлено | const leave = async () => { |
| +добавлено | if (!(await confirmDialog({ title: `Покинуть «${team.name}»?`, text: 'Вы потеряете доступ к задачам, ключам и файлам команды. Вернуться можно только по новому приглашению.', ok: 'Покинуть' }))) return; |
| +добавлено | const [, err] = await act('leaveTeam', { teamId: s.teamId }, { ok: 'Вы покинули команду' }); |
| +добавлено | if (!err) { await selectTeam(null); refreshSession(); } |
| +добавлено | }; |
| +добавлено | const online = members.filter((m) => m.online).length; |
| +добавлено | |
| +добавлено | return html`<div class="pad stack"> |
| +добавлено | <div class="card pad stack-s"> |
| +добавлено | <div class="row"> |
| +добавлено | <span class="team-tile lg">${(team?.name || '?').split(/\s+/).map((x) => x[0]).join('').slice(0, 2).toUpperCase()}</span> |
| +добавлено | <div class="grow"> |
| +добавлено | ${renaming ? html`<input class="inp" value=${name} maxlength="60" aria-label="Название команды" ref=${(el) => el && requestAnimationFrame(() => el.focus())} |
| +добавлено | onInput=${(e) => setName(e.currentTarget.value)} onBlur=${rename} |
| +добавлено | onKeyDown=${(e) => { if (e.key === 'Enter') e.currentTarget.blur(); if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setName(team.name); setRenaming(false); } }} />` |
| +добавлено | : html`<div class="row" style="gap:4px"><span class="h2 ell">${team?.name}</span> |
| +добавлено | ${roleAtLeast(role, 'maintainer') ? html`<button type="button" class="ibtn sm" title="Переименовать" aria-label="Переименовать команду" onClick=${() => setRenaming(true)}><${Icon} name="pencil" size=${13} /></button>` : null}</div>`} |
| +добавлено | <div class="row muted xs" style="gap:6px;margin-top:2px">${members.length} ${plural(members.length, 'участник', 'участника', 'участников')} · ${online} в сети</div> |
| +добавлено | </div> |
| +добавлено | <${RoleBadge} role=${role} /> |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="stack-s"> |
| +добавлено | <div class="row"><div class="sec-title"><${Icon} name="users" size=${14} />Участники</div><span class="grow"></span> |
| +добавлено | ${roleAtLeast(role, 'maintainer') ? html`<button type="button" class="btn primary" onClick=${() => setInviteOpen(true)}><${Icon} name="user-plus" size=${14} />Пригласить</button>` : null} |
| +добавлено | </div> |
| +добавлено | ${!data ? html`<${SkelList} rows=${4} />` |
| +добавлено | : html`<div class="card list">${members.map((m, i) => html`<${MemberRow} key=${m.id} s=${s} m=${m} i=${i} tasksCount=${counts[m.id] || 0} myId=${user?.id} role=${role} />`)}</div>`} |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | <div class="card pad stack-s"> |
| +добавлено | <div class="sec-title"><${Icon} name="shield" size=${14} />Роли</div> |
| +добавлено | <div class="legend"> |
| +добавлено | ${['owner', 'maintainer', 'dev', 'viewer'].map((r) => html`<${Fragment} key=${r}><${RoleBadge} role=${r} /><span class="d">${ROLE_DESC[r]}</span><//>`)} |
| +добавлено | </div> |
| +добавлено | </div> |
| +добавлено | |
| +добавлено | ${role !== 'owner' ? html`<div class="card pad danger-zone row"> |
| +добавлено | <div class="grow"><div class="b">Покинуть команду</div><div class="muted xs">Доступ пропадёт сразу.</div></div> |
| +добавлено | <button type="button" class="btn danger" onClick=${leave}><${Icon} name="log-out" size=${14} />Покинуть</button> |
| +добавлено | </div>` : null} |
| +добавлено | |
| +добавлено | <${InviteSheet} s=${s} open=${inviteOpen} onClose=${() => setInviteOpen(false)} /> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | // UI-примитивы: аватары, сегменты, поповеры, слои (шторки/диалоги) с фокус-ловушкой, тосты, пустые состояния. |
| +добавлено | import { h, Fragment } from 'preact'; |
| +добавлено | import { useEffect, useLayoutEffect, useRef, useState, useCallback } from 'preact/hooks'; |
| +добавлено | import { html, createStore, useStore, toasts, dismissToast, initials, colorFor, reducedMotion } from './core.js'; |
| +добавлено | import { Icon } from './icons.js'; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- стек слоёв (Esc) |
| +добавлено | |
| +добавлено | const layerStack = []; |
| +добавлено | export function pushLayer(close) { |
| +добавлено | const entry = { close }; |
| +добавлено | layerStack.push(entry); |
| +добавлено | return () => { |
| +добавлено | const i = layerStack.indexOf(entry); |
| +добавлено | if (i >= 0) layerStack.splice(i, 1); |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | export function hasLayers() { return layerStack.length > 0; } |
| +добавлено | export function closeTopLayer() { |
| +добавлено | const top = layerStack[layerStack.length - 1]; |
| +добавлено | if (top) { top.close(); return true; } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- аватар |
| +добавлено | |
| +добавлено | export function Avatar({ name, id, color, size = 24, online, status, title }) { |
| +добавлено | const st = status && status !== 'online' ? status : ''; |
| +добавлено | return html`<span class=${'av s' + size} style=${{ background: colorFor(id || name, color) }} title=${title ?? name}> |
| +добавлено | ${initials(name)} |
| +добавлено | ${online ? html`<i class=${'on ' + st}></i>` : null} |
| +добавлено | </span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function AvatarStack({ members = [], max = 4 }) { |
| +добавлено | const shown = members.slice(0, max); |
| +добавлено | const rest = members.length - shown.length; |
| +добавлено | return html`<div class="av-stack" title=${members.map((m) => m.displayName).join(', ')}> |
| +добавлено | ${shown.map((m) => html`<${Avatar} key=${m.id} name=${m.displayName} id=${m.id} color=${m.avatarColor} size=${20} title=${m.displayName + ' — в сети'} />`)} |
| +добавлено | ${rest > 0 ? html`<span class="av s20 more">+${rest}</span>` : null} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- сегментированный контрол |
| +добавлено | |
| +добавлено | export function Seg({ value, options, onChange, block, disabled, label }) { |
| +добавлено | const ref = useRef(null); |
| +добавлено | const [thumb, setThumb] = useState(null); |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | const root = ref.current; |
| +добавлено | if (!root) return; |
| +добавлено | const measure = () => { |
| +добавлено | const btn = root.querySelector('button[aria-pressed="true"]'); |
| +добавлено | if (!btn) return setThumb(null); |
| +добавлено | setThumb({ x: btn.offsetLeft, w: btn.offsetWidth }); |
| +добавлено | }; |
| +добавлено | measure(); |
| +добавлено | const ro = new ResizeObserver(measure); |
| +добавлено | ro.observe(root); |
| +добавлено | return () => ro.disconnect(); |
| +добавлено | }, [value, options.length]); |
| +добавлено | return html`<div class=${'seg' + (block ? ' block' : '')} ref=${ref} role="group" aria-label=${label}> |
| +добавлено | ${thumb ? html`<span class="thumb" style=${{ width: thumb.w + 'px', transform: `translateX(${thumb.x - 2}px)`, left: '2px' }}></span>` : null} |
| +добавлено | ${options.map((o) => html`<button type="button" key=${o.id} aria-pressed=${String(o.id === value)} disabled=${disabled} |
| +добавлено | onClick=${() => !disabled && onChange(o.id)}>${o.label}</button>`)} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- select (нативный, стилизованный) |
| +добавлено | |
| +добавлено | export function Select({ value, onChange, options, sm, disabled, label, class: cls = '' }) { |
| +добавлено | return html`<select class=${'sel ' + (sm ? 'sm ' : '') + cls} value=${value ?? ''} disabled=${disabled} aria-label=${label} |
| +добавлено | onChange=${(e) => onChange(e.currentTarget.value)}> |
| +добавлено | ${options.map((o) => html`<option key=${o.id} value=${o.id}>${o.label}</option>`)} |
| +добавлено | </select>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- авто-высота textarea |
| +добавлено | |
| +добавлено | export function useAutosize(ref, value, max = 400) { |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | const el = ref.current; |
| +добавлено | if (!el) return; |
| +добавлено | el.style.height = 'auto'; |
| +добавлено | const hgt = Math.min(el.scrollHeight + 2, max); |
| +добавлено | el.style.height = hgt + 'px'; |
| +добавлено | el.style.overflowY = el.scrollHeight + 2 > max ? 'auto' : 'hidden'; |
| +добавлено | }, [value]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function AutoTextarea({ value, onInput, max = 400, class: cls = 'ta', ...rest }) { |
| +добавлено | const ref = useRef(null); |
| +добавлено | useAutosize(ref, value, max); |
| +добавлено | return html`<textarea ref=${ref} class=${cls} value=${value} onInput=${onInput} ...${rest}></textarea>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- поповер |
| +добавлено | |
| +добавлено | export function Popover({ anchor, onClose, children, align = 'left', width }) { |
| +добавлено | const ref = useRef(null); |
| +добавлено | const [pos, setPos] = useState(null); |
| +добавлено | useLayoutEffect(() => { |
| +добавлено | if (!anchor) return; |
| +добавлено | const r = anchor.getBoundingClientRect(); |
| +добавлено | const el = ref.current; |
| +добавлено | const w = el?.offsetWidth || width || 220; |
| +добавлено | const hgt = el?.offsetHeight || 200; |
| +добавлено | let left = align === 'right' ? r.right - w : r.left; |
| +добавлено | left = Math.max(8, Math.min(left, window.innerWidth - w - 8)); |
| +добавлено | let top = r.bottom + 4; |
| +добавлено | if (top + hgt > window.innerHeight - 8) top = Math.max(8, r.top - hgt - 4); |
| +добавлено | setPos({ left, top }); |
| +добавлено | }, [anchor]); |
| +добавлено | useEffect(() => { |
| +добавлено | const pop = pushLayer(onClose); |
| +добавлено | const onDown = (e) => { |
| +добавлено | if (ref.current?.contains(e.target) || anchor?.contains(e.target)) return; |
| +добавлено | onClose(); |
| +добавлено | }; |
| +добавлено | document.addEventListener('pointerdown', onDown, true); |
| +добавлено | const first = ref.current?.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'); |
| +добавлено | first?.focus({ preventScroll: true }); |
| +добавлено | return () => { pop(); document.removeEventListener('pointerdown', onDown, true); }; |
| +добавлено | }, []); |
| +добавлено | const onKey = (e) => { |
| +добавлено | if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return; |
| +добавлено | const items = [...ref.current.querySelectorAll('.mi:not(:disabled)')]; |
| +добавлено | if (!items.length) return; |
| +добавлено | e.preventDefault(); |
| +добавлено | const i = items.indexOf(document.activeElement); |
| +добавлено | const n = e.key === 'ArrowDown' ? (i + 1) % items.length : (i - 1 + items.length) % items.length; |
| +добавлено | items[n].focus(); |
| +добавлено | }; |
| +добавлено | return html`<div class="pop" role="menu" ref=${ref} onKeyDown=${onKey} |
| +добавлено | style=${{ left: (pos?.left ?? -9999) + 'px', top: (pos?.top ?? -9999) + 'px', width: width ? width + 'px' : undefined, transformOrigin: align === 'right' ? 'top right' : 'top left' }}> |
| +добавлено | ${children} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Кнопка с выпадающим меню. items: [{label, icon, onClick, danger, checked, sep, hidden, disabled}] */ |
| +добавлено | export function MenuButton({ items, icon = 'more', label = 'Ещё', class: cls = 'ibtn', align = 'right', children, width }) { |
| +добавлено | const [open, setOpen] = useState(false); |
| +добавлено | const ref = useRef(null); |
| +добавлено | const visible = items.filter((i) => !i.hidden); |
| +добавлено | if (!visible.length) return null; |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <button type="button" class=${cls} ref=${ref} aria-haspopup="menu" aria-expanded=${String(open)} title=${label} aria-label=${label} |
| +добавлено | onClick=${(e) => { e.stopPropagation(); setOpen((o) => !o); }} onPointerDown=${(e) => e.stopPropagation()}> |
| +добавлено | ${children ?? html`<${Icon} name=${icon} />`} |
| +добавлено | </button> |
| +добавлено | ${open ? html`<${Popover} anchor=${ref.current} align=${align} width=${width} onClose=${() => { setOpen(false); ref.current?.focus(); }}> |
| +добавлено | ${visible.map((it, i) => it.sep |
| +добавлено | ? html`<div class="sep" key=${'s' + i}></div>` |
| +добавлено | : html`<button type="button" role="menuitem" key=${i} class=${'mi' + (it.danger ? ' danger' : '')} disabled=${it.disabled} |
| +добавлено | onClick=${(e) => { e.stopPropagation(); setOpen(false); it.onClick?.(); }}> |
| +добавлено | ${it.icon ? html`<${Icon} name=${it.icon} />` : null} |
| +добавлено | <span class="grow ell">${it.label}</span> |
| +добавлено | ${it.checked ? html`<${Icon} name="check" class="chk-ic" />` : null} |
| +добавлено | </button>`)} |
| +добавлено | <//>` : null} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- слой: шторка/диалог |
| +добавлено | |
| +добавлено | const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Layer — правая шторка (kind='drawer'), нижний лист ('sheet') или диалог ('dialog'). |
| +добавлено | * Управление: open=true монтирует, onClose вызывается для закрытия; анимация выхода — внутри. |
| +добавлено | */ |
| +добавлено | export function Layer({ open, onClose, kind = 'drawer', title, wide, children, footer, headExtra, label, initialFocus }) { |
| +добавлено | const [mounted, setMounted] = useState(open); |
| +добавлено | const [leaving, setLeaving] = useState(false); |
| +добавлено | const panel = useRef(null); |
| +добавлено | const returnTo = useRef(null); |
| +добавлено | const closeRef = useRef(onClose); |
| +добавлено | closeRef.current = onClose; |
| +добавлено | |
| +добавлено | useEffect(() => { |
| +добавлено | if (open) { |
| +добавлено | returnTo.current = document.activeElement; |
| +добавлено | setMounted(true); |
| +добавлено | setLeaving(false); |
| +добавлено | } else if (mounted) { |
| +добавлено | setLeaving(true); |
| +добавлено | const t = setTimeout(() => { setMounted(false); setLeaving(false); }, reducedMotion() ? 0 : 200); |
| +добавлено | const back = returnTo.current; |
| +добавлено | if (back && document.contains(back)) back.focus?.({ preventScroll: true }); |
| +добавлено | return () => clearTimeout(t); |
| +добавлено | } |
| +добавлено | }, [open]); |
| +добавлено | |
| +добавлено | useEffect(() => { |
| +добавлено | if (!mounted || leaving) return; |
| +добавлено | const pop = pushLayer(() => closeRef.current?.()); |
| +добавлено | const el = panel.current; |
| +добавлено | requestAnimationFrame(() => { |
| +добавлено | const target = (initialFocus && el?.querySelector(initialFocus)) || el?.querySelector('[data-autofocus]') || el; |
| +добавлено | target?.focus?.({ preventScroll: true }); |
| +добавлено | }); |
| +добавлено | return pop; |
| +добавлено | }, [mounted, leaving]); |
| +добавлено | |
| +добавлено | if (!mounted) return null; |
| +добавлено | |
| +добавлено | const trap = (e) => { |
| +добавлено | if (e.key !== 'Tab') return; |
| +добавлено | const items = [...panel.current.querySelectorAll(FOCUSABLE)].filter((x) => x.offsetParent !== null); |
| +добавлено | if (!items.length) { e.preventDefault(); return; } |
| +добавлено | const first = items[0]; |
| +добавлено | const last = items[items.length - 1]; |
| +добавлено | if (e.shiftKey && (document.activeElement === first || document.activeElement === panel.current)) { e.preventDefault(); last.focus(); } |
| +добавлено | else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const out = leaving ? ' out' : ''; |
| +добавлено | if (kind === 'dialog') { |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <div class=${'backdrop dlg' + out} onClick=${() => onClose?.()}></div> |
| +добавлено | <div class=${'dialog' + out} role="alertdialog" aria-modal="true" aria-label=${label || title} tabindex="-1" ref=${panel} onKeyDown=${trap}> |
| +добавлено | ${children} |
| +добавлено | </div> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | return html`<${Fragment}> |
| +добавлено | <div class=${'backdrop' + out} onClick=${() => onClose?.()}></div> |
| +добавлено | <section class=${kind + (wide ? ' wide' : '') + out} role="dialog" aria-modal="true" aria-label=${label || title} tabindex="-1" ref=${panel} onKeyDown=${trap}> |
| +добавлено | ${kind === 'sheet' ? html`<div class="grab"></div>` : null} |
| +добавлено | <header class="layer-h"> |
| +добавлено | <div class="t ell">${title}</div> |
| +добавлено | ${headExtra} |
| +добавлено | <button type="button" class="ibtn" title="Закрыть (Esc)" aria-label="Закрыть" onClick=${() => onClose?.()}><${Icon} name="x" /></button> |
| +добавлено | </header> |
| +добавлено | <div class="layer-b">${children}</div> |
| +добавлено | ${footer ? html`<footer class="layer-f">${footer}</footer>` : null} |
| +добавлено | </section> |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- confirm() |
| +добавлено | |
| +добавлено | const confirmStore = createStore(null); |
| +добавлено | export function confirmDialog({ title, text, ok = 'Подтвердить', danger = true }) { |
| +добавлено | return new Promise((resolve) => confirmStore.set({ title, text, ok, danger, resolve })); |
| +добавлено | } |
| +добавлено | export function ConfirmHost() { |
| +добавлено | const c = useStore(confirmStore); |
| +добавлено | const [last, setLast] = useState(null); |
| +добавлено | useEffect(() => { if (c) setLast(c); }, [c]); |
| +добавлено | const shown = c || last; |
| +добавлено | const done = (v) => { c?.resolve(v); confirmStore.set(null); }; |
| +добавлено | return html`<${Layer} kind="dialog" open=${!!c} onClose=${() => done(false)} label=${shown?.title} initialFocus=".btn.cancel"> |
| +добавлено | ${shown ? html`<div class="t">${shown.title}</div> |
| +добавлено | ${shown.text ? html`<div class="d">${shown.text}</div>` : null} |
| +добавлено | <div class="row" style="justify-content:flex-end"> |
| +добавлено | <button type="button" class="btn cancel" onClick=${() => done(false)}>Отмена</button> |
| +добавлено | <button type="button" class=${'btn ' + (shown.danger ? 'solid-danger' : 'primary')} onClick=${() => done(true)}>${shown.ok}</button> |
| +добавлено | </div>` : null} |
| +добавлено | <//>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- тосты |
| +добавлено | |
| +добавлено | function ToastItem({ t }) { |
| +добавлено | const timer = useRef(0); |
| +добавлено | const left = useRef(t.timeout); |
| +добавлено | const started = useRef(0); |
| +добавлено | const start = useCallback(() => { |
| +добавлено | if (!t.timeout) return; |
| +добавлено | started.current = Date.now(); |
| +добавлено | timer.current = setTimeout(() => dismissToast(t.id), left.current); |
| +добавлено | }, []); |
| +добавлено | const pause = () => { clearTimeout(timer.current); left.current -= Date.now() - started.current; }; |
| +добавлено | useEffect(() => { start(); return () => clearTimeout(timer.current); }, []); |
| +добавлено | const icon = t.kind === 'ok' ? 'check' : t.kind === 'err' ? 'alert' : 'activity'; |
| +добавлено | return html`<div class=${'toast ' + t.kind + (t.leaving ? ' out' : '')} role=${t.kind === 'err' ? 'alert' : 'status'} |
| +добавлено | onMouseEnter=${pause} onMouseLeave=${start}> |
| +добавлено | <${Icon} name=${icon} class="k" /> |
| +добавлено | <div class="msg">${t.message}</div> |
| +добавлено | ${t.action ? html`<button type="button" class="btn" onClick=${() => { t.action.onClick(); dismissToast(t.id); }}>${t.action.label}</button>` : null} |
| +добавлено | <button type="button" class="ibtn sm" aria-label="Скрыть" onClick=${() => dismissToast(t.id)}><${Icon} name="x" size=${14} /></button> |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | export function ToastHost() { |
| +добавлено | const list = useStore(toasts); |
| +добавлено | return html`<div class="toasts" aria-live="polite">${list.map((t) => html`<${ToastItem} key=${t.id} t=${t} />`)}</div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- пустые состояния / скелетоны |
| +добавлено | |
| +добавлено | export function Empty({ icon = 'inbox', title, text, children }) { |
| +добавлено | return html`<div class="empty"> |
| +добавлено | <div class="tile"><${Icon} name=${icon} size=${20} /></div> |
| +добавлено | ${title ? html`<div class="t">${title}</div>` : null} |
| +добавлено | ${text ? html`<div class="d">${text}</div>` : null} |
| +добавлено | ${children} |
| +добавлено | </div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function Launcher({ icon, title, text, pill, onClick, tag = 'button' }) { |
| +добавлено | const inner = html`<div class="tile"><${Icon} name=${icon} size=${20} /></div> |
| +добавлено | <div class="grow"><div class="t ell">${title}</div><div class="d">${text}</div></div> |
| +добавлено | ${pill ? html`<span class="pill">${pill}</span>` : null}`; |
| +добавлено | return tag === 'button' |
| +добавлено | ? html`<button type="button" class="launcher" onClick=${onClick}>${inner}</button>` |
| +добавлено | : html`<div class="launcher">${inner}</div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function Skel({ w = '100%', hgt = 14, r = 8, style }) { |
| +добавлено | return html`<div class="skel" style=${{ width: typeof w === 'number' ? w + 'px' : w, height: hgt + 'px', borderRadius: r + 'px', ...style }}></div>`; |
| +добавлено | } |
| +добавлено | export function SkelList({ rows = 4, card = true }) { |
| +добавлено | const body = Array.from({ length: rows }, (_, i) => html`<div class="li" key=${i}> |
| +добавлено | <${Skel} w=${28} hgt=${28} r=${14} /> |
| +добавлено | <div class="grow stack-s" style="gap:6px"><${Skel} w=${`${55 + ((i * 17) % 35)}%`} hgt=${11} /><${Skel} w=${`${30 + ((i * 23) % 30)}%`} hgt=${9} /></div> |
| +добавлено | </div>`); |
| +добавлено | return card ? html`<div class="card list">${body}</div>` : html`<div class="list">${body}</div>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function Spinner({ size = 16 }) { |
| +добавлено | return html`<span class="spin" style=${{ width: size + 'px', height: size + 'px' }} aria-label="Загрузка"></span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Кнопка с отложенным спиннером. */ |
| +добавлено | export function AsyncButton({ onClick, class: cls = 'btn', children, disabled, title, type = 'button', ...rest }) { |
| +добавлено | const [busy, setBusy] = useState(false); |
| +добавлено | const [spin, setSpin] = useState(false); |
| +добавлено | const click = async (e) => { |
| +добавлено | if (busy) return; |
| +добавлено | setBusy(true); |
| +добавлено | const t = setTimeout(() => setSpin(true), 300); |
| +добавлено | try { await onClick?.(e); } finally { clearTimeout(t); setBusy(false); setSpin(false); } |
| +добавлено | }; |
| +добавлено | return html`<button type=${type} class=${cls} disabled=${disabled || busy} title=${title} aria-busy=${String(busy)} onClick=${click} ...${rest}> |
| +добавлено | ${spin ? html`<span class="spin"></span>` : null}${children} |
| +добавлено | </button>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function Field({ label, hint, children, style }) { |
| +добавлено | return html`<label class="field" style=${style}> |
| +добавлено | ${label ? html`<span class="lbl">${label}</span>` : null} |
| +добавлено | ${children} |
| +добавлено | ${hint ? html`<span class="hint">${hint}</span>` : null} |
| +добавлено | </label>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function RoleBadge({ role }) { |
| +добавлено | const ROLE = { owner: 'Владелец', maintainer: 'Мейнтейнер', dev: 'Разработчик', viewer: 'Наблюдатель' }; |
| +добавлено | const ic = role === 'owner' ? 'crown' : role === 'maintainer' ? 'shield' : role === 'viewer' ? 'eye' : 'user'; |
| +добавлено | return html`<span class=${'role ' + role}><${Icon} name=${ic} size=${12} />${ROLE[role] || role}</span>`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Анимация появления для первых 6 элементов списка — возвращает style. */ |
| +добавлено | export function stagger(i, seen) { |
| +добавлено | if (seen || i > 5) return undefined; |
| +добавлено | return { animationDelay: i * 18 + 'ms' }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Список с анимацией удаления: держит удалённые элементы ещё 180 мс с классом leave-item. |
| +добавлено | * items: массив с полем key; render(item, i, phase) |
| +добавлено | */ |
| +добавлено | export function useLeaving(items, keyOf = (x) => x.id) { |
| +добавлено | const prev = useRef(new Map()); |
| +добавлено | const [ghosts, setGhosts] = useState([]); |
| +добавлено | const cur = new Map(items.map((x, i) => [keyOf(x), { x, i }])); |
| +добавлено | useEffect(() => { |
| +добавлено | const gone = []; |
| +добавлено | for (const [k, v] of prev.current) if (!cur.has(k)) gone.push({ ...v, k }); |
| +добавлено | prev.current = cur; |
| +добавлено | if (gone.length && !reducedMotion()) { |
| +добавлено | setGhosts((g) => [...g, ...gone]); |
| +добавлено | setTimeout(() => setGhosts((g) => g.filter((x) => !gone.includes(x))), 180); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | if (!ghosts.length) return items.map((x) => ({ item: x, leaving: false })); |
| +добавлено | const out = items.map((x) => ({ item: x, leaving: false })); |
| +добавлено | for (const g of ghosts) out.splice(Math.min(g.i, out.length), 0, { item: g.x, leaving: true }); |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | // Чистая база общего сервера для локальной работы панели: схема + пара демо-данных. |
| +добавлено | // Нужна, потому что копия сервиса в сборке (fork/team) умеет сама поднять сервер — |
| +добавлено | // но у неё должен быть prepared-билд и база, а не data/ разработчика. |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { execFileSync } from 'node:child_process'; |
| +добавлено | |
| +добавлено | const ROOT = path.resolve('.'); |
| +добавлено | const SRC = path.join(ROOT, '..', 'ide', 'vscode-main', 'aura-team-server'); |
| +добавлено | const OUT = path.join(ROOT, 'resources', 'team', 'aura-team-server'); |
| +добавлено | const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; |
| +добавлено | |
| +добавлено | console.log('[server] tsc ->', OUT); |
| +добавлено | execFileSync(npm, ['run', 'build'], { cwd: SRC, stdio: 'inherit', shell: true }); |
| +добавлено | fs.rmSync(path.join(OUT, 'dist'), { recursive: true, force: true }); |
| +добавлено | fs.cpSync(path.join(SRC, 'dist'), path.join(OUT, 'dist'), { recursive: true }); |
| +добавлено | |
| +добавлено | // база: схема создаётся самим сервером при первом запуске, аккаунтов нет |
| +добавлено | fs.rmSync(path.join(OUT, 'data'), { recursive: true, force: true }); |
| +добавлено | fs.mkdirSync(path.join(OUT, 'data'), { recursive: true }); |
| +добавлено | |
| +добавлено | const env = `# Локальный сервер Aura Team (дистрибутив Zcode Aura). Секреты генерируются при первом запуске. |
| +добавлено | AURA_HOST=127.0.0.1 |
| +добавлено | AURA_PORT=3220 |
| +добавлено | `; |
| +добавлено | fs.writeFileSync(path.join(OUT, '.env.example'), env); |
| +добавлено | console.log('[server] готово:', path.join(OUT, 'dist', 'server.js')); |
| +добавлено | // Клиент API team-server.invalid: Bearer-токен, повтор после refresh (single-flight), ошибки со статусом. |
| +добавлено | |
| +добавлено | import { HttpError } from './http.mjs'; |
| +добавлено | |
| +добавлено | export class ApiError extends HttpError {} |
| +добавлено | |
| +добавлено | export function createApi({ state, save, log = () => {}, onSignedOut = () => {} }) { |
| +добавлено | const baseUrl = () => String(state.serverUrl || 'https://team-server.invalid').replace(/\/+$/, ''); |
| +добавлено | let refreshing = null; |
| +добавлено | |
| +добавлено | async function doRefresh() { |
| +добавлено | if (!state.refreshToken) return false; |
| +добавлено | let res; |
| +добавлено | try { |
| +добавлено | res = await fetch(`${baseUrl()}/v1/auth/refresh`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json' }, |
| +добавлено | body: JSON.stringify({ refreshToken: state.refreshToken }), |
| +добавлено | signal: AbortSignal.timeout(20_000), |
| +добавлено | }); |
| +добавлено | } catch (err) { |
| +добавлено | // Сеть недоступна — токены не трогаем, иначе любой обрыв разлогинивал бы пользователя. |
| +добавлено | log('refresh network error', err.message); |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | if (!res.ok) { |
| +добавлено | log('refresh rejected', res.status); |
| +добавлено | if (res.status === 401 || res.status === 400 || res.status === 403) { |
| +добавлено | state.accessToken = null; |
| +добавлено | state.refreshToken = null; |
| +добавлено | save(); |
| +добавлено | onSignedOut(); |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | const tokens = await res.json(); |
| +добавлено | state.accessToken = tokens.accessToken; |
| +добавлено | state.refreshToken = tokens.refreshToken ?? state.refreshToken; |
| +добавлено | save(); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Одновременные 401 делят один refresh: сервер ротирует refresh-токен, второй вызов бы его сжёг. */ |
| +добавлено | function refreshTokens() { |
| +добавлено | refreshing ??= doRefresh().finally(() => { refreshing = null; }); |
| +добавлено | return refreshing; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function parse(res) { |
| +добавлено | if (res.status === 204) return null; |
| +добавлено | const text = await res.text(); |
| +добавлено | let json = null; |
| +добавлено | try { json = text ? JSON.parse(text) : null; } catch { /* не JSON */ } |
| +добавлено | if (!res.ok) { |
| +добавлено | throw new ApiError(res.status, json?.message || json?.error || `HTTP ${res.status}`, json ?? text.slice(0, 400)); |
| +добавлено | } |
| +добавлено | return json ?? (text ? { text } : null); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Низкоуровневый запрос. `makeInit` вызывается на каждую попытку — тело-поток |
| +добавлено | * нельзя переиспользовать после 401, поэтому его создают заново. |
| +добавлено | */ |
| +добавлено | async function raw(pathname, makeInit = () => ({}), { auth = true, retry = true, timeoutMs = 120_000 } = {}) { |
| +добавлено | const init = makeInit(); |
| +добавлено | const headers = { ...(init.headers ?? {}) }; |
| +добавлено | if (auth) { |
| +добавлено | if (!state.accessToken) throw new HttpError(401, 'not signed in'); |
| +добавлено | headers.authorization = `Bearer ${state.accessToken}`; |
| +добавлено | } |
| +добавлено | const res = await fetch(`${baseUrl()}${pathname}`, { ...init, headers, signal: AbortSignal.timeout(timeoutMs) }); |
| +добавлено | if (res.status === 401 && auth && retry) { |
| +добавлено | try { await res.body?.cancel(); } catch { /* уже закрыт */ } |
| +добавлено | if (await refreshTokens()) return raw(pathname, makeInit, { auth, retry: false, timeoutMs }); |
| +добавлено | } |
| +добавлено | return res; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function api(pathname, { method = 'GET', body, auth = true, timeoutMs } = {}) { |
| +добавлено | const res = await raw( |
| +добавлено | pathname, |
| +добавлено | () => (body === undefined |
| +добавлено | ? { method } |
| +добавлено | : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }), |
| +добавлено | { auth, timeoutMs }, |
| +добавлено | ); |
| +добавлено | return parse(res); |
| +добавлено | } |
| +добавлено | |
| +добавлено | return { api, raw, parse, baseUrl, refreshTokens }; |
| +добавлено | } |
| +добавлено | // Пути сервиса и переопределения через окружение (для тестов и переносимости). |
| +добавлено | |
| +добавлено | import path from 'node:path'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| +добавлено | |
| +добавлено | const env = (name) => (process.env[name] ?? '').trim(); |
| +добавлено | |
| +добавлено | export const PORT = Number(env('ZTEAM_PORT') || 8790); |
| +добавлено | |
| +добавлено | /** Каталог state.json и .state-key. */ |
| +добавлено | export const STATE_DIR = env('ZTEAM_STATE_DIR') || ROOT; |
| +добавлено | |
| +добавлено | /** `<fork>/home/.zcode/cli` — config.json и plugins/*.json ZCode CLI. */ |
| +добавлено | export const ZCODE_HOME = env('ZTEAM_ZCODE_HOME') || path.resolve(ROOT, '..', 'home', '.zcode', 'cli'); |
| +добавлено | |
| +добавлено | export const PLUGIN_ID = 'aura-team@local-marketplace'; |
| +добавлено | |
| +добавлено | export const paths = { |
| +добавлено | state: path.join(STATE_DIR, 'state.json'), |
| +добавлено | stateKey: path.join(STATE_DIR, '.state-key'), |
| +добавлено | assets: path.join(ROOT, 'assets'), |
| +добавлено | panel: path.join(ROOT, 'panel.html'), |
| +добавлено | cliConfig: path.join(ZCODE_HOME, 'config.json'), |
| +добавлено | installedPlugins: path.join(ZCODE_HOME, 'plugins', 'installed_plugins.json'), |
| +добавлено | providerConfig: env('ZTEAM_PROVIDER_CONFIG') || path.resolve(ZCODE_HOME, '..', 'v2', 'provider_config.json'), |
| +добавлено | agentFile: env('ZTEAM_AGENT_FILE') || path.resolve(ZCODE_HOME, '..', 'aura-team', 'agent.json'), |
| +добавлено | tmp: env('ZTEAM_TMP_DIR') || path.join(STATE_DIR, '.tmp'), |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export const DEFAULT_SERVER = env('ZTEAM_SERVER_URL') || 'https://team-server.invalid'; |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Локальный бэкенд внутри дистрибутива: сервис сам поднимает aura-team-server из |
| +добавлено | * resources/team/aura-team-server, если он есть рядом. Так скачанная сборка работает |
| +добавлено | * без внешнего сервера; в рабочем форке рядом сервера нет — режим выключен. |
| +добавлено | */ |
| +добавлено | export const localServer = (() => { |
| +добавлено | const bundled = path.resolve(ROOT, '..', 'resources', 'team', 'aura-team-server', 'dist', 'server.js'); |
| +добавлено | const entry = env('ZTEAM_SERVER_ENTRY') || bundled; |
| +добавлено | // Внутри установки сервер всегда свой; в каталоге разработки — по умолчанию выключен, |
| +добавлено | // иначе рабочий форк начал бы ходить не в боевой team-server.invalid. |
| +добавлено | const insideRelease = fs.existsSync(bundled); |
| +добавлено | if (!insideRelease && env('ZTEAM_LOCAL_SERVER') !== '1') return null; |
| +добавлено | if (!fs.existsSync(entry)) return null; |
| +добавлено | return { entry, dataDir: path.dirname(entry), port: Number(env('ZTEAM_LOCAL_SERVER_PORT') || 3220) }; |
| +добавлено | })(); |
| +добавлено | // Git через execFile (без shell): статус, лог, show, diff, stage/unstage/discard, commit, push/pull, ветки. |
| +добавлено | |
| +добавлено | import { execFile } from 'node:child_process'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { HttpError } from './http.mjs'; |
| +добавлено | |
| +добавлено | const MAX_BUFFER = 8 * 1024 * 1024; |
| +добавлено | const PATCH_LIMIT = 400 * 1024; |
| +добавлено | |
| +добавлено | export function runGit(cwd, args, { timeout = 30_000, allowExit = [] } = {}) { |
| +добавлено | return new Promise((resolve, reject) => { |
| +добавлено | execFile('git', args, { |
| +добавлено | cwd, |
| +добавлено | timeout, |
| +добавлено | windowsHide: true, |
| +добавлено | maxBuffer: MAX_BUFFER, |
| +добавлено | encoding: 'utf8', |
| +добавлено | env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' }, |
| +добавлено | }, (err, stdout, stderr) => { |
| +добавлено | if (err) { |
| +добавлено | const code = typeof err.code === 'number' ? err.code : null; |
| +добавлено | if (code !== null && allowExit.includes(code)) return resolve({ stdout, stderr, code }); |
| +добавлено | const msg = (stderr || err.message || '').trim().split('\n').slice(-6).join('\n'); |
| +добавлено | const e = new HttpError(err.code === 'ENOENT' ? 500 : 400, msg || `git ${args[0]} failed`, { stderr: stderr?.slice(0, 4000) ?? '' }); |
| +добавлено | e.exitCode = code; |
| +добавлено | return reject(e); |
| +добавлено | } |
| +добавлено | resolve({ stdout, stderr, code: 0 }); |
| +добавлено | }); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function resolveDir(dir, fallback) { |
| +добавлено | const cwd = (typeof dir === 'string' && dir.trim()) || fallback; |
| +добавлено | if (!cwd) throw new HttpError(400, 'no workspace selected (set workspace or pass dir)'); |
| +добавлено | const abs = path.resolve(cwd); |
| +добавлено | let st; |
| +добавлено | try { st = fs.statSync(abs); } catch { throw new HttpError(400, `directory not found: ${abs}`); } |
| +добавлено | if (!st.isDirectory()) throw new HttpError(400, `not a directory: ${abs}`); |
| +добавлено | return abs; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function checkFiles(files) { |
| +добавлено | if (!Array.isArray(files) || files.length === 0) throw new HttpError(400, 'files must be a non-empty array'); |
| +добавлено | for (const f of files) { |
| +добавлено | if (typeof f !== 'string' || !f.trim()) throw new HttpError(400, 'file path must be a non-empty string'); |
| +добавлено | if (f.startsWith('-')) throw new HttpError(400, `invalid file argument: ${f}`); |
| +добавлено | if (f.includes('\0')) throw new HttpError(400, 'invalid file argument'); |
| +добавлено | } |
| +добавлено | return files; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function checkBranch(cwd, branch) { |
| +добавлено | if (typeof branch !== 'string' || !branch.trim() || branch.startsWith('-')) throw new HttpError(400, 'invalid branch name'); |
| +добавлено | try { |
| +добавлено | await runGit(cwd, ['check-ref-format', '--branch', branch], { timeout: 10_000 }); |
| +добавлено | } catch { |
| +добавлено | throw new HttpError(400, `invalid branch name: ${branch}`); |
| +добавлено | } |
| +добавлено | return branch; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function isRepo(cwd) { |
| +добавлено | try { |
| +добавлено | const { stdout } = await runGit(cwd, ['rev-parse', '--is-inside-work-tree'], { timeout: 10_000 }); |
| +добавлено | return stdout.trim() === 'true'; |
| +добавлено | } catch { |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function topLevel(cwd) { |
| +добавлено | const { stdout } = await runGit(cwd, ['rev-parse', '--show-toplevel'], { timeout: 10_000 }); |
| +добавлено | return path.resolve(stdout.trim()); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const STATUS_NAMES = { M: 'modified', A: 'added', D: 'deleted', R: 'renamed', C: 'copied', T: 'typechange', U: 'unmerged' }; |
| +добавлено | |
| +добавлено | export function parseStatusV2(out) { |
| +добавлено | const res = { |
| +добавлено | branch: null, detached: false, oid: null, upstream: null, ahead: 0, behind: 0, |
| +добавлено | staged: [], unstaged: [], untracked: [], conflicts: [], |
| +добавлено | }; |
| +добавлено | const tokens = out.split('\0'); |
| +добавлено | for (let i = 0; i < tokens.length; i++) { |
| +добавлено | const line = tokens[i]; |
| +добавлено | if (!line) continue; |
| +добавлено | if (line.startsWith('# ')) { |
| +добавлено | const [, key, ...rest] = line.split(' '); |
| +добавлено | const val = rest.join(' '); |
| +добавлено | if (key === 'branch.oid') res.oid = val === '(initial)' ? null : val; |
| +добавлено | else if (key === 'branch.head') { |
| +добавлено | if (val === '(detached)') res.detached = true; |
| +добавлено | else res.branch = val; |
| +добавлено | } else if (key === 'branch.upstream') res.upstream = val; |
| +добавлено | else if (key === 'branch.ab') { |
| +добавлено | const m = /\+(\d+) -(\d+)/.exec(val); |
| +добавлено | if (m) { res.ahead = Number(m[1]); res.behind = Number(m[2]); } |
| +добавлено | } |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const type = line[0]; |
| +добавлено | if (type === '?') { res.untracked.push(line.slice(2)); continue; } |
| +добавлено | if (type === '!') continue; |
| +добавлено | if (type === '1' || type === '2') { |
| +добавлено | const parts = line.split(' '); |
| +добавлено | const xy = parts[1]; |
| +добавлено | const p = parts.slice(type === '1' ? 8 : 9).join(' '); |
| +добавлено | let orig; |
| +добавлено | if (type === '2') orig = tokens[++i]; |
| +добавлено | const x = xy[0]; |
| +добавлено | const y = xy[1]; |
| +добавлено | if (x !== '.') res.staged.push({ path: p, status: STATUS_NAMES[x] ?? x, code: x, ...(orig ? { orig } : {}) }); |
| +добавлено | if (y !== '.') res.unstaged.push({ path: p, status: STATUS_NAMES[y] ?? y, code: y, ...(orig ? { orig } : {}) }); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | if (type === 'u') { |
| +добавлено | const parts = line.split(' '); |
| +добавлено | res.conflicts.push(parts.slice(10).join(' ')); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return res; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function status(cwd) { |
| +добавлено | if (!(await isRepo(cwd))) { |
| +добавлено | return { cwd, isRepo: false, branch: null, detached: false, upstream: null, ahead: 0, behind: 0, remoteUrl: null, staged: [], unstaged: [], untracked: [], conflicts: [], counts: { staged: 0, unstaged: 0, untracked: 0, conflicts: 0, total: 0 } }; |
| +добавлено | } |
| +добавлено | const { stdout } = await runGit(cwd, ['status', '--porcelain=v2', '--branch', '-z', '--untracked-files=all']); |
| +добавлено | const s = parseStatusV2(stdout); |
| +добавлено | const remoteUrl = await getRemoteUrl(cwd); |
| +добавлено | const counts = { |
| +добавлено | staged: s.staged.length, |
| +добавлено | unstaged: s.unstaged.length, |
| +добавлено | untracked: s.untracked.length, |
| +добавлено | conflicts: s.conflicts.length, |
| +добавлено | }; |
| +добавлено | counts.total = counts.staged + counts.unstaged + counts.untracked + counts.conflicts; |
| +добавлено | return { |
| +добавлено | cwd, isRepo: true, branch: s.branch, detached: s.detached, head: s.oid, upstream: s.upstream, |
| +добавлено | ahead: s.ahead, behind: s.behind, remoteUrl, |
| +добавлено | staged: s.staged, unstaged: s.unstaged, untracked: s.untracked, conflicts: s.conflicts, counts, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function getRemoteUrl(cwd) { |
| +добавлено | try { |
| +добавлено | const { stdout } = await runGit(cwd, ['remote', 'get-url', 'origin'], { timeout: 10_000 }); |
| +добавлено | return stdout.trim() || null; |
| +добавлено | } catch { |
| +добавлено | try { |
| +добавлено | const { stdout } = await runGit(cwd, ['remote'], { timeout: 10_000 }); |
| +добавлено | const first = stdout.split(/\r?\n/).find(Boolean); |
| +добавлено | if (!first) return null; |
| +добавлено | const r = await runGit(cwd, ['remote', 'get-url', first], { timeout: 10_000 }); |
| +добавлено | return r.stdout.trim() || null; |
| +добавлено | } catch { |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function currentBranch(cwd) { |
| +добавлено | try { |
| +добавлено | const { stdout } = await runGit(cwd, ['symbolic-ref', '--short', '-q', 'HEAD'], { timeout: 10_000 }); |
| +добавлено | return stdout.trim() || null; |
| +добавлено | } catch { |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const FS = '\x1f'; |
| +добавлено | const RS = '\x1e'; |
| +добавлено | |
| +добавлено | export async function log(cwd, { limit = 50, skip = 0, file } = {}) { |
| +добавлено | const n = Math.min(Math.max(Number(limit) || 50, 1), 500); |
| +добавлено | const s = Math.max(Number(skip) || 0, 0); |
| +добавлено | const args = ['log', `--max-count=${n}`, `--skip=${s}`, '--decorate=short', '--date=iso-strict', |
| +добавлено | `--format=%H${FS}%h${FS}%P${FS}%an${FS}%ae${FS}%aI${FS}%s${FS}%D${RS}`]; |
| +добавлено | if (file) { |
| +добавлено | checkFiles([file]); |
| +добавлено | args.push('--', file); |
| +добавлено | } |
| +добавлено | let stdout; |
| +добавлено | try { |
| +добавлено | ({ stdout } = await runGit(cwd, args)); |
| +добавлено | } catch (err) { |
| +добавлено | // Пустой репозиторий (нет ни одного коммита) — не ошибка. |
| +добавлено | if (/does not have any commits|unknown revision|bad default revision/i.test(err.message)) return []; |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | return stdout.split(RS).map((r) => r.replace(/^\s+/, '')).filter(Boolean).map((rec) => { |
| +добавлено | const [hash, short, parents, author, email, date, subject, refs] = rec.split(FS); |
| +добавлено | return { |
| +добавлено | hash, short, |
| +добавлено | parents: parents ? parents.split(' ').filter(Boolean) : [], |
| +добавлено | author, email, date, subject, |
| +добавлено | refs: refs ? refs.split(',').map((x) => x.trim()).filter(Boolean) : [], |
| +добавлено | }; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function checkHash(hash) { |
| +добавлено | if (typeof hash !== 'string' || !/^[0-9a-fA-F]{4,64}$|^HEAD(~\d+|\^\d*)*$/.test(hash)) throw new HttpError(400, 'invalid commit hash'); |
| +добавлено | return hash; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function show(cwd, hash) { |
| +добавлено | checkHash(hash); |
| +добавлено | const meta = await runGit(cwd, ['show', '-s', `--format=%H${FS}%an${FS}%ae${FS}%aI${FS}%P${FS}%s${FS}%b`, hash, '--']); |
| +добавлено | const [full, author, email, date, parents, subject, ...bodyParts] = meta.stdout.split(FS); |
| +добавлено | const numstat = await runGit(cwd, ['show', '--format=', '--numstat', '-z', '-M', hash, '--']); |
| +добавлено | const nameStatus = await runGit(cwd, ['show', '--format=', '--name-status', '-z', '-M', hash, '--']); |
| +добавлено | const statuses = new Map(); |
| +добавлено | { |
| +добавлено | const t = nameStatus.stdout.split('\0').filter((x) => x !== ''); |
| +добавлено | for (let i = 0; i < t.length;) { |
| +добавлено | const code = t[i++]; |
| +добавлено | const letter = code[0]; |
| +добавлено | if (letter === 'R' || letter === 'C') { |
| +добавлено | const from = t[i++]; |
| +добавлено | const to = t[i++]; |
| +добавлено | statuses.set(to, { status: STATUS_NAMES[letter] ?? letter, orig: from }); |
| +добавлено | } else { |
| +добавлено | statuses.set(t[i++], { status: STATUS_NAMES[letter] ?? letter }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const files = []; |
| +добавлено | { |
| +добавлено | // numstat -z: "add\tdel\tpath\0" или для переименований "add\tdel\t\0from\0to\0" |
| +добавлено | const t = numstat.stdout.split('\0'); |
| +добавлено | for (let i = 0; i < t.length; i++) { |
| +добавлено | const rec = t[i]; |
| +добавлено | if (!rec) continue; |
| +добавлено | const [a, d, p] = rec.split('\t'); |
| +добавлено | let filePath = p; |
| +добавлено | if (p === '' || p === undefined) { |
| +добавлено | i += 2; |
| +добавлено | filePath = t[i]; |
| +добавлено | } |
| +добавлено | const st = statuses.get(filePath) ?? { status: 'modified' }; |
| +добавлено | files.push({ |
| +добавлено | path: filePath, |
| +добавлено | status: st.status, |
| +добавлено | ...(st.orig ? { orig: st.orig } : {}), |
| +добавлено | additions: a === '-' ? null : Number(a), |
| +добавлено | deletions: d === '-' ? null : Number(d), |
| +добавлено | binary: a === '-', |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const patchRes = await runGit(cwd, ['show', '--format=', '--patch', '--no-color', '-M', hash, '--']); |
| +добавлено | let patch = patchRes.stdout; |
| +добавлено | let truncated = false; |
| +добавлено | if (Buffer.byteLength(patch) > PATCH_LIMIT) { |
| +добавлено | patch = Buffer.from(patch).subarray(0, PATCH_LIMIT).toString('utf8'); |
| +добавлено | truncated = true; |
| +добавлено | } |
| +добавлено | return { |
| +добавлено | hash: full, author, email, date, |
| +добавлено | subject, body: bodyParts.join(FS).replace(/\s+$/, ''), |
| +добавлено | parents: parents ? parents.split(' ').filter(Boolean) : [], |
| +добавлено | files, patch, truncated, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function diff(cwd, { file, staged } = {}) { |
| +добавлено | if (file) checkFiles([file]); |
| +добавлено | if (file && !staged) { |
| +добавлено | // Неотслеживаемый файл — показываем как полностью добавленный. |
| +добавлено | const ls = await runGit(cwd, ['ls-files', '--others', '--exclude-standard', '--', file]); |
| +добавлено | if (ls.stdout.trim()) { |
| +добавлено | const r = await runGit(cwd, ['diff', '--no-color', '--no-index', '--', '/dev/null', file], { allowExit: [1] }); |
| +добавлено | return { diff: r.stdout, untracked: true }; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const args = ['diff', '--no-color', '-M']; |
| +добавлено | if (staged) args.push('--cached'); |
| +добавлено | if (file) args.push('--', file); |
| +добавлено | const { stdout } = await runGit(cwd, args); |
| +добавлено | let out = stdout; |
| +добавлено | let truncated = false; |
| +добавлено | if (Buffer.byteLength(out) > PATCH_LIMIT) { |
| +добавлено | out = Buffer.from(out).subarray(0, PATCH_LIMIT).toString('utf8'); |
| +добавлено | truncated = true; |
| +добавлено | } |
| +добавлено | return { diff: out, ...(truncated ? { truncated } : {}) }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function stage(cwd, files) { |
| +добавлено | await runGit(cwd, ['add', '--', ...checkFiles(files)]); |
| +добавлено | return { ok: true }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function stageAll(cwd) { |
| +добавлено | await runGit(cwd, ['add', '-A']); |
| +добавлено | return { ok: true }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function unstage(cwd, files) { |
| +добавлено | checkFiles(files); |
| +добавлено | try { |
| +добавлено | await runGit(cwd, ['restore', '--staged', '--', ...files]); |
| +добавлено | } catch (err) { |
| +добавлено | // В репозитории без коммитов restore --staged не работает — снимаем через rm --cached. |
| +добавлено | if (/could not resolve HEAD|HEAD.*invalid|bad revision/i.test(err.message)) { |
| +добавлено | await runGit(cwd, ['rm', '--cached', '-q', '--', ...files]); |
| +добавлено | } else { |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { ok: true }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Отменяет изменения: отслеживаемые — restore, неотслеживаемые — удаление (только внутри cwd). */ |
| +добавлено | export async function discard(cwd, files) { |
| +добавлено | checkFiles(files); |
| +добавлено | const root = await topLevel(cwd); |
| +добавлено | const base = path.resolve(cwd); |
| +добавлено | const ls = await runGit(cwd, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files]); |
| +добавлено | const untrackedRel = new Set(ls.stdout.split('\0').filter(Boolean).map((p) => path.resolve(cwd, p))); |
| +добавлено | const tracked = []; |
| +добавлено | const removed = []; |
| +добавлено | for (const f of files) { |
| +добавлено | const abs = path.resolve(cwd, f); |
| +добавлено | const inside = (abs + path.sep).toLowerCase().startsWith(base.toLowerCase() + path.sep) && abs.toLowerCase() !== base.toLowerCase(); |
| +добавлено | if (!inside || !(abs.toLowerCase() + path.sep).startsWith(root.toLowerCase() + path.sep)) { |
| +добавлено | throw new HttpError(400, `path outside working directory: ${f}`); |
| +добавлено | } |
| +добавлено | if (untrackedRel.has(abs)) { |
| +добавлено | fs.rmSync(abs, { force: true, recursive: false }); |
| +добавлено | removed.push(f); |
| +добавлено | } else { |
| +добавлено | tracked.push(f); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (tracked.length) await runGit(cwd, ['restore', '--', ...tracked]); |
| +добавлено | return { ok: true, restored: tracked, removed }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function commit(cwd, { message, amend = false }) { |
| +добавлено | if (typeof message !== 'string' || !message.trim()) { |
| +добавлено | if (!amend) throw new HttpError(400, 'commit message is required'); |
| +добавлено | } |
| +добавлено | // diff --cached работает и без HEAD (сравнение с пустым деревом): код 1 — есть изменения. |
| +добавлено | const cached = await runGit(cwd, ['diff', '--cached', '--quiet'], { allowExit: [1] }); |
| +добавлено | if (cached.code === 0 && !amend) throw new HttpError(400, 'Nothing staged'); |
| +добавлено | const args = ['commit', '--no-edit']; |
| +добавлено | if (amend) args.push('--amend'); |
| +добавлено | if (message && message.trim()) args.push('-F', '-'); |
| +добавлено | // message через stdin — без ограничений длины командной строки и без экранирования. |
| +добавлено | const out = await new Promise((resolve, reject) => { |
| +добавлено | const child = execFile('git', args, { |
| +добавлено | cwd, timeout: 60_000, windowsHide: true, maxBuffer: MAX_BUFFER, encoding: 'utf8', |
| +добавлено | env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, |
| +добавлено | }, (err, stdout, stderr) => { |
| +добавлено | if (err) return reject(new HttpError(400, (stderr || stdout || err.message).trim().slice(-2000))); |
| +добавлено | resolve(stdout); |
| +добавлено | }); |
| +добавлено | child.stdin.end(message && message.trim() ? message : ''); |
| +добавлено | }); |
| +добавлено | const { stdout: hash } = await runGit(cwd, ['rev-parse', 'HEAD']); |
| +добавлено | return { hash: hash.trim(), summary: out.trim().split(/\r?\n/)[0] ?? '' }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function push(cwd, { setUpstream = false } = {}) { |
| +добавлено | const s = await status(cwd); |
| +добавлено | if (!s.isRepo) throw new HttpError(400, 'not a git repository'); |
| +добавлено | let args = ['push']; |
| +добавлено | if (!s.upstream || setUpstream) { |
| +добавлено | if (!s.branch) throw new HttpError(400, 'cannot push a detached HEAD'); |
| +добавлено | await checkBranch(cwd, s.branch); |
| +добавлено | args = ['push', '-u', 'origin', s.branch]; |
| +добавлено | } |
| +добавлено | const r = await runGit(cwd, args, { timeout: 120_000 }); |
| +добавлено | return { ok: true, output: (r.stdout + r.stderr).trim() }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function pull(cwd) { |
| +добавлено | const r = await runGit(cwd, ['pull', '--ff-only'], { timeout: 120_000 }); |
| +добавлено | return { ok: true, output: (r.stdout + r.stderr).trim() }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function fetchAll(cwd) { |
| +добавлено | const r = await runGit(cwd, ['fetch', '--prune'], { timeout: 120_000 }); |
| +добавлено | return { ok: true, output: (r.stdout + r.stderr).trim() }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function branches(cwd) { |
| +добавлено | if (!(await isRepo(cwd))) return []; |
| +добавлено | const fmt = `%(refname:short)${FS}%(HEAD)${FS}%(upstream:short)${FS}%(upstream:track,nobracket)${FS}%(objectname:short)${FS}%(subject)${FS}%(committerdate:iso-strict)`; |
| +добавлено | const { stdout } = await runGit(cwd, ['for-each-ref', `--format=${fmt}`, 'refs/heads']); |
| +добавлено | return stdout.split(/\r?\n/).filter(Boolean).map((line) => { |
| +добавлено | const [name, head, upstream, track, hash, subject, date] = line.split(FS); |
| +добавлено | const ahead = Number(/ahead (\d+)/.exec(track)?.[1] ?? 0); |
| +добавлено | const behind = Number(/behind (\d+)/.exec(track)?.[1] ?? 0); |
| +добавлено | return { |
| +добавлено | name, current: head === '*', upstream: upstream || null, ahead, behind, |
| +добавлено | gone: /gone/.test(track), |
| +добавлено | lastCommit: hash ? { hash, subject, date } : null, |
| +добавлено | }; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function checkout(cwd, { branch, create = false }) { |
| +добавлено | await checkBranch(cwd, branch); |
| +добавлено | const args = create ? ['checkout', '-b', branch] : ['checkout', branch, '--']; |
| +добавлено | await runGit(cwd, args); |
| +добавлено | return { ok: true, branch }; |
| +добавлено | } |
| +добавлено | // HTTP-утилиты сервиса: JSON-ответы, чтение тела с лимитом, приём тела в файл. |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import { pipeline } from 'node:stream/promises'; |
| +добавлено | import { Transform } from 'node:stream'; |
| +добавлено | |
| +добавлено | export class HttpError extends Error { |
| +добавлено | constructor(status, message, body = null) { |
| +добавлено | super(message); |
| +добавлено | this.status = status; |
| +добавлено | this.body = body; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function sendJson(res, code, obj, headers = {}) { |
| +добавлено | const payload = JSON.stringify(obj ?? null); |
| +добавлено | res.writeHead(code, { |
| +добавлено | 'Content-Type': 'application/json; charset=utf-8', |
| +добавлено | 'Content-Length': Buffer.byteLength(payload), |
| +добавлено | 'Cache-Control': 'no-store', |
| +добавлено | ...headers, |
| +добавлено | }); |
| +добавлено | res.end(payload); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function tooLarge(limit) { |
| +добавлено | return new HttpError(413, `request body too large (max ${limit} bytes)`, { limitBytes: limit }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Читает тело целиком (для JSON-запросов) с жёстким лимитом. */ |
| +добавлено | export function readBody(req, limit) { |
| +добавлено | return new Promise((resolve, reject) => { |
| +добавлено | const declared = Number(req.headers['content-length']); |
| +добавлено | if (Number.isFinite(declared) && declared > limit) { |
| +добавлено | req.on('error', () => {}); |
| +добавлено | req.resume(); |
| +добавлено | reject(tooLarge(limit)); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const chunks = []; |
| +добавлено | let size = 0; |
| +добавлено | let settled = false; |
| +добавлено | const done = (fn, value) => { |
| +добавлено | if (settled) return; |
| +добавлено | settled = true; |
| +добавлено | req.off('data', onData); |
| +добавлено | req.off('end', onEnd); |
| +добавлено | req.off('error', onError); |
| +добавлено | fn(value); |
| +добавлено | }; |
| +добавлено | const onData = (chunk) => { |
| +добавлено | size += chunk.length; |
| +добавлено | if (size > limit) { |
| +добавлено | req.on('error', () => {}); |
| +добавлено | req.resume(); |
| +добавлено | done(reject, tooLarge(limit)); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | chunks.push(chunk); |
| +добавлено | }; |
| +добавлено | const onEnd = () => done(resolve, Buffer.concat(chunks).toString('utf8')); |
| +добавлено | const onError = (err) => done(reject, err); |
| +добавлено | req.on('data', onData); |
| +добавлено | req.on('end', onEnd); |
| +добавлено | req.on('error', onError); |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export async function readJson(req, limit) { |
| +добавлено | const text = await readBody(req, limit); |
| +добавлено | if (!text.trim()) return {}; |
| +добавлено | try { |
| +добавлено | const value = JSON.parse(text); |
| +добавлено | if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object'); |
| +добавлено | return value; |
| +добавлено | } catch { |
| +добавлено | throw new HttpError(400, 'invalid JSON body'); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Потоково пишет тело запроса в файл; возвращает число байт. Файл удаляется при ошибке. */ |
| +добавлено | export async function receiveToFile(req, filePath, limit) { |
| +добавлено | const declared = Number(req.headers['content-length']); |
| +добавлено | if (Number.isFinite(declared) && declared > limit) { |
| +добавлено | req.on('error', () => {}); |
| +добавлено | req.resume(); |
| +добавлено | throw tooLarge(limit); |
| +добавлено | } |
| +добавлено | let size = 0; |
| +добавлено | const counter = new Transform({ |
| +добавлено | transform(chunk, _enc, cb) { |
| +добавлено | size += chunk.length; |
| +добавлено | if (size > limit) cb(tooLarge(limit)); |
| +добавлено | else cb(null, chunk); |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | try { |
| +добавлено | await pipeline(req, counter, fs.createWriteStream(filePath, { flags: 'wx', mode: 0o600 })); |
| +добавлено | return size; |
| +добавлено | } catch (err) { |
| +добавлено | try { fs.rmSync(filePath, { force: true }); } catch { /* уже нет */ } |
| +добавлено | if (err instanceof HttpError) { |
| +добавлено | req.on('error', () => {}); |
| +добавлено | req.resume(); |
| +добавлено | } |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const CONTENT_TYPES = { |
| +добавлено | '.js': 'text/javascript; charset=utf-8', |
| +добавлено | '.mjs': 'text/javascript; charset=utf-8', |
| +добавлено | '.css': 'text/css; charset=utf-8', |
| +добавлено | '.html': 'text/html; charset=utf-8', |
| +добавлено | '.json': 'application/json; charset=utf-8', |
| +добавлено | '.svg': 'image/svg+xml', |
| +добавлено | '.png': 'image/png', |
| +добавлено | '.jpg': 'image/jpeg', |
| +добавлено | '.jpeg': 'image/jpeg', |
| +добавлено | '.gif': 'image/gif', |
| +добавлено | '.webp': 'image/webp', |
| +добавлено | '.avif': 'image/avif', |
| +добавлено | '.ico': 'image/x-icon', |
| +добавлено | '.woff': 'font/woff', |
| +добавлено | '.woff2': 'font/woff2', |
| +добавлено | '.ttf': 'font/ttf', |
| +добавлено | '.mp3': 'audio/mpeg', |
| +добавлено | '.wav': 'audio/wav', |
| +добавлено | '.mp4': 'video/mp4', |
| +добавлено | '.webm': 'video/webm', |
| +добавлено | '.txt': 'text/plain; charset=utf-8', |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export function contentTypeFor(name) { |
| +добавлено | const m = /\.[^.]+$/.exec(name.toLowerCase()); |
| +добавлено | return (m && CONTENT_TYPES[m[0]]) || 'application/octet-stream'; |
| +добавлено | } |
| +добавлено | // Состояние плагина в ZCode, токен агента (agent.json), потоковый multipart. |
| +добавлено | |
| +добавлено | import crypto from 'node:crypto'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { Readable } from 'node:stream'; |
| +добавлено | import { paths, PLUGIN_ID, ROOT } from './config.mjs'; |
| +добавлено | |
| +добавлено | function readJson(file) { |
| +добавлено | try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * installed — запись aura-team@local-marketplace в installed_plugins.json; |
| +добавлено | * enabled — installed && config.json plugins.enabled !== false && enabledPlugins[id] !== false. |
| +добавлено | * Файлы читаются заново на каждый вызов: переключатель в Settings → Plugins действует сразу. |
| +добавлено | */ |
| +добавлено | export function pluginState() { |
| +добавлено | const installedDoc = readJson(paths.installedPlugins); |
| +добавлено | const list = Array.isArray(installedDoc?.plugins) ? installedDoc.plugins : []; |
| +добавлено | const entry = list.find((p) => p?.id === PLUGIN_ID || (p?.name === 'aura-team' && p?.marketplace === 'local-marketplace')); |
| +добавлено | const installed = Boolean(entry); |
| +добавлено | const cfg = readJson(paths.cliConfig); |
| +добавлено | const plugins = cfg?.plugins ?? {}; |
| +добавлено | const enabled = installed |
| +добавлено | && plugins.enabled !== false |
| +добавлено | && (plugins.enabledPlugins ?? {})[PLUGIN_ID] !== false; |
| +добавлено | return { installed, enabled, version: entry?.version ?? null }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Токен агента: создаётся один раз, файл обновляется (порт/путь) при каждом старте. */ |
| +добавлено | export function ensureAgentFile(port) { |
| +добавлено | const file = paths.agentFile; |
| +добавлено | const prev = readJson(file); |
| +добавлено | const token = typeof prev?.token === 'string' && /^[0-9a-f]{64}$/.test(prev.token) |
| +добавлено | ? prev.token |
| +добавлено | : crypto.randomBytes(32).toString('hex'); |
| +добавлено | const doc = { port, token, serviceDir: ROOT }; |
| +добавлено | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| +добавлено | const tmp = `${file}.${process.pid}.tmp`; |
| +добавлено | fs.writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 }); |
| +добавлено | fs.renameSync(tmp, file); |
| +добавлено | try { fs.chmodSync(file, 0o600); } catch { /* Windows ACL */ } |
| +добавлено | return token; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function safeEqual(a, b) { |
| +добавлено | if (typeof a !== 'string' || typeof b !== 'string') return false; |
| +добавлено | const ba = Buffer.from(a); |
| +добавлено | const bb = Buffer.from(b); |
| +добавлено | return ba.length === bb.length && crypto.timingSafeEqual(ba, bb); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function quoteName(name) { |
| +добавлено | return String(name).replace(/[\r\n"\\]/g, '_'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * multipart/form-data с одним файлом без буферизации всего содержимого: |
| +добавлено | * head-буфер + fs.createReadStream + tail-буфер, Content-Length считается заранее. |
| +добавлено | */ |
| +добавлено | export function multipartFile({ filePath, fileName, fieldName = 'file', contentType = 'application/octet-stream' }) { |
| +добавлено | const boundary = `----zteam${crypto.randomBytes(12).toString('hex')}`; |
| +добавлено | // Имя в UTF-8 прямо в filename="…", как шлют браузеры: busboy (@fastify/multipart) |
| +добавлено | // при наличии и filename, и filename* берёт первое — кириллица превращалась в «_____». |
| +добавлено | const disp = `form-data; name="${fieldName}"; filename="${quoteName(fileName)}"`; |
| +добавлено | const head = Buffer.from(`--${boundary}\r\nContent-Disposition: ${disp}\r\nContent-Type: ${contentType}\r\n\r\n`, 'utf8'); |
| +добавлено | const tail = Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8'); |
| +добавлено | const size = fs.statSync(filePath).size; |
| +добавлено | const length = head.length + size + tail.length; |
| +добавлено | const makeBody = () => Readable.from((async function* gen() { |
| +добавлено | yield head; |
| +добавлено | for await (const chunk of fs.createReadStream(filePath, { highWaterMark: 256 * 1024 })) yield chunk; |
| +добавлено | yield tail; |
| +добавлено | })()); |
| +добавлено | return { boundary, length, makeBody, contentType: `multipart/form-data; boundary=${boundary}` }; |
| +добавлено | } |
| +добавлено | // Локальные провайдеры ZCode: чтение provider_config.json/key_pool.json (только маски наружу) |
| +добавлено | // и подключение провайдера команды через прокси-токен. |
| +добавлено | // |
| +добавлено | // ВАЖНО: схема provider_config.json в ZCode строгая (zod .strict()) — любое лишнее поле в |
| +добавлено | // правиле (например config.auraTeam) делает невалидным ВЕСЬ файл, и ZCode теряет все модели |
| +добавлено | // («Select a model before sending a message»). Поэтому маркер «правило создано Aura Team» |
| +добавлено | // хранится в соседнем файле aura_team_providers.json, а не в самом правиле. |
| +добавлено | |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { paths } from './config.mjs'; |
| +добавлено | |
| +добавлено | export const SIDECAR_NAME = 'aura_team_providers.json'; |
| +добавлено | const API_TYPES = new Set(['openai-chat-completions', 'openai-responses', 'anthropic-messages']); |
| +добавлено | |
| +добавлено | const providerConfigPath = () => paths.providerConfig; |
| +добавлено | const sidecarPath = () => path.join(path.dirname(providerConfigPath()), SIDECAR_NAME); |
| +добавлено | const poolPath = () => path.join(path.dirname(providerConfigPath()), 'key_pool.json'); |
| +добавлено | |
| +добавлено | export function maskKey(key) { |
| +добавлено | const k = String(key ?? '').trim(); |
| +добавлено | if (!k) return null; |
| +добавлено | return k.length <= 10 ? '••••' : `${k.slice(0, 3)}…${k.slice(-4)}`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Подсказка как на бэкенде (maskKey в keys.ts): 3 символа + … + 4. Нужна для дедупа. */ |
| +добавлено | export const backendHint = (key) => { |
| +добавлено | const k = String(key ?? '').trim(); |
| +добавлено | return k.length <= 8 ? '••••' : `${k.slice(0, 3)}…${k.slice(-4)}`; |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function readJsonFile(file, fallback) { |
| +добавлено | try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function writeJsonAtomic(file, value) { |
| +добавлено | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| +добавлено | const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; |
| +добавлено | try { |
| +добавлено | fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 }); |
| +добавлено | fs.renameSync(tmp, file); |
| +добавлено | } finally { |
| +добавлено | try { fs.unlinkSync(tmp); } catch { /* переименован */ } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function readProviderDoc() { |
| +добавлено | const file = providerConfigPath(); |
| +добавлено | let text; |
| +добавлено | try { text = fs.readFileSync(file, 'utf8'); } catch (err) { |
| +добавлено | if (err.code === 'ENOENT') return null; |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | return JSON.parse(text); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const readSidecar = () => { |
| +добавлено | const s = readJsonFile(sidecarPath(), null); |
| +добавлено | return s && typeof s === 'object' && s.providers && typeof s.providers === 'object' ? s : { version: 1, providers: {} }; |
| +добавлено | }; |
| +добавлено | const writeSidecar = (s) => writeJsonAtomic(sidecarPath(), s); |
| +добавлено | |
| +добавлено | const rulesOf = (doc) => doc?.config?.providerConfigRules?.providerRules ?? []; |
| +добавлено | |
| +добавлено | function modelsOf(rule) { |
| +добавлено | const c = rule?.config ?? {}; |
| +добавлено | return [...(c.modelOrder?.length ? c.modelOrder : c.personalModelIds ?? [])]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function keysOf(rule, pool) { |
| +добавлено | const primary = String(rule?.config?.access?.apiKey ?? '').trim(); |
| +добавлено | const extra = Array.isArray(pool?.providers?.[rule.providerId]?.keys) ? pool.providers[rule.providerId].keys : []; |
| +добавлено | return [...new Set([primary, ...extra.map((k) => String(k).trim())].filter(Boolean))]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Список локальных провайдеров без сырых ключей. */ |
| +добавлено | export function listLocalProviders() { |
| +добавлено | const doc = readProviderDoc(); |
| +добавлено | if (!doc) return []; |
| +добавлено | const pool = readJsonFile(poolPath(), { providers: {} }); |
| +добавлено | const sidecar = readSidecar(); |
| +добавлено | return rulesOf(doc) |
| +добавлено | .filter((rule) => rule?.config?.api?.baseUrl) |
| +добавлено | .map((rule) => { |
| +добавлено | const keys = keysOf(rule, pool); |
| +добавлено | const apiType = rule.config.api.type || 'anthropic-messages'; |
| +добавлено | return { |
| +добавлено | providerId: rule.providerId, |
| +добавлено | name: rule.providerName || rule.providerId, |
| +добавлено | apiType: API_TYPES.has(apiType) ? apiType : apiType, |
| +добавлено | baseUrl: rule.config.api.baseUrl, |
| +добавлено | models: modelsOf(rule), |
| +добавлено | enabled: rule.enabled !== false, |
| +добавлено | keyHint: maskKey(keys[0]), |
| +добавлено | keyCount: keys.length, |
| +добавлено | teamManaged: Boolean(sidecar.providers[rule.providerId]), |
| +добавлено | }; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Сырые ключи провайдера — только для внутреннего использования (shareLocalProvider). */ |
| +добавлено | export function localProviderSecrets(providerId) { |
| +добавлено | const doc = readProviderDoc(); |
| +добавлено | const rule = rulesOf(doc).find((r) => r.providerId === providerId); |
| +добавлено | if (!rule) return null; |
| +добавлено | const pool = readJsonFile(poolPath(), { providers: {} }); |
| +добавлено | return { |
| +добавлено | providerId, |
| +добавлено | name: rule.providerName || providerId, |
| +добавлено | apiType: rule.config?.api?.type || 'anthropic-messages', |
| +добавлено | baseUrl: rule.config?.api?.baseUrl ?? null, |
| +добавлено | models: modelsOf(rule), |
| +добавлено | primaryKey: String(rule.config?.access?.apiKey ?? '').trim() || null, |
| +добавлено | keys: keysOf(rule, pool), |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function backupOnce() { |
| +добавлено | const file = providerConfigPath(); |
| +добавлено | const backup = path.join(path.dirname(file), 'provider_config.before-team.json'); |
| +добавлено | if (!fs.existsSync(backup) && fs.existsSync(file)) fs.copyFileSync(file, backup); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function emptyDoc() { |
| +добавлено | return { |
| +добавлено | schemaVersion: 1, |
| +добавлено | config: { |
| +добавлено | providerOrder: [], |
| +добавлено | providerConfigRules: { providerRules: [] }, |
| +добавлено | modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] }, |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Добавляет/заменяет правило провайдера команды. Остальные поля документа не трогаются. |
| +добавлено | * Возвращает прежнюю запись сайдкара (если была) — чтобы вызывающий отозвал старый токен. |
| +добавлено | */ |
| +добавлено | export function upsertTeamProvider({ providerId, providerName, apiType, baseUrl, apiKey, models, teamId, tokenId }) { |
| +добавлено | backupOnce(); |
| +добавлено | const doc = readProviderDoc() ?? emptyDoc(); |
| +добавлено | doc.config ??= {}; |
| +добавлено | doc.config.providerConfigRules ??= { providerRules: [] }; |
| +добавлено | doc.config.providerConfigRules.providerRules ??= []; |
| +добавлено | doc.config.modelConfigRules ??= { providerModelRules: [], manualProviderModelRules: [] }; |
| +добавлено | doc.config.modelConfigRules.providerModelRules ??= []; |
| +добавлено | |
| +добавлено | const sidecar = readSidecar(); |
| +добавлено | const previous = sidecar.providers[providerId] ?? null; |
| +добавлено | |
| +добавлено | const rule = { |
| +добавлено | providerId, |
| +добавлено | providerName, |
| +добавлено | enabled: true, |
| +добавлено | config: { |
| +добавлено | group: 'standard-personal', |
| +добавлено | access: { type: 'api-key', apiKey }, |
| +добавлено | api: { type: apiType, baseUrl }, |
| +добавлено | personalModelIds: [...models], |
| +добавлено | modelOrder: [...models], |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | const rules = doc.config.providerConfigRules.providerRules; |
| +добавлено | const idx = rules.findIndex((r) => r.providerId === providerId); |
| +добавлено | if (idx >= 0) rules[idx] = rule; |
| +добавлено | else rules.push(rule); |
| +добавлено | |
| +добавлено | if (Array.isArray(doc.config.providerOrder)) { |
| +добавлено | if (!doc.config.providerOrder.includes(providerId)) doc.config.providerOrder.push(providerId); |
| +добавлено | } else { |
| +добавлено | doc.config.providerOrder = [providerId]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const modelRules = doc.config.modelConfigRules.providerModelRules; |
| +добавлено | const addedModels = new Set(previous?.addedModels ?? []); |
| +добавлено | // Модели, которые мы добавляли раньше, но которых нет в новом списке — убираем. |
| +добавлено | for (let i = modelRules.length - 1; i >= 0; i--) { |
| +добавлено | const r = modelRules[i]; |
| +добавлено | if (r.providerId === providerId && addedModels.has(r.modelId) && !models.includes(r.modelId)) { |
| +добавлено | modelRules.splice(i, 1); |
| +добавлено | addedModels.delete(r.modelId); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | for (const modelId of models) { |
| +добавлено | if (!modelRules.some((r) => r.providerId === providerId && r.modelId === modelId)) { |
| +добавлено | modelRules.push({ modelId, config: { enabled: true, properties: { inputFormat: { supportsText: true } } }, providerId }); |
| +добавлено | addedModels.add(modelId); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | writeJsonAtomic(providerConfigPath(), doc); |
| +добавлено | sidecar.providers[providerId] = { |
| +добавлено | teamId, |
| +добавлено | tokenId, |
| +добавлено | addedModels: [...addedModels], |
| +добавлено | addedOrder: previous ? previous.addedOrder : true, |
| +добавлено | connectedAt: new Date().toISOString(), |
| +добавлено | }; |
| +добавлено | writeSidecar(sidecar); |
| +добавлено | return previous; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Убирает правило, порядок и добавленные нами правила моделей. Возвращает запись сайдкара. */ |
| +добавлено | export function removeTeamProvider(providerId) { |
| +добавлено | const sidecar = readSidecar(); |
| +добавлено | const entry = sidecar.providers[providerId]; |
| +добавлено | if (!entry) return null; |
| +добавлено | const doc = readProviderDoc(); |
| +добавлено | if (doc?.config) { |
| +добавлено | backupOnce(); |
| +добавлено | const rules = doc.config.providerConfigRules?.providerRules; |
| +добавлено | if (Array.isArray(rules)) { |
| +добавлено | const i = rules.findIndex((r) => r.providerId === providerId); |
| +добавлено | if (i >= 0) rules.splice(i, 1); |
| +добавлено | } |
| +добавлено | if (Array.isArray(doc.config.providerOrder)) { |
| +добавлено | doc.config.providerOrder = doc.config.providerOrder.filter((p) => p !== providerId); |
| +добавлено | } |
| +добавлено | const added = new Set(entry.addedModels ?? []); |
| +добавлено | const modelRules = doc.config.modelConfigRules?.providerModelRules; |
| +добавлено | if (Array.isArray(modelRules)) { |
| +добавлено | doc.config.modelConfigRules.providerModelRules = modelRules.filter( |
| +добавлено | (r) => !(r.providerId === providerId && added.has(r.modelId)), |
| +добавлено | ); |
| +добавлено | } |
| +добавлено | writeJsonAtomic(providerConfigPath(), doc); |
| +добавлено | } |
| +добавлено | delete sidecar.providers[providerId]; |
| +добавлено | writeSidecar(sidecar); |
| +добавлено | return entry; |
| +добавлено | } |
| +добавлено | // Живая лента: SSE для панели + WebSocket к бэкенду (/v1/teams/:id/events?ticket=...). |
| +добавлено | |
| +добавлено | const PING_MS = 25_000; |
| +добавлено | const BACKOFF_MIN = 1_000; |
| +добавлено | const BACKOFF_MAX = 30_000; |
| +добавлено | const WANT_POLL_WINDOW = 60_000; |
| +добавлено | |
| +добавлено | export function createRealtime({ state, api, baseUrl, log = () => {}, onTeamEvent = () => {} }) { |
| +добавлено | const clients = new Set(); |
| +добавлено | let lastPluginPoll = 0; |
| +добавлено | let ws = null; |
| +добавлено | let wsTeam = null; |
| +добавлено | let status = 'idle'; // idle | connecting | connected |
| +добавлено | let backoff = BACKOFF_MIN; |
| +добавлено | let timer = null; |
| +добавлено | let generation = 0; |
| +добавлено | |
| +добавлено | function send(res, event, data) { |
| +добавлено | try { |
| +добавлено | res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); |
| +добавлено | } catch { /* клиент ушёл */ } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function broadcast(event, data) { |
| +добавлено | for (const res of clients) send(res, event, data); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const emitLocal = (type, extra = {}) => broadcast('local', { type, at: new Date().toISOString(), ...extra }); |
| +добавлено | |
| +добавлено | const pingTimer = setInterval(() => { |
| +добавлено | for (const res of clients) { |
| +добавлено | try { res.write(': ping\n\n'); } catch { /* закрыт */ } |
| +добавлено | } |
| +добавлено | }, PING_MS); |
| +добавлено | pingTimer.unref(); |
| +добавлено | |
| +добавлено | const checkTimer = setInterval(() => ensure(), 10_000); |
| +добавлено | checkTimer.unref(); |
| +добавлено | |
| +добавлено | function wanted() { |
| +добавлено | return Boolean(state.accessToken && state.teamId) |
| +добавлено | && (clients.size > 0 || Date.now() - lastPluginPoll < WANT_POLL_WINDOW); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function setStatus(next) { |
| +добавлено | if (status === next) return; |
| +добавлено | status = next; |
| +добавлено | emitLocal('realtime', { status }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function stop() { |
| +добавлено | generation++; |
| +добавлено | clearTimeout(timer); |
| +добавлено | timer = null; |
| +добавлено | if (ws) { |
| +добавлено | try { ws.close(1000, 'stop'); } catch { /* уже закрыт */ } |
| +добавлено | } |
| +добавлено | ws = null; |
| +добавлено | wsTeam = null; |
| +добавлено | backoff = BACKOFF_MIN; |
| +добавлено | setStatus('idle'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function schedule() { |
| +добавлено | clearTimeout(timer); |
| +добавлено | if (!wanted()) { setStatus('idle'); return; } |
| +добавлено | const delay = backoff; |
| +добавлено | backoff = Math.min(backoff * 2, BACKOFF_MAX); |
| +добавлено | timer = setTimeout(() => { timer = null; connect(); }, delay); |
| +добавлено | timer.unref?.(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function connect() { |
| +добавлено | if (!wanted()) { setStatus('idle'); return; } |
| +добавлено | if (ws && wsTeam === state.teamId) return; |
| +добавлено | const gen = ++generation; |
| +добавлено | const teamId = state.teamId; |
| +добавлено | setStatus('connecting'); |
| +добавлено | let ticket; |
| +добавлено | try { |
| +добавлено | const r = await api(`/v1/teams/${encodeURIComponent(teamId)}/events-ticket`, { method: 'POST', body: {} }); |
| +добавлено | ticket = r?.ticket; |
| +добавлено | if (!ticket) throw new Error('no ticket'); |
| +добавлено | } catch (err) { |
| +добавлено | if (gen !== generation) return; |
| +добавлено | log('realtime ticket failed', err.status ?? '', err.message); |
| +добавлено | schedule(); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (gen !== generation) return; |
| +добавлено | const url = `${baseUrl().replace(/^http/i, 'ws')}/v1/teams/${encodeURIComponent(teamId)}/events?ticket=${encodeURIComponent(ticket)}`; |
| +добавлено | let socket; |
| +добавлено | try { |
| +добавлено | socket = new WebSocket(url); |
| +добавлено | } catch (err) { |
| +добавлено | log('realtime ws failed', err.message); |
| +добавлено | schedule(); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | ws = socket; |
| +добавлено | wsTeam = teamId; |
| +добавлено | socket.addEventListener('open', () => { |
| +добавлено | if (gen !== generation) return; |
| +добавлено | backoff = BACKOFF_MIN; |
| +добавлено | setStatus('connected'); |
| +добавлено | }); |
| +добавлено | socket.addEventListener('message', (ev) => { |
| +добавлено | if (gen !== generation) return; |
| +добавлено | let msg; |
| +добавлено | try { msg = JSON.parse(typeof ev.data === 'string' ? ev.data : Buffer.from(ev.data).toString('utf8')); } catch { return; } |
| +добавлено | if (!msg || typeof msg.type !== 'string') return; |
| +добавлено | const data = { type: msg.type, at: msg.at ?? new Date().toISOString() }; |
| +добавлено | onTeamEvent(data); |
| +добавлено | broadcast('team', data); |
| +добавлено | }); |
| +добавлено | const onEnd = () => { |
| +добавлено | if (gen !== generation) return; |
| +добавлено | ws = null; |
| +добавлено | wsTeam = null; |
| +добавлено | setStatus(wanted() ? 'connecting' : 'idle'); |
| +добавлено | schedule(); |
| +добавлено | }; |
| +добавлено | socket.addEventListener('close', onEnd); |
| +добавлено | socket.addEventListener('error', () => { /* за ним придёт close */ }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function ensure() { |
| +добавлено | if (!wanted()) { |
| +добавлено | if (ws || timer) stop(); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (ws && wsTeam !== state.teamId) stop(); |
| +добавлено | if (!ws && !timer && status !== 'connecting') connect(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function restart() { |
| +добавлено | stop(); |
| +добавлено | ensure(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function addClient(req, res) { |
| +добавлено | res.writeHead(200, { |
| +добавлено | 'Content-Type': 'text/event-stream; charset=utf-8', |
| +добавлено | 'Cache-Control': 'no-store', |
| +добавлено | Connection: 'keep-alive', |
| +добавлено | 'X-Accel-Buffering': 'no', |
| +добавлено | }); |
| +добавлено | res.write(`retry: 3000\n\n`); |
| +добавлено | send(res, 'local', { type: 'hello', at: new Date().toISOString(), realtime: status }); |
| +добавлено | clients.add(res); |
| +добавлено | const drop = () => { |
| +добавлено | clients.delete(res); |
| +добавлено | // Ничего не держим без слушателей (кроме окна после опроса плагина). |
| +добавлено | setTimeout(ensure, 0); |
| +добавлено | }; |
| +добавлено | req.on('close', drop); |
| +добавлено | res.on('error', drop); |
| +добавлено | ensure(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function notePluginPoll() { |
| +добавлено | lastPluginPoll = Date.now(); |
| +добавлено | ensure(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function close() { |
| +добавлено | clearInterval(pingTimer); |
| +добавлено | clearInterval(checkTimer); |
| +добавлено | stop(); |
| +добавлено | for (const res of clients) { try { res.end(); } catch { /* */ } } |
| +добавлено | clients.clear(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | return { |
| +добавлено | addClient, emitLocal, broadcast, restart, stop, ensure, notePluginPoll, close, |
| +добавлено | get status() { return status; }, |
| +добавлено | get clientCount() { return clients.size; }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | // Состояние сервиса: state.json с зашифрованными токенами (AES-256-GCM, ключ в .state-key). |
| +добавлено | |
| +добавлено | import crypto from 'node:crypto'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { paths, DEFAULT_SERVER, localServer } from './config.mjs'; |
| +добавлено | |
| +добавлено | const AAD = Buffer.from('aura-team-state-v1'); |
| +добавлено | const MAX_RECENT = 8; |
| +добавлено | |
| +добавлено | function loadKey() { |
| +добавлено | try { |
| +добавлено | const key = Buffer.from(fs.readFileSync(paths.stateKey, 'utf8').trim(), 'base64'); |
| +добавлено | if (key.length === 32) return key; |
| +добавлено | } catch { /* нет ключа — создадим */ } |
| +добавлено | fs.mkdirSync(path.dirname(paths.stateKey), { recursive: true }); |
| +добавлено | const key = crypto.randomBytes(32); |
| +добавлено | fs.writeFileSync(paths.stateKey, key.toString('base64') + '\n', { mode: 0o600 }); |
| +добавлено | try { fs.chmodSync(paths.stateKey, 0o600); } catch { /* Windows ACL */ } |
| +добавлено | return key; |
| +добавлено | } |
| +добавлено | |
| +добавлено | let KEY = null; |
| +добавлено | const key = () => (KEY ??= loadKey()); |
| +добавлено | |
| +добавлено | function encrypt(secrets) { |
| +добавлено | const iv = crypto.randomBytes(12); |
| +добавлено | const cipher = crypto.createCipheriv('aes-256-gcm', key(), iv); |
| +добавлено | cipher.setAAD(AAD); |
| +добавлено | const data = Buffer.concat([cipher.update(JSON.stringify(secrets), 'utf8'), cipher.final()]); |
| +добавлено | return { v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function decrypt(box) { |
| +добавлено | if (!box || box.v !== 1) return {}; |
| +добавлено | const decipher = crypto.createDecipheriv('aes-256-gcm', key(), Buffer.from(box.iv, 'base64')); |
| +добавлено | decipher.setAAD(AAD); |
| +добавлено | decipher.setAuthTag(Buffer.from(box.tag, 'base64')); |
| +добавлено | return JSON.parse(Buffer.concat([decipher.update(Buffer.from(box.data, 'base64')), decipher.final()]).toString('utf8')); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function defaults() { |
| +добавлено | return { |
| +добавлено | // дистрибутив со встроенным сервером работает с ним же, пока пользователь не выбрал другой |
| +добавлено | serverUrl: localServer ? `http://127.0.0.1:${localServer.port}` : DEFAULT_SERVER, |
| +добавлено | accessToken: null, |
| +добавлено | refreshToken: null, |
| +добавлено | teamId: null, |
| +добавлено | workspace: null, |
| +добавлено | recentWorkspaces: [], |
| +добавлено | ui: {}, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function loadState(log = () => {}) { |
| +добавлено | const state = defaults(); |
| +добавлено | let migrate = false; |
| +добавлено | let raw; |
| +добавлено | try { |
| +добавлено | raw = JSON.parse(fs.readFileSync(paths.state, 'utf8')); |
| +добавлено | } catch { |
| +добавлено | return { state, migrate: false }; |
| +добавлено | } |
| +добавлено | let secrets = {}; |
| +добавлено | if (raw.secrets) { |
| +добавлено | try { secrets = decrypt(raw.secrets); } catch (err) { log('state decrypt failed', err.message); } |
| +добавлено | } |
| +добавлено | if (raw.accessToken || raw.refreshToken) migrate = true; |
| +добавлено | state.serverUrl = typeof raw.serverUrl === 'string' && raw.serverUrl ? raw.serverUrl : state.serverUrl; |
| +добавлено | // Встроенный сервер переезжает вместе с цифрой сборки: старый адрес показывает на выбранный вручную. |
| +добавлено | if (localServer && /^https?:\/\/auraide\.xyz\/?$/.test(state.serverUrl)) state.serverUrl = `http://127.0.0.1:${localServer.port}`; state.accessToken = secrets.accessToken ?? raw.accessToken ?? null; |
| +добавлено | state.refreshToken = secrets.refreshToken ?? raw.refreshToken ?? null; |
| +добавлено | state.teamId = raw.teamId ?? null; |
| +добавлено | state.workspace = raw.workspace ?? null; |
| +добавлено | state.recentWorkspaces = Array.isArray(raw.recentWorkspaces) |
| +добавлено | ? raw.recentWorkspaces.filter((p) => typeof p === 'string').slice(0, MAX_RECENT) |
| +добавлено | : []; |
| +добавлено | state.ui = raw.ui && typeof raw.ui === 'object' && !Array.isArray(raw.ui) ? raw.ui : {}; |
| +добавлено | // Старое поле theme переезжает в ui.theme. |
| +добавлено | if (typeof raw.theme === 'string' && state.ui.theme === undefined) state.ui.theme = raw.theme; |
| +добавлено | return { state, migrate }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function saveState(state) { |
| +добавлено | const payload = { |
| +добавлено | serverUrl: state.serverUrl, |
| +добавлено | teamId: state.teamId, |
| +добавлено | workspace: state.workspace, |
| +добавлено | recentWorkspaces: state.recentWorkspaces, |
| +добавлено | ui: state.ui, |
| +добавлено | secrets: encrypt({ accessToken: state.accessToken, refreshToken: state.refreshToken }), |
| +добавлено | }; |
| +добавлено | fs.mkdirSync(path.dirname(paths.state), { recursive: true }); |
| +добавлено | const tmp = `${paths.state}.${process.pid}.tmp`; |
| +добавлено | try { |
| +добавлено | fs.writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 }); |
| +добавлено | fs.renameSync(tmp, paths.state); |
| +добавлено | try { fs.chmodSync(paths.state, 0o600); } catch { /* Windows ACL */ } |
| +добавлено | } finally { |
| +добавлено | try { fs.unlinkSync(tmp); } catch { /* уже переименован */ } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function pushRecent(state, dir) { |
| +добавлено | if (!dir) return; |
| +добавлено | const norm = (p) => path.resolve(p).toLowerCase(); |
| +добавлено | state.recentWorkspaces = [dir, ...state.recentWorkspaces.filter((p) => norm(p) !== norm(dir))].slice(0, MAX_RECENT); |
| +добавлено | } |
| +добавлено | <!doctype html> |
| +добавлено | <html lang="ru"> |
| +добавлено | <head> |
| +добавлено | <meta charset="utf-8" /> |
| +добавлено | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| +добавлено | <meta name="color-scheme" content="dark light" /> |
| +добавлено | <title>Aura Team</title> |
| +добавлено | <link rel="icon" href="data:," /> |
| +добавлено | <link rel="stylesheet" href="/panel/assets/panel.css" /> |
| +добавлено | <style> |
| +добавлено | /* Критичный минимум до загрузки CSS — без белой вспышки. */ |
| +добавлено | html, body { background: #171717; margin: 0; height: 100%; } |
| +добавлено | html.light, html.light body { background: #f8f8f8; } |
| +добавлено | </style> |
| +добавлено | <script type="importmap"> |
| +добавлено | { |
| +добавлено | "imports": { |
| +добавлено | "preact": "/panel/assets/preact.module.js", |
| +добавлено | "preact/hooks": "/panel/assets/hooks.module.js", |
| +добавлено | "htm": "/panel/assets/htm.module.js" |
| +добавлено | } |
| +добавлено | } |
| +добавлено | </script> |
| +добавлено | <script> |
| +добавлено | // Тема до первой отрисовки: ?theme=light или prefers-color-scheme (родитель потом пришлёт zteam:theme). |
| +добавлено | (function () { |
| +добавлено | try { |
| +добавлено | var q = new URLSearchParams(location.search).get('theme'); |
| +добавлено | var light = q ? q === 'light' : (window.parent === window && matchMedia('(prefers-color-scheme: light)').matches); |
| +добавлено | if (light) document.documentElement.classList.add('light'); |
| +добавлено | } catch (e) { /* ignore */ } |
| +добавлено | })(); |
| +добавлено | </script> |
| +добавлено | </head> |
| +добавлено | <body> |
| +добавлено | <div id="app" aria-live="off"></div> |
| +добавлено | <noscript><p style="color:#e5e5e5;font:13px system-ui;padding:16px">Для панели Aura Team нужен JavaScript.</p></noscript> |
| +добавлено | <script type="module" src="/panel/assets/main.js"></script> |
| +добавлено | </body> |
| +добавлено | </html> |
| +добавлено | // Aura Team — локальный сервис для правой панели ZCode (v2). |
| +добавлено | // Проксирует API team-server.invalid, хранит токены (зашифрованы), отдаёт UI на /panel, |
| +добавлено | // живую ленту по SSE, загрузку файлов потоком, git, локальных провайдеров ZCode |
| +добавлено | // и ограниченный API для ИИ-агентов (/agent/rpc, плагин aura-team). |
| +добавлено | // |
| +добавлено | // Запуск: node server.mjs → http://127.0.0.1:8790/panel |
| +добавлено | // Окружение: ZTEAM_PORT, ZTEAM_STATE_DIR, ZTEAM_ZCODE_HOME, ZTEAM_PROVIDER_CONFIG, |
| +добавлено | // ZTEAM_AGENT_FILE, ZTEAM_TMP_DIR, ZTEAM_SERVER_URL (см. lib/config.mjs). |
| +добавлено | |
| +добавлено | import http from 'node:http'; |
| +добавлено | import crypto from 'node:crypto'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { execFile, spawn } from 'node:child_process'; |
| +добавлено | import { Readable } from 'node:stream'; |
| +добавлено | import { pipeline } from 'node:stream/promises'; |
| +добавлено | |
| +добавлено | import { PORT, paths, localServer } from './lib/config.mjs'; |
| +добавлено | import { HttpError, sendJson, readJson, receiveToFile, contentTypeFor } from './lib/http.mjs'; |
| +добавлено | import { loadState, saveState as persistState, pushRecent } from './lib/state.mjs'; |
| +добавлено | import { createApi } from './lib/api.mjs'; |
| +добавлено | import { createRealtime } from './lib/realtime.mjs'; |
| +добавлено | import { pluginState, ensureAgentFile, safeEqual, multipartFile } from './lib/plugin.mjs'; |
| +добавлено | import * as git from './lib/git.mjs'; |
| +добавлено | import { |
| +добавлено | listLocalProviders, localProviderSecrets, upsertTeamProvider, removeTeamProvider, readSidecar, backendHint, |
| +добавлено | } from './lib/providers.mjs'; |
| +добавлено | |
| +добавлено | const VERSION = '2'; |
| +добавлено | const MAX_BODY_BYTES = 1024 * 1024; |
| +добавлено | const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024; |
| +добавлено | const CSRF_TOKEN = crypto.randomBytes(24).toString('hex'); |
| +добавлено | const TASK_STATUSES = ['todo', 'doing', 'review', 'done']; |
| +добавлено | |
| +добавлено | const log = (...a) => console.log(new Date().toISOString(), '[team]', ...a); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- состояние |
| +добавлено | |
| +добавлено | const loaded = loadState(log); |
| +добавлено | const state = loaded.state; |
| +добавлено | const saveState = () => persistState(state); |
| +добавлено | if (loaded.migrate) { |
| +добавлено | saveState(); |
| +добавлено | log('state migrated to encrypted secrets'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- встроенный сервер |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Дистрибутив везёт с собой aura-team-server — поднимаем его до приёма запросов. |
| +добавлено | * Секреты генерируются здесь при первом старте и лежат в data того же пакета. |
| +добавлено | */ |
| +добавлено | let localServerProcess = null; |
| +добавлено | async function ensureLocalServer() { |
| +добавлено | if (!localServer) return; |
| +добавлено | const up = async () => { |
| +добавлено | try { |
| +добавлено | const r = await fetch(`http://127.0.0.1:${localServer.port}/health`, { signal: AbortSignal.timeout(1200) }); |
| +добавлено | return r.ok; |
| +добавлено | } catch { |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | if (await up()) return; |
| +добавлено | const dataDir = path.join(localServer.dataDir, 'data'); |
| +добавлено | fs.mkdirSync(dataDir, { recursive: true }); |
| +добавлено | const secretFile = path.join(dataDir, '.secrets.json'); |
| +добавлено | let secrets; |
| +добавлено | try { secrets = JSON.parse(fs.readFileSync(secretFile, 'utf8')); } catch { secrets = null; } |
| +добавлено | if (!secrets?.jwt || !secrets?.master) { |
| +добавлено | secrets = { jwt: crypto.randomBytes(48).toString('base64'), master: crypto.randomBytes(32).toString('base64') }; |
| +добавлено | fs.writeFileSync(secretFile, JSON.stringify(secrets), { mode: 0o600 }); |
| +добавлено | } |
| +добавлено | const logFd = fs.openSync(path.join(dataDir, 'server.log'), 'a'); |
| +добавлено | localServerProcess = spawn(process.execPath, [localServer.entry], { |
| +добавлено | cwd: localServer.dataDir, |
| +добавлено | env: { |
| +добавлено | ...process.env, |
| +добавлено | AURA_HOST: '127.0.0.1', |
| +добавлено | AURA_PORT: String(localServer.port), |
| +добавлено | AURA_PUBLIC_URL: `http://127.0.0.1:${localServer.port}`, |
| +добавлено | AURA_DATA_DIR: dataDir, |
| +добавлено | AURA_JWT_SECRET: secrets.jwt, |
| +добавлено | AURA_MASTER_KEY: secrets.master, |
| +добавлено | NODE_ENV: 'production', |
| +добавлено | }, |
| +добавлено | stdio: ['ignore', logFd, logFd], |
| +добавлено | windowsHide: true, |
| +добавлено | }); |
| +добавлено | localServerProcess.on('exit', (code) => { log(`local server exited (${code})`); localServerProcess = null; }); |
| +добавлено | for (let i = 0; i < 40; i++) { |
| +добавлено | if (await up()) return log(`local server up on ${localServer.port}`); |
| +добавлено | await new Promise((r) => setTimeout(r, 250)); |
| +добавлено | } |
| +добавлено | log('local server did not answer in 10s — см. data/server.log'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | let port = PORT; |
| +добавлено | let agentToken = null; |
| +добавлено | let ide = null; |
| +добавлено | const writtenPaths = new Set(); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- API и realtime |
| +добавлено | |
| +добавлено | const client = createApi({ |
| +добавлено | state, |
| +добавлено | save: saveState, |
| +добавлено | log, |
| +добавлено | onSignedOut: () => { |
| +добавлено | invalidateCaches(); |
| +добавлено | realtime?.stop(); |
| +добавлено | realtime?.emitLocal('state'); |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | const { api, raw, parse, baseUrl } = client; |
| +добавлено | |
| +добавлено | let pendingCache = null; |
| +добавлено | let pendingInflight = null; |
| +добавлено | let meCache = null; |
| +добавлено | |
| +добавлено | function invalidateCaches() { |
| +добавлено | pendingCache = null; |
| +добавлено | meCache = null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const realtime = createRealtime({ |
| +добавлено | state, |
| +добавлено | api, |
| +добавлено | baseUrl, |
| +добавлено | log, |
| +добавлено | onTeamEvent: (ev) => { |
| +добавлено | if (/^(task|membership|member|team)\./.test(ev.type)) pendingCache = null; |
| +добавлено | if (/^(membership|member|team)\./.test(ev.type)) meCache = null; |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | function requireAuth() { |
| +добавлено | if (!state.accessToken) throw new HttpError(401, 'not signed in'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function getMe({ fresh = false } = {}) { |
| +добавлено | requireAuth(); |
| +добавлено | if (!fresh && meCache && Date.now() - meCache.at < 30_000) return meCache.value; |
| +добавлено | const value = await api('/v1/me'); |
| +добавлено | meCache = { at: Date.now(), value }; |
| +добавлено | return value; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const enc = encodeURIComponent; |
| +добавлено | |
| +добавлено | function teamIdOf(params) { |
| +добавлено | const id = params?.teamId || state.teamId; |
| +добавлено | if (!id || typeof id !== 'string') throw new HttpError(400, 'no team selected'); |
| +добавлено | return id; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const T = (params) => `/v1/teams/${enc(teamIdOf(params))}`; |
| +добавлено | |
| +добавлено | function need(value, name) { |
| +добавлено | if (value === undefined || value === null || value === '') throw new HttpError(400, `${name} is required`); |
| +добавлено | return value; |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Только определённые поля (null сохраняется — это явный сброс). */ |
| +добавлено | function pick(obj, keys) { |
| +добавлено | const out = {}; |
| +добавлено | for (const k of keys) if (obj[k] !== undefined) out[k] = obj[k]; |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function setTokens(tokens) { |
| +добавлено | if (!tokens?.accessToken) throw new HttpError(502, 'backend returned no tokens'); |
| +добавлено | state.accessToken = tokens.accessToken; |
| +добавлено | state.refreshToken = tokens.refreshToken ?? null; |
| +добавлено | invalidateCaches(); |
| +добавлено | saveState(); |
| +добавлено | realtime.restart(); |
| +добавлено | realtime.emitLocal('state'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function selectTeam(teamId) { |
| +добавлено | state.teamId = teamId ?? null; |
| +добавлено | pendingCache = null; |
| +добавлено | saveState(); |
| +добавлено | realtime.restart(); |
| +добавлено | realtime.emitLocal('state'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function pendingCount() { |
| +добавлено | if (!state.accessToken || !state.teamId) return 0; |
| +добавлено | const teamId = state.teamId; |
| +добавлено | if (pendingCache && pendingCache.teamId === teamId && Date.now() - pendingCache.at < 15_000) return pendingCache.value; |
| +добавлено | pendingInflight ??= (async () => { |
| +добавлено | try { |
| +добавлено | const [me, board] = await Promise.all([getMe(), api(`/v1/teams/${enc(teamId)}/board`)]); |
| +добавлено | const myId = me?.user?.id; |
| +добавлено | const value = myId ? (board?.tasks ?? []).filter((t) => t.status !== 'done' && t.assigneeId === myId).length : 0; |
| +добавлено | pendingCache = { teamId, at: Date.now(), value }; |
| +добавлено | return value; |
| +добавлено | } finally { |
| +добавлено | pendingInflight = null; |
| +добавлено | } |
| +добавлено | })(); |
| +добавлено | return pendingInflight; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- файлы |
| +добавлено | |
| +добавлено | function sanitizeFileName(name, fallback = 'file') { |
| +добавлено | const base = String(name ?? '').split(/[\\/]/).pop() ?? ''; |
| +добавлено | // eslint-disable-next-line no-control-regex |
| +добавлено | let clean = base.replace(/[<>:"|?*\x00-\x1f]/g, '_').replace(/[. ]+$/, '').trim(); |
| +добавлено | if (/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(clean)) clean = `_${clean}`; |
| +добавлено | return clean.slice(0, 200) || fallback; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function filenameFromDisposition(cd, fallback) { |
| +добавлено | if (cd) { |
| +добавлено | const star = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(cd); |
| +добавлено | if (star) { try { return decodeURIComponent(star[1].trim().replace(/^"|"$/g, '')); } catch { /* битое */ } } |
| +добавлено | const plain = /filename\s*=\s*"?([^";]+)"?/i.exec(cd); |
| +добавлено | if (plain) return plain[1]; |
| +добавлено | } |
| +добавлено | return fallback; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function openUnique(dir, name) { |
| +добавлено | const ext = path.extname(name); |
| +добавлено | const stem = ext ? name.slice(0, -ext.length) : name; |
| +добавлено | for (let i = 0; i < 1000; i++) { |
| +добавлено | const candidate = path.join(dir, i === 0 ? name : `${stem} (${i})${ext}`); |
| +добавлено | try { |
| +добавлено | const fd = fs.openSync(candidate, 'wx', 0o644); |
| +добавлено | return { fd, file: candidate }; |
| +добавлено | } catch (err) { |
| +добавлено | if (err.code !== 'EEXIST') throw err; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | throw new HttpError(409, 'too many files with the same name'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function downloadsDir() { |
| +добавлено | return path.join(os.userInfo().homedir, 'Downloads'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function downloadTo(pathname, { targetDir, fallbackName }) { |
| +добавлено | requireAuth(); |
| +добавлено | const dir = targetDir ? path.resolve(String(targetDir)) : downloadsDir(); |
| +добавлено | if (targetDir) { |
| +добавлено | if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new HttpError(400, `target directory not found: ${dir}`); |
| +добавлено | } else { |
| +добавлено | fs.mkdirSync(dir, { recursive: true }); |
| +добавлено | } |
| +добавлено | const res = await raw(pathname, () => ({ method: 'GET' }), { timeoutMs: 3_600_000 }); |
| +добавлено | if (!res.ok) await parse(res); |
| +добавлено | const name = sanitizeFileName(filenameFromDisposition(res.headers.get('content-disposition'), fallbackName), fallbackName); |
| +добавлено | const { fd, file } = openUnique(dir, name); |
| +добавлено | try { |
| +добавлено | await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(file, { fd })); |
| +добавлено | } catch (err) { |
| +добавлено | try { fs.rmSync(file, { force: true }); } catch { /* */ } |
| +добавлено | throw err; |
| +добавлено | } |
| +добавлено | writtenPaths.add(path.resolve(file)); |
| +добавлено | return { path: file, name: path.basename(file), bytes: fs.statSync(file).size }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function uploadMultipart(pathname, { filePath, fileName }) { |
| +добавлено | const form = multipartFile({ filePath, fileName }); |
| +добавлено | const res = await raw(pathname, () => ({ |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': form.contentType, 'content-length': String(form.length) }, |
| +добавлено | body: form.makeBody(), |
| +добавлено | duplex: 'half', |
| +добавлено | }), { timeoutMs: 3_600_000 }); |
| +добавлено | return parse(res); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function isInside(child, parent) { |
| +добавлено | if (!parent) return false; |
| +добавлено | const c = path.resolve(child).toLowerCase(); |
| +добавлено | const p = path.resolve(parent).toLowerCase(); |
| +добавлено | return c === p || c.startsWith(p.endsWith(path.sep) ? p : p + path.sep); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function revealAllowed(abs) { |
| +добавлено | if (writtenPaths.has(abs)) return true; |
| +добавлено | return [state.workspace, ...state.recentWorkspaces].filter(Boolean).some((dir) => isInside(abs, dir)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- задачи (общие для панели и агента) |
| +добавлено | |
| +добавлено | function normalizeTask(t, members = []) { |
| +добавлено | const assigneeId = t.assigneeId ?? t.assignee_id ?? null; |
| +добавлено | const assigneeName = t.assigneeName ?? members.find((m) => m.id === assigneeId)?.displayName ?? null; |
| +добавлено | const desc = typeof t.description === 'string' ? t.description : ''; |
| +добавлено | return { |
| +добавлено | id: t.id, |
| +добавлено | shortId: String(t.id).slice(0, 8), |
| +добавлено | title: t.title, |
| +добавлено | status: t.status, |
| +добавлено | priority: t.priority ?? 'normal', |
| +добавлено | labels: Array.isArray(t.labels) ? t.labels : (() => { try { return JSON.parse(t.labels ?? '[]'); } catch { return []; } })(), |
| +добавлено | assigneeId, |
| +добавлено | assigneeName, |
| +добавлено | dueAt: t.dueAt ?? t.due_at ?? null, |
| +добавлено | description: desc.length > 500 ? `${desc.slice(0, 500)}…` : desc, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function resolveTaskId(board, ref) { |
| +добавлено | const id = String(ref ?? '').trim().replace(/^#/, '').toLowerCase(); |
| +добавлено | if (!id) throw new HttpError(400, 'taskId is required'); |
| +добавлено | const tasks = board?.tasks ?? []; |
| +добавлено | const exact = tasks.find((t) => String(t.id).toLowerCase() === id); |
| +добавлено | if (exact) return exact; |
| +добавлено | if (id.length < 6) throw new HttpError(400, 'taskId prefix must be at least 6 characters'); |
| +добавлено | const found = tasks.filter((t) => String(t.id).toLowerCase().startsWith(id)); |
| +добавлено | if (found.length === 0) throw new HttpError(404, `task #${id} not found`); |
| +добавлено | if (found.length > 1) throw new HttpError(409, `task prefix #${id} is ambiguous (${found.length} matches)`); |
| +добавлено | return found[0]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function resolveMember(members, ref) { |
| +добавлено | const q = String(ref ?? '').trim().replace(/^@/, '').toLowerCase(); |
| +добавлено | if (!q) return null; |
| +добавлено | const byId = members.find((m) => String(m.id).toLowerCase() === q); |
| +добавлено | if (byId) return byId; |
| +добавлено | const byEmail = members.find((m) => String(m.email ?? '').toLowerCase() === q); |
| +добавлено | if (byEmail) return byEmail; |
| +добавлено | const byName = members.filter((m) => String(m.displayName ?? '').toLowerCase() === q); |
| +добавлено | if (byName.length === 1) return byName[0]; |
| +добавлено | const partial = members.filter((m) => String(m.displayName ?? '').toLowerCase().includes(q) || String(m.email ?? '').toLowerCase().startsWith(q)); |
| +добавлено | if (partial.length === 1) return partial[0]; |
| +добавлено | if (byName.length > 1 || partial.length > 1) throw new HttpError(409, `assignee "${ref}" is ambiguous`); |
| +добавлено | throw new HttpError(404, `member "${ref}" not found in the team`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function checkStatus(status) { |
| +добавлено | if (status !== undefined && !TASK_STATUSES.includes(status)) { |
| +добавлено | throw new HttpError(400, `status must be one of: ${TASK_STATUSES.join(', ')}`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- RPC панели |
| +добавлено | |
| +добавлено | const ops = { |
| +добавлено | // --- вход и профиль |
| +добавлено | async session() { |
| +добавлено | return getMe({ fresh: true }); |
| +добавлено | }, |
| +добавлено | async login({ email, password }) { |
| +добавлено | need(email, 'email'); |
| +добавлено | need(password, 'password'); |
| +добавлено | setTokens(await api('/v1/auth/login', { method: 'POST', body: { email, password }, auth: false })); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | async register({ email, password, displayName }) { |
| +добавлено | need(email, 'email'); |
| +добавлено | need(password, 'password'); |
| +добавлено | await api('/v1/auth/register', { method: 'POST', body: { email, password, displayName }, auth: false }); |
| +добавлено | setTokens(await api('/v1/auth/login', { method: 'POST', body: { email, password }, auth: false })); |
| +добавлено | return { ok: true, signedIn: true }; |
| +добавлено | }, |
| +добавлено | async deviceStart() { |
| +добавлено | return api('/v1/auth/device', { method: 'POST', body: {}, auth: false }); |
| +добавлено | }, |
| +добавлено | async devicePoll({ deviceCode }) { |
| +добавлено | need(deviceCode, 'deviceCode'); |
| +добавлено | const result = await api('/v1/auth/device/token', { method: 'POST', body: { deviceCode }, auth: false }); |
| +добавлено | if (result?.accessToken) { |
| +добавлено | setTokens(result); |
| +добавлено | return { ok: true }; |
| +добавлено | } |
| +добавлено | return { pending: true }; |
| +добавлено | }, |
| +добавлено | async logout() { |
| +добавлено | state.accessToken = null; |
| +добавлено | state.refreshToken = null; |
| +добавлено | state.teamId = null; |
| +добавлено | invalidateCaches(); |
| +добавлено | saveState(); |
| +добавлено | realtime.stop(); |
| +добавлено | realtime.emitLocal('state'); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | async changePassword({ currentPassword, newPassword }) { |
| +добавлено | need(currentPassword, 'currentPassword'); |
| +добавлено | need(newPassword, 'newPassword'); |
| +добавлено | const me = await getMe({ fresh: true }); |
| +добавлено | const email = me?.user?.email; |
| +добавлено | await api('/v1/auth/password', { method: 'POST', body: { currentPassword, newPassword } }); |
| +добавлено | // Сервер отзывает все refresh-токены — входим заново с новым паролем. |
| +добавлено | try { |
| +добавлено | setTokens(await api('/v1/auth/login', { method: 'POST', body: { email, password: newPassword }, auth: false })); |
| +добавлено | return { ok: true, relogged: true }; |
| +добавлено | } catch (err) { |
| +добавлено | log('re-login after password change failed', err.status ?? '', err.message); |
| +добавлено | return { ok: true, relogged: false }; |
| +добавлено | } |
| +добавлено | }, |
| +добавлено | async updateProfile(p) { |
| +добавлено | const body = pick(p, ['displayName', 'bio', 'avatarColor', 'status']); |
| +добавлено | const user = await api('/v1/me', { method: 'PATCH', body }); |
| +добавлено | meCache = null; |
| +добавлено | return user; |
| +добавлено | }, |
| +добавлено | |
| +добавлено | // --- команды |
| +добавлено | async teams() { |
| +добавлено | return (await getMe({ fresh: true }))?.teams ?? []; |
| +добавлено | }, |
| +добавлено | async selectTeam({ teamId }) { |
| +добавлено | if (teamId !== null && (typeof teamId !== 'string' || !teamId)) throw new HttpError(400, 'teamId is required'); |
| +добавлено | selectTeam(teamId); |
| +добавлено | return { teamId: state.teamId }; |
| +добавлено | }, |
| +добавлено | async createTeam({ name }) { |
| +добавлено | need(name, 'name'); |
| +добавлено | const team = await api('/v1/teams', { method: 'POST', body: { name } }); |
| +добавлено | meCache = null; |
| +добавлено | if (team?.id) selectTeam(team.id); |
| +добавлено | return team; |
| +добавлено | }, |
| +добавлено | async joinTeam({ code }) { |
| +добавлено | need(code, 'code'); |
| +добавлено | const before = new Set(((await getMe({ fresh: true }))?.teams ?? []).map((t) => t.id)); |
| +добавлено | await api('/v1/invites/accept', { method: 'POST', body: { code } }); |
| +добавлено | const after = (await getMe({ fresh: true }))?.teams ?? []; |
| +добавлено | const joined = after.find((t) => !before.has(t.id)); |
| +добавлено | if (joined) selectTeam(joined.id); |
| +добавлено | return { ok: true, teamId: joined?.id ?? null, team: joined ?? null }; |
| +добавлено | }, |
| +добавлено | async renameTeam(p) { |
| +добавлено | need(p.name, 'name'); |
| +добавлено | const r = await api(T(p), { method: 'PATCH', body: { name: p.name } }); |
| +добавлено | meCache = null; |
| +добавлено | return r; |
| +добавлено | }, |
| +добавлено | async leaveTeam(p) { |
| +добавлено | const teamId = teamIdOf(p); |
| +добавлено | await api(`/v1/teams/${enc(teamId)}/leave`, { method: 'POST', body: {} }); |
| +добавлено | meCache = null; |
| +добавлено | if (state.teamId === teamId) selectTeam(null); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | invite: (p) => api(`${T(p)}/invite`), |
| +добавлено | createInvite: (p) => api(`${T(p)}/invites`, { method: 'POST', body: pick(p, ['role']) }), |
| +добавлено | revokeInvite: (p) => api(`${T(p)}/invite`, { method: 'DELETE' }), |
| +добавлено | directory: (p) => api(`${T(p)}/directory?q=${enc(p.q ?? '')}`), |
| +добавлено | addMember: (p) => api(`${T(p)}/invites/send`, { method: 'POST', body: { userId: need(p.userId, 'userId'), ...pick(p, ['role']) } }), |
| +добавлено | setRole: (p) => api(`${T(p)}/members/${enc(need(p.memberId, 'memberId'))}`, { method: 'PATCH', body: { role: need(p.role, 'role') } }), |
| +добавлено | async removeMember(p) { |
| +добавлено | await api(`${T(p)}/members/${enc(need(p.memberId, 'memberId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | setQuota: (p) => api(`${T(p)}/members/${enc(need(p.memberId, 'memberId'))}/quota`, { method: 'PUT', body: { dailyRequests: p.dailyRequests ?? null } }), |
| +добавлено | |
| +добавлено | // --- доска |
| +добавлено | board: (p) => api(`${T(p)}/board`), |
| +добавлено | summary: (p) => api(`${T(p)}/summary${p.limit ? `?limit=${enc(p.limit)}` : ''}`), |
| +добавлено | async createTask(p) { |
| +добавлено | need(p.title, 'title'); |
| +добавлено | const r = await api(`${T(p)}/tasks`, { method: 'POST', body: pick(p, ['title', 'description', 'status', 'assigneeId', 'priority', 'labels', 'dueAt']) }); |
| +добавлено | pendingCache = null; |
| +добавлено | return r; |
| +добавлено | }, |
| +добавлено | async updateTask(p) { |
| +добавлено | const r = await api(`${T(p)}/tasks/${enc(need(p.taskId, 'taskId'))}`, { method: 'PATCH', body: p.changes ?? {} }); |
| +добавлено | pendingCache = null; |
| +добавлено | return r; |
| +добавлено | }, |
| +добавлено | async deleteTask(p) { |
| +добавлено | await api(`${T(p)}/tasks/${enc(need(p.taskId, 'taskId'))}`, { method: 'DELETE' }); |
| +добавлено | pendingCache = null; |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | async restoreTask(p) { |
| +добавлено | await api(`${T(p)}/tasks/${enc(need(p.taskId, 'taskId'))}/restore`, { method: 'PATCH', body: {} }); |
| +добавлено | pendingCache = null; |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | trash: (p) => api(`${T(p)}/tasks/trash`), |
| +добавлено | async reorderTasks(p) { |
| +добавлено | await api(`${T(p)}/tasks/reorder`, { method: 'POST', body: { status: p.status, orderedIds: p.orderedIds } }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | taskHistory: (p) => api(`${T(p)}/tasks/${enc(need(p.taskId, 'taskId'))}/history`), |
| +добавлено | taskCommits: (p) => api(`${T(p)}/tasks/${enc(need(p.taskId, 'taskId'))}/commits`), |
| +добавлено | activity: (p) => api(`${T(p)}/activity?limit=${enc(p.limit ?? 20)}`), |
| +добавлено | async deleteActivity(p) { |
| +добавлено | await api(`${T(p)}/activity/${enc(need(p.eventId, 'eventId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | |
| +добавлено | // --- ключи и провайдеры |
| +добавлено | keys: (p) => api(`${T(p)}/keys`), |
| +добавлено | keyGroups: (p) => api(`${T(p)}/key-groups`), |
| +добавлено | addKey: (p) => api(`${T(p)}/keys`, { |
| +добавлено | method: 'POST', |
| +добавлено | body: pick(p, ['provider', 'value', 'accessRole', 'label', 'priority', 'groupId', 'baseUrl', 'model', 'models', 'dailyLimit']), |
| +добавлено | }), |
| +добавлено | updateKey: (p) => api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}`, { method: 'PATCH', body: p.changes ?? {} }), |
| +добавлено | pingKey: (p) => api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}/ping`, { method: 'POST', body: {} }), |
| +добавлено | revealKey: (p) => api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}/reveal`, { method: 'POST', body: {} }), |
| +добавлено | async deleteKey(p) { |
| +добавлено | await api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}/remove`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | async disableKey(p) { |
| +добавлено | await api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | async enableKey(p) { |
| +добавлено | await api(`${T(p)}/keys/${enc(need(p.keyId, 'keyId'))}/enable`, { method: 'POST', body: {} }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | checkAllKeys: (p) => api(`${T(p)}/keys/check`, { method: 'POST', body: {} }), |
| +добавлено | providers: (p) => api(`${T(p)}/providers`), |
| +добавлено | usage: (p) => api(`${T(p)}/usage${p.days ? `?days=${enc(p.days)}` : ''}`), |
| +добавлено | limits: (p) => api(`${T(p)}/limits`), |
| +добавлено | proxyTokens: (p) => api(`${T(p)}/proxy-tokens`), |
| +добавлено | async revokeProxyToken(p) { |
| +добавлено | await api(`${T(p)}/proxy-tokens/${enc(need(p.tokenId, 'tokenId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | |
| +добавлено | async localProviders() { |
| +добавлено | return listLocalProviders(); |
| +добавлено | }, |
| +добавлено | async shareLocalProvider(p) { |
| +добавлено | requireAuth(); |
| +добавлено | const secrets = localProviderSecrets(need(p.providerId, 'providerId')); |
| +добавлено | if (!secrets) throw new HttpError(404, `local provider ${p.providerId} not found`); |
| +добавлено | if (!secrets.baseUrl) throw new HttpError(400, 'local provider has no base URL'); |
| +добавлено | const values = p.allKeys ? secrets.keys : [secrets.primaryKey].filter(Boolean); |
| +добавлено | if (values.length === 0) throw new HttpError(400, 'local provider has no API key'); |
| +добавлено | const models = Array.isArray(p.models) ? p.models.filter((m) => typeof m === 'string' && m) : secrets.models; |
| +добавлено | const provider = secrets.apiType === 'anthropic-messages' ? 'anthropic' : 'openai'; |
| +добавлено | const norm = (u) => String(u ?? '').trim().replace(/\/+$/, '').toLowerCase(); |
| +добавлено | const existing = (await api(`${T(p)}/keys`)) ?? []; |
| +добавлено | const result = { created: 0, skipped: 0, keys: [], skippedHints: [] }; |
| +добавлено | for (const value of values) { |
| +добавлено | const hint = backendHint(value); |
| +добавлено | if (existing.some((k) => k.keyHint === hint && norm(k.baseUrl) === norm(secrets.baseUrl))) { |
| +добавлено | result.skipped++; |
| +добавлено | result.skippedHints.push(hint); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | const created = await api(`${T(p)}/keys`, { |
| +добавлено | method: 'POST', |
| +добавлено | body: { |
| +добавлено | provider, |
| +добавлено | value, |
| +добавлено | accessRole: p.accessRole ?? 'dev', |
| +добавлено | label: p.label || `${secrets.name} (shared)`, |
| +добавлено | baseUrl: secrets.baseUrl, |
| +добавлено | model: models[0] ?? null, |
| +добавлено | models, |
| +добавлено | dailyLimit: p.dailyLimit ?? null, |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | existing.push({ keyHint: hint, baseUrl: secrets.baseUrl }); |
| +добавлено | result.created++; |
| +добавлено | result.keys.push({ id: created?.id, label: created?.label, keyHint: created?.keyHint ?? hint }); |
| +добавлено | } |
| +добавлено | return result; |
| +добавлено | }, |
| +добавлено | async connectTeamProvider(p) { |
| +добавлено | requireAuth(); |
| +добавлено | const provider = p.provider; |
| +добавлено | if (provider !== 'openai' && provider !== 'anthropic') throw new HttpError(400, "provider must be 'openai' or 'anthropic'"); |
| +добавлено | const models = [...new Set((Array.isArray(p.models) ? p.models : []).filter((m) => typeof m === 'string' && m.trim()).map((m) => m.trim()))]; |
| +добавлено | if (models.length === 0) throw new HttpError(400, 'models must be a non-empty array'); |
| +добавлено | const teamId = teamIdOf(p); |
| +добавлено | const me = await getMe(); |
| +добавлено | const team = (me?.teams ?? []).find((t) => t.id === teamId); |
| +добавлено | const providerId = `team-${provider}-${teamId.slice(0, 8)}`; |
| +добавлено | const token = await api(`/v1/teams/${enc(teamId)}/proxy-tokens`, { method: 'POST', body: { provider, model: '*' } }); |
| +добавлено | if (!token?.token) throw new HttpError(502, 'backend returned no proxy token'); |
| +добавлено | const server = baseUrl(); |
| +добавлено | const previous = upsertTeamProvider({ |
| +добавлено | providerId, |
| +добавлено | providerName: p.name || `Team · ${team?.name ?? teamId.slice(0, 8)}`, |
| +добавлено | apiType: provider === 'anthropic' ? 'anthropic-messages' : 'openai-chat-completions', |
| +добавлено | baseUrl: `${server}/v1/teams/${teamId}/proxy/${provider}${provider === 'openai' ? '/v1' : ''}`, |
| +добавлено | apiKey: token.token, |
| +добавлено | models, |
| +добавлено | teamId, |
| +добавлено | tokenId: token.id, |
| +добавлено | }); |
| +добавлено | if (previous?.tokenId && previous.tokenId !== token.id) { |
| +добавлено | try { |
| +добавлено | await api(`/v1/teams/${enc(previous.teamId ?? teamId)}/proxy-tokens/${enc(previous.tokenId)}`, { method: 'DELETE' }); |
| +добавлено | } catch (err) { |
| +добавлено | log('old proxy token revoke failed', err.status ?? '', err.message); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | realtime.emitLocal('providers'); |
| +добавлено | return { providerId, models }; |
| +добавлено | }, |
| +добавлено | async disconnectTeamProvider(p) { |
| +добавлено | const providerId = need(p.providerId, 'providerId'); |
| +добавлено | if (!readSidecar().providers[providerId]) throw new HttpError(404, `${providerId} is not a team provider`); |
| +добавлено | const entry = removeTeamProvider(providerId); |
| +добавлено | if (entry?.tokenId && state.accessToken) { |
| +добавлено | try { |
| +добавлено | await api(`/v1/teams/${enc(entry.teamId)}/proxy-tokens/${enc(entry.tokenId)}`, { method: 'DELETE' }); |
| +добавлено | } catch (err) { |
| +добавлено | log('proxy token revoke failed', err.status ?? '', err.message); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | realtime.emitLocal('providers'); |
| +добавлено | return { ok: true, providerId }; |
| +добавлено | }, |
| +добавлено | |
| +добавлено | // --- файлы и архивы |
| +добавлено | files: (p) => api(`${T(p)}/files`), |
| +добавлено | downloadFile: (p) => downloadTo(`${T(p)}/files/${enc(need(p.fileId, 'fileId'))}`, { targetDir: p.targetDir, fallbackName: `file-${p.fileId}` }), |
| +добавлено | async deleteFile(p) { |
| +добавлено | await api(`${T(p)}/files/${enc(need(p.fileId, 'fileId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | archives: (p) => api(`${T(p)}/archives`), |
| +добавлено | downloadArchive: (p) => downloadTo(`${T(p)}/archives/${enc(need(p.archiveId, 'archiveId'))}`, { targetDir: p.targetDir, fallbackName: `archive-${p.archiveId}.zip` }), |
| +добавлено | async deleteArchive(p) { |
| +добавлено | await api(`${T(p)}/archives/${enc(need(p.archiveId, 'archiveId'))}`, { method: 'DELETE' }); |
| +добавлено | return { ok: true }; |
| +добавлено | }, |
| +добавлено | /** Совместимость со старой панелью: загрузка архива по локальному пути (потоково). */ |
| +добавлено | async uploadArchive(p) { |
| +добавлено | requireAuth(); |
| +добавлено | const filePath = path.resolve(need(p.filePath, 'filePath')); |
| +добавлено | if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) throw new HttpError(400, `file not found: ${filePath}`); |
| +добавлено | const qs = p.projectId ? `projectId=${enc(p.projectId)}` : `projectName=${enc(p.projectName || path.basename(filePath).replace(/\.[^.]+$/, ''))}`; |
| +добавлено | return uploadMultipart(`${T(p)}/archives?${qs}`, { filePath, fileName: path.basename(filePath) }); |
| +добавлено | }, |
| +добавлено | async revealPath(p) { |
| +добавлено | const abs = path.resolve(need(p.path, 'path')); |
| +добавлено | if (!revealAllowed(abs)) throw new HttpError(403, 'path is not inside the workspace or a file downloaded by this service'); |
| +добавлено | if (!fs.existsSync(abs)) throw new HttpError(404, 'path not found'); |
| +добавлено | const [cmd, args] = process.platform === 'win32' |
| +добавлено | ? ['explorer.exe', [`/select,${abs}`]] |
| +добавлено | : process.platform === 'darwin' ? ['open', ['-R', abs]] : ['xdg-open', [path.dirname(abs)]]; |
| +добавлено | // explorer.exe возвращает 1 даже при успехе — результат не ждём. |
| +добавлено | execFile(cmd, args, { windowsHide: false, timeout: 10_000 }, () => {}); |
| +добавлено | return { ok: true, path: abs }; |
| +добавлено | }, |
| +добавлено | |
| +добавлено | // --- git |
| +добавлено | git: async (p) => git.status(git.resolveDir(p.dir, state.workspace)), |
| +добавлено | gitLog: async (p) => git.log(git.resolveDir(p.dir, state.workspace), p), |
| +добавлено | gitShow: async (p) => git.show(git.resolveDir(p.dir, state.workspace), need(p.hash, 'hash')), |
| +добавлено | gitDiff: async (p) => git.diff(git.resolveDir(p.dir, state.workspace), p), |
| +добавлено | gitStage: gitMut((cwd, p) => git.stage(cwd, p.files)), |
| +добавлено | gitStageAll: gitMut((cwd) => git.stageAll(cwd)), |
| +добавлено | gitUnstage: gitMut((cwd, p) => git.unstage(cwd, p.files)), |
| +добавлено | gitDiscard: gitMut((cwd, p) => git.discard(cwd, p.files)), |
| +добавлено | gitCommit: gitMut(async (cwd, p) => { |
| +добавлено | const result = await git.commit(cwd, { message: p.message, amend: Boolean(p.amend) }); |
| +добавлено | let linkedTaskId = null; |
| +добавлено | const msg = String(p.message ?? ''); |
| +добавлено | if (state.accessToken && state.teamId && /(?:^|\s)#[0-9a-f-]{6,36}(?:\s|$)/i.test(msg)) { |
| +добавлено | try { |
| +добавлено | const remoteUrl = await git.getRemoteUrl(cwd); |
| +добавлено | const r = await api(`/v1/teams/${enc(state.teamId)}/commits`, { |
| +добавлено | method: 'POST', |
| +добавлено | body: { commitHash: result.hash, repositoryUrl: remoteUrl || cwd, message: msg }, |
| +добавлено | }); |
| +добавлено | linkedTaskId = r?.taskId ?? null; |
| +добавлено | } catch (err) { |
| +добавлено | log('commit link failed', err.status ?? '', err.message); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | let pushed = false; |
| +добавлено | let pushOutput = ''; |
| +добавлено | if (p.push) { |
| +добавлено | try { |
| +добавлено | pushOutput = (await git.push(cwd, {})).output; |
| +добавлено | pushed = true; |
| +добавлено | } catch (err) { |
| +добавлено | pushOutput = err.message; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { hash: result.hash, summary: result.summary, pushed, pushOutput, linkedTaskId }; |
| +добавлено | }), |
| +добавлено | gitPush: gitMut((cwd, p) => git.push(cwd, { setUpstream: Boolean(p.setUpstream) })), |
| +добавлено | gitPull: gitMut((cwd) => git.pull(cwd)), |
| +добавлено | gitFetch: gitMut((cwd) => git.fetchAll(cwd)), |
| +добавлено | gitBranches: async (p) => git.branches(git.resolveDir(p.dir, state.workspace)), |
| +добавлено | gitCheckout: gitMut((cwd, p) => git.checkout(cwd, { branch: p.branch, create: Boolean(p.create) })), |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function gitMut(fn) { |
| +добавлено | return async (p) => { |
| +добавлено | const cwd = git.resolveDir(p.dir, state.workspace); |
| +добавлено | try { |
| +добавлено | return await fn(cwd, p); |
| +добавлено | } finally { |
| +добавлено | realtime.emitLocal('git', { cwd }); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- RPC агента (плагин aura-team) |
| +добавлено | |
| +добавлено | async function agentBoard(p) { |
| +добавлено | return api(`${T(p)}/board`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const agentOps = { |
| +добавлено | async whoami(p) { |
| +добавлено | const me = await getMe(); |
| +добавлено | const teamId = p.teamId || state.teamId; |
| +добавлено | const team = (me?.teams ?? []).find((t) => t.id === teamId) ?? null; |
| +добавлено | return { |
| +добавлено | user: me?.user ? { id: me.user.id, email: me.user.email, displayName: me.user.displayName } : null, |
| +добавлено | teamId: team?.id ?? null, |
| +добавлено | teamName: team?.name ?? null, |
| +добавлено | role: team?.role ?? null, |
| +добавлено | teams: (me?.teams ?? []).map((t) => ({ id: t.id, name: t.name, role: t.role })), |
| +добавлено | workspace: state.workspace, |
| +добавлено | }; |
| +добавлено | }, |
| +добавлено | async teams() { |
| +добавлено | return ((await getMe())?.teams ?? []).map((t) => ({ id: t.id, name: t.name, role: t.role, memberCount: t.memberCount, selected: t.id === state.teamId })); |
| +добавлено | }, |
| +добавлено | async members(p) { |
| +добавлено | const board = await agentBoard(p); |
| +добавлено | return (board?.members ?? []).map((m) => ({ id: m.id, displayName: m.displayName, email: m.email, role: m.role, online: Boolean(m.online) })); |
| +добавлено | }, |
| +добавлено | async board(p) { |
| +добавлено | checkStatus(p.status); |
| +добавлено | const board = await agentBoard(p); |
| +добавлено | const members = board?.members ?? []; |
| +добавлено | let tasks = (board?.tasks ?? []).map((t) => normalizeTask(t, members)); |
| +добавлено | if (p.status) tasks = tasks.filter((t) => t.status === p.status); |
| +добавлено | return { teamId: teamIdOf(p), tasks }; |
| +добавлено | }, |
| +добавлено | async myTasks(p) { |
| +добавлено | const [me, board] = await Promise.all([getMe(), agentBoard(p)]); |
| +добавлено | const myId = me?.user?.id; |
| +добавлено | const members = board?.members ?? []; |
| +добавлено | const team = (me?.teams ?? []).find((t) => t.id === teamIdOf(p)); |
| +добавлено | const tasks = (board?.tasks ?? []) |
| +добавлено | .filter((t) => t.assigneeId === myId && (p.includeDone || t.status !== 'done')) |
| +добавлено | .map((t) => normalizeTask(t, members)); |
| +добавлено | return { teamId: teamIdOf(p), teamName: team?.name ?? null, user: me?.user?.displayName ?? null, tasks }; |
| +добавлено | }, |
| +добавлено | async getTask(p) { |
| +добавлено | const board = await agentBoard(p); |
| +добавлено | const t = resolveTaskId(board, p.taskId); |
| +добавлено | const [history, commits] = await Promise.all([ |
| +добавлено | api(`${T(p)}/tasks/${enc(t.id)}/history`).catch(() => []), |
| +добавлено | api(`${T(p)}/tasks/${enc(t.id)}/commits`).catch(() => []), |
| +добавлено | ]); |
| +добавлено | const full = normalizeTask(t, board?.members ?? []); |
| +добавлено | full.description = t.description ?? ''; |
| +добавлено | return { ...full, createdAt: t.createdAt ?? null, updatedAt: t.updatedAt ?? null, history: history ?? [], commits: commits ?? [] }; |
| +добавлено | }, |
| +добавлено | async createTask(p) { |
| +добавлено | if (typeof p.title !== 'string' || !p.title.trim()) throw new HttpError(400, 'title is required'); |
| +добавлено | checkStatus(p.status); |
| +добавлено | const [me, board] = await Promise.all([getMe(), agentBoard(p)]); |
| +добавлено | const members = board?.members ?? []; |
| +добавлено | const assignee = p.assignee ? resolveMember(members, p.assignee) : null; |
| +добавлено | const body = { |
| +добавлено | title: p.title.trim(), |
| +добавлено | ...pick(p, ['description', 'status', 'priority', 'labels', 'dueAt']), |
| +добавлено | assigneeId: assignee?.id ?? me?.user?.id, |
| +добавлено | }; |
| +добавлено | const created = await api(`${T(p)}/tasks`, { method: 'POST', body }); |
| +добавлено | pendingCache = null; |
| +добавлено | return normalizeTask(created, members); |
| +добавлено | }, |
| +добавлено | async updateTask(p) { |
| +добавлено | checkStatus(p.status); |
| +добавлено | const board = await agentBoard(p); |
| +добавлено | const members = board?.members ?? []; |
| +добавлено | const t = resolveTaskId(board, p.taskId); |
| +добавлено | const changes = pick(p, ['status', 'priority', 'title', 'description', 'labels', 'dueAt']); |
| +добавлено | if (p.assignee !== undefined) { |
| +добавлено | changes.assigneeId = p.assignee === null || p.assignee === '' || p.assignee === 'none' |
| +добавлено | ? null |
| +добавлено | : resolveMember(members, p.assignee).id; |
| +добавлено | } |
| +добавлено | if (Object.keys(changes).length === 0) throw new HttpError(400, 'nothing to update'); |
| +добавлено | const updated = await api(`${T(p)}/tasks/${enc(t.id)}`, { method: 'PATCH', body: changes }); |
| +добавлено | pendingCache = null; |
| +добавлено | return normalizeTask(updated, members); |
| +добавлено | }, |
| +добавлено | async moveTask(p) { |
| +добавлено | if (!p.status) throw new HttpError(400, 'status is required'); |
| +добавлено | return agentOps.updateTask({ teamId: p.teamId, taskId: p.taskId, status: p.status }); |
| +добавлено | }, |
| +добавлено | async activity(p) { |
| +добавлено | const limit = Math.min(Math.max(Number(p.limit) || 20, 1), 100); |
| +добавлено | const rows = (await api(`${T(p)}/activity?limit=${limit}`)) ?? []; |
| +добавлено | return rows.map((e) => ({ id: e.id, action: e.action, userName: e.userName, taskTitle: e.taskTitle ?? null, targetId: e.targetId ?? null, createdAt: e.createdAt })); |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- HTTP |
| +добавлено | |
| +добавлено | function publicState() { |
| +добавлено | const plugin = pluginState(); |
| +добавлено | return { |
| +добавлено | serverUrl: state.serverUrl, |
| +добавлено | signedIn: Boolean(state.accessToken), |
| +добавлено | teamId: state.teamId, |
| +добавлено | workspace: state.workspace, |
| +добавлено | recentWorkspaces: state.recentWorkspaces, |
| +добавлено | ui: state.ui, |
| +добавлено | theme: state.ui?.theme ?? 'zcode', |
| +добавлено | csrfToken: CSRF_TOKEN, |
| +добавлено | plugin: { installed: plugin.installed, enabled: plugin.enabled }, |
| +добавлено | ide, |
| +добавлено | realtime: realtime.status, |
| +добавлено | version: VERSION, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function applySettings(body) { |
| +добавлено | let restart = false; |
| +добавлено | if (body.serverUrl !== undefined) { |
| +добавлено | let url; |
| +добавлено | try { url = new URL(String(body.serverUrl).trim()); } catch { throw new HttpError(400, 'serverUrl must be a URL'); } |
| +добавлено | if (!/^https?:$/.test(url.protocol)) throw new HttpError(400, 'serverUrl must be http(s)'); |
| +добавлено | const next = url.toString().replace(/\/+$/, ''); |
| +добавлено | if (next !== state.serverUrl) { |
| +добавлено | state.serverUrl = next; |
| +добавлено | invalidateCaches(); |
| +добавлено | restart = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (body.teamId !== undefined) { |
| +добавлено | if (body.teamId !== null && typeof body.teamId !== 'string') throw new HttpError(400, 'teamId must be a string or null'); |
| +добавлено | if ((body.teamId || null) !== state.teamId) { |
| +добавлено | state.teamId = body.teamId || null; |
| +добавлено | pendingCache = null; |
| +добавлено | restart = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (body.workspace !== undefined) { |
| +добавлено | if (body.workspace === null || body.workspace === '') { |
| +добавлено | state.workspace = null; |
| +добавлено | } else if (typeof body.workspace === 'string') { |
| +добавлено | state.workspace = body.workspace.trim(); |
| +добавлено | pushRecent(state, state.workspace); |
| +добавлено | } else { |
| +добавлено | throw new HttpError(400, 'workspace must be a string or null'); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (body.ui !== undefined) { |
| +добавлено | if (!body.ui || typeof body.ui !== 'object' || Array.isArray(body.ui)) throw new HttpError(400, 'ui must be an object'); |
| +добавлено | if (JSON.stringify(body.ui).length > 64 * 1024) throw new HttpError(413, 'ui is too large (max 64 KB)'); |
| +добавлено | state.ui = body.ui; |
| +добавлено | } |
| +добавлено | if (typeof body.theme === 'string') state.ui = { ...state.ui, theme: body.theme }; |
| +добавлено | saveState(); |
| +добавлено | if (restart) realtime.restart(); |
| +добавлено | realtime.emitLocal('state'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function allowedHosts() { |
| +добавлено | return new Set([`127.0.0.1:${port}`, `localhost:${port}`, '127.0.0.1', 'localhost']); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function allowedOrigins() { |
| +добавлено | return new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/; |
| +добавлено | |
| +добавлено | function errorStatus(err) { |
| +добавлено | if (err instanceof HttpError || typeof err?.status === 'number') return err.status; |
| +добавлено | if (err?.name === 'TimeoutError') return 504; |
| +добавлено | if (err?.name === 'TypeError' && /fetch failed/i.test(err.message)) return 502; |
| +добавлено | return 500; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function errorMessage(err) { |
| +добавлено | if (err?.name === 'TypeError' && /fetch failed/i.test(err.message)) { |
| +добавлено | return `backend unreachable: ${err.cause?.code ?? err.cause?.message ?? err.message}`; |
| +добавлено | } |
| +добавлено | return String(err?.message ?? err); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function handle(req, res) { |
| +добавлено | const url = new URL(req.url, `http://127.0.0.1:${port}`); |
| +добавлено | const p = url.pathname.replace(/\/+$/, '') || '/'; |
| +добавлено | const method = req.method; |
| +добавлено | const origin = req.headers.origin; |
| +добавлено | const ORIGINS = allowedOrigins(); |
| +добавлено | const sameOrigin = origin !== undefined && ORIGINS.has(origin); |
| +добавлено | |
| +добавлено | // DNS rebinding: отвечаем только под своим именем. |
| +добавлено | if (!allowedHosts().has(req.headers.host)) return sendJson(res, 403, { error: 'forbidden host' }); |
| +добавлено | |
| +добавлено | // --- read-only эндпоинты для рендерера ZCode (CORS *) |
| +добавлено | if (method === 'GET' && (p === '/plugin-state' || p === '/notify/pending')) { |
| +добавлено | const cors = { 'Access-Control-Allow-Origin': '*' }; |
| +добавлено | if (p === '/plugin-state') { |
| +добавлено | const plugin = pluginState(); |
| +добавлено | if (plugin.enabled) realtime.notePluginPoll(); |
| +добавлено | let pending = 0; |
| +добавлено | if (plugin.enabled) { |
| +добавлено | try { pending = await pendingCount(); } catch { pending = 0; } |
| +добавлено | } |
| +добавлено | return sendJson(res, 200, { installed: plugin.installed, enabled: plugin.enabled, signedIn: Boolean(state.accessToken), pending }, cors); |
| +добавлено | } |
| +добавлено | let count = 0; |
| +добавлено | try { count = await pendingCount(); } catch { count = 0; } |
| +добавлено | return sendJson(res, 200, { count }, cors); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- API агента: только с токеном, без Origin (браузер его всегда шлёт на POST) |
| +добавлено | if (p === '/agent/rpc') { |
| +добавлено | if (method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' }); |
| +добавлено | if (origin !== undefined) return sendJson(res, 403, { error: 'origin not allowed' }); |
| +добавлено | if (!safeEqual(req.headers['x-zteam-agent'], agentToken)) return sendJson(res, 401, { error: 'agent token missing or invalid' }); |
| +добавлено | try { |
| +добавлено | const body = await readJson(req, MAX_BODY_BYTES); |
| +добавлено | const fn = Object.hasOwn(agentOps, body.method) ? agentOps[body.method] : null; |
| +добавлено | if (!fn) return sendJson(res, 404, { error: `unknown method ${body.method}` }); |
| +добавлено | const params = body.params && typeof body.params === 'object' ? body.params : {}; |
| +добавлено | return sendJson(res, 200, { ok: true, result: await fn(params) }); |
| +добавлено | } catch (err) { |
| +добавлено | return sendError(res, err); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Чужой Origin не допускается нигде дальше. |
| +добавлено | if (origin !== undefined && !sameOrigin) return sendJson(res, 403, { error: 'origin not allowed' }); |
| +добавлено | |
| +добавлено | if (method === 'OPTIONS') { |
| +добавлено | if (!sameOrigin) return sendJson(res, 403, { error: 'origin not allowed' }); |
| +добавлено | res.writeHead(204, { |
| +добавлено | 'Access-Control-Allow-Origin': origin, |
| +добавлено | 'Access-Control-Allow-Headers': 'Content-Type, X-ZTeam-CSRF, X-File-Name', |
| +добавлено | 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS', |
| +добавлено | 'Access-Control-Max-Age': '600', |
| +добавлено | Vary: 'Origin', |
| +добавлено | }); |
| +добавлено | return res.end(); |
| +добавлено | } |
| +добавлено | if (sameOrigin) { |
| +добавлено | res.setHeader('Access-Control-Allow-Origin', origin); |
| +добавлено | res.setHeader('Vary', 'Origin'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- контекст IDE от хука плагина: токен агента вместо CSRF |
| +добавлено | if (p === '/ide/context') { |
| +добавлено | if (method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' }); |
| +добавлено | if (!safeEqual(req.headers['x-zteam-agent'], agentToken)) return sendJson(res, 401, { error: 'agent token missing or invalid' }); |
| +добавлено | try { |
| +добавлено | const body = await readJson(req, MAX_BODY_BYTES); |
| +добавлено | if (typeof body.cwd !== 'string' || !body.cwd.trim()) throw new HttpError(400, 'cwd is required'); |
| +добавлено | const cwd = path.resolve(body.cwd.trim()); |
| +добавлено | if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new HttpError(400, 'cwd is not a directory'); |
| +добавлено | const branch = await git.currentBranch(cwd); |
| +добавлено | ide = { |
| +добавлено | cwd, |
| +добавлено | branch, |
| +добавлено | event: typeof body.event === 'string' ? body.event.slice(0, 64) : null, |
| +добавлено | sessionId: typeof body.sessionId === 'string' ? body.sessionId.slice(0, 128) : null, |
| +добавлено | at: new Date().toISOString(), |
| +добавлено | }; |
| +добавлено | if (!state.workspace) { |
| +добавлено | state.workspace = cwd; |
| +добавлено | pushRecent(state, cwd); |
| +добавлено | saveState(); |
| +добавлено | realtime.emitLocal('state'); |
| +добавлено | } |
| +добавлено | realtime.emitLocal('ide', { ide }); |
| +добавлено | return sendJson(res, 200, { ok: true, workspace: state.workspace, teamId: state.teamId, signedIn: Boolean(state.accessToken) }); |
| +добавлено | } catch (err) { |
| +добавлено | return sendError(res, err); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // CSRF: любой прочий POST обязан нести токен из /state. |
| +добавлено | if (method === 'POST' && !safeEqual(req.headers['x-zteam-csrf'], CSRF_TOKEN)) { |
| +добавлено | req.resume(); |
| +добавлено | return sendJson(res, 403, { error: 'csrf token missing or invalid' }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | try { |
| +добавлено | if (method === 'GET' && (p === '/panel' || p === '/')) { |
| +добавлено | const html = fs.readFileSync(paths.panel); |
| +добавлено | res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Length': html.length }); |
| +добавлено | return res.end(html); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (method === 'GET' && p.startsWith('/panel/assets/')) { |
| +добавлено | const name = decodeURIComponent(p.slice('/panel/assets/'.length)); |
| +добавлено | if (!ASSET_NAME.test(name)) return sendJson(res, 400, { error: 'invalid asset name' }); |
| +добавлено | const file = path.join(paths.assets, name); |
| +добавлено | let st; |
| +добавлено | try { st = fs.statSync(file); } catch { return sendJson(res, 404, { error: 'asset not found' }); } |
| +добавлено | if (!st.isFile()) return sendJson(res, 404, { error: 'asset not found' }); |
| +добавлено | res.writeHead(200, { 'Content-Type': contentTypeFor(name), 'Content-Length': st.size, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' }); |
| +добавлено | return fs.createReadStream(file).pipe(res); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (method === 'GET' && p === '/state') return sendJson(res, 200, publicState()); |
| +добавлено | |
| +добавлено | if (method === 'GET' && p === '/events') { |
| +добавлено | const site = req.headers['sec-fetch-site']; |
| +добавлено | if (site && site !== 'same-origin' && site !== 'none') return sendJson(res, 403, { error: 'same-origin only' }); |
| +добавлено | return realtime.addClient(req, res); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (method === 'POST' && p === '/settings') { |
| +добавлено | await applySettings(await readJson(req, MAX_BODY_BYTES)); |
| +добавлено | return sendJson(res, 200, { ok: true, ...publicState() }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (method === 'POST' && p === '/rpc') { |
| +добавлено | const body = await readJson(req, MAX_BODY_BYTES); |
| +добавлено | const fn = Object.hasOwn(ops, body.method) ? ops[body.method] : null; |
| +добавлено | if (!fn) return sendJson(res, 404, { error: `unknown method ${body.method}` }); |
| +добавлено | const params = body.params && typeof body.params === 'object' ? body.params : {}; |
| +добавлено | return sendJson(res, 200, { ok: true, result: await fn(params) }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (method === 'POST' && p === '/upload') return await handleUpload(req, res, url); |
| +добавлено | |
| +добавлено | return sendJson(res, 404, { error: `unknown route ${method} ${p}` }); |
| +добавлено | } catch (err) { |
| +добавлено | return sendError(res, err); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function handleUpload(req, res, url) { |
| +добавлено | const q = url.searchParams; |
| +добавлено | const kind = q.get('kind') || 'file'; |
| +добавлено | if (kind !== 'file' && kind !== 'archive') throw new HttpError(400, "kind must be 'file' or 'archive'"); |
| +добавлено | requireAuth(); |
| +добавлено | const teamId = teamIdOf({ teamId: q.get('teamId') || undefined }); |
| +добавлено | let rawName = req.headers['x-file-name']; |
| +добавлено | if (typeof rawName !== 'string' || !rawName) throw new HttpError(400, 'X-File-Name header is required'); |
| +добавлено | try { rawName = decodeURIComponent(rawName); } catch { throw new HttpError(400, 'X-File-Name must be encodeURIComponent-encoded'); } |
| +добавлено | const fileName = sanitizeFileName(rawName); |
| +добавлено | fs.mkdirSync(paths.tmp, { recursive: true }); |
| +добавлено | const tmp = path.join(paths.tmp, `upload-${process.pid}-${crypto.randomBytes(8).toString('hex')}`); |
| +добавлено | try { |
| +добавлено | const bytes = await receiveToFile(req, tmp, MAX_UPLOAD_BYTES); |
| +добавлено | if (bytes === 0) throw new HttpError(400, 'empty file'); |
| +добавлено | let target; |
| +добавлено | if (kind === 'file') { |
| +добавлено | const qs = new URLSearchParams(); |
| +добавлено | if (q.get('recipientId')) qs.set('recipientId', q.get('recipientId')); |
| +добавлено | if (q.get('note')) qs.set('note', q.get('note')); |
| +добавлено | target = `/v1/teams/${enc(teamId)}/files${qs.size ? `?${qs}` : ''}`; |
| +добавлено | } else { |
| +добавлено | const qs = new URLSearchParams(); |
| +добавлено | if (q.get('projectId')) qs.set('projectId', q.get('projectId')); |
| +добавлено | else qs.set('projectName', q.get('projectName') || fileName.replace(/\.[^.]+$/, '') || fileName); |
| +добавлено | target = `/v1/teams/${enc(teamId)}/archives?${qs}`; |
| +добавлено | } |
| +добавлено | const result = await uploadMultipart(target, { filePath: tmp, fileName }); |
| +добавлено | log(`uploaded ${kind} ${fileName} (${Math.round(bytes / 1024)} KiB)`); |
| +добавлено | return sendJson(res, 200, result ?? { ok: true }); |
| +добавлено | } finally { |
| +добавлено | fs.rm(tmp, { force: true }, () => {}); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function sendError(res, err) { |
| +добавлено | const status = errorStatus(err); |
| +добавлено | if (status >= 500) log('error', status, errorMessage(err)); |
| +добавлено | if (res.headersSent) { |
| +добавлено | try { res.end(); } catch { /* */ } |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const headers = status === 413 ? { Connection: 'close' } : {}; |
| +добавлено | return sendJson(res, status, { error: errorMessage(err), body: err?.body ?? null }, headers); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- запуск |
| +добавлено | |
| +добавлено | const server = http.createServer((req, res) => { |
| +добавлено | handle(req, res).catch((err) => sendError(res, err)); |
| +добавлено | }); |
| +добавлено | server.requestTimeout = 0; // загрузки до 1 ГиБ не должны обрываться таймаутом запроса |
| +добавлено | server.headersTimeout = 60_000; |
| +добавлено | |
| +добавлено | server.on('error', (err) => { |
| +добавлено | if (err.code === 'EADDRINUSE') { |
| +добавлено | log(`port ${port} busy — already running`); |
| +добавлено | process.exit(0); |
| +добавлено | } |
| +добавлено | log('server error', err); |
| +добавлено | process.exit(1); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | await ensureLocalServer(); |
| +добавлено | |
| +добавлено | server.listen(PORT, '127.0.0.1', () => { |
| +добавлено | port = server.address().port; |
| +добавлено | try { |
| +добавлено | agentToken = ensureAgentFile(port); |
| +добавлено | } catch (err) { |
| +добавлено | log('agent file write failed', err.message); |
| +добавлено | agentToken = crypto.randomBytes(32).toString('hex'); |
| +добавлено | } |
| +добавлено | log(`listening http://127.0.0.1:${port}/panel`); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | const shutdown = () => { |
| +добавлено | realtime.close(); |
| +добавлено | server.close(); |
| +добавлено | try { localServerProcess?.kill(); } catch { /* уже завершён */ } |
| +добавлено | setTimeout(() => process.exit(0), 300).unref(); |
| +добавлено | }; |
| +добавлено | process.on('SIGTERM', shutdown); |
| +добавлено | process.on('SIGINT', shutdown); |
| +добавлено | // Интеграционные тесты сервиса Aura Team (server.mjs) и плагина aura-team. |
| +добавлено | // Поднимают фейковый бэкенд на случайном порту и сервис на ZTEAM_TEST_PORT (по умолчанию 8791) |
| +добавлено | // с временными state / provider_config / config.json — живой экземпляр на 8790 не трогается. |
| +добавлено | // |
| +добавлено | // Запуск: node --test fork/team/test/ |
| +добавлено | |
| +добавлено | import { test, before, after } from 'node:test'; |
| +добавлено | import assert from 'node:assert/strict'; |
| +добавлено | import http from 'node:http'; |
| +добавлено | import crypto from 'node:crypto'; |
| +добавлено | import fs from 'node:fs'; |
| +добавлено | import os from 'node:os'; |
| +добавлено | import path from 'node:path'; |
| +добавлено | import { spawn, execFileSync } from 'node:child_process'; |
| +добавлено | import { fileURLToPath } from 'node:url'; |
| +добавлено | |
| +добавлено | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| +добавлено | const SERVICE = path.resolve(HERE, '..', 'server.mjs'); |
| +добавлено | const PLUGIN_SCRIPTS = path.resolve(HERE, '..', '..', 'marketplace', 'plugins', 'aura-team', 'scripts'); |
| +добавлено | const PORT = Number(process.env.ZTEAM_TEST_PORT || 8791); |
| +добавлено | const SVC = `http://127.0.0.1:${PORT}`; |
| +добавлено | const ORIGIN = SVC; |
| +добавлено | |
| +добавлено | const TEAM = '7e4c1a90-1111-4222-8333-944455556666'; |
| +добавлено | const ME = { id: 'u1-ivan', email: 'ivan@example.com', displayName: 'Ivan' }; |
| +добавлено | const PETR = { id: 'u2-petr', email: 'petr@example.com', displayName: 'Petr' }; |
| +добавлено | const LOCAL_KEY = 'sk-local-secret-ABCDEFGH1234'; |
| +добавлено | const POOL_KEY = 'sk-pool-secret-ZYXWVUTS9876'; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- фейковый бэкенд |
| +добавлено | |
| +добавлено | const fake = { |
| +добавлено | tasks: [], |
| +добавлено | keys: [], |
| +добавлено | proxyTokens: [], |
| +добавлено | revoked: [], |
| +добавлено | commits: [], |
| +добавлено | uploads: [], |
| +добавлено | password: 'secret-pass', |
| +добавлено | requests: [], |
| +добавлено | }; |
| +добавлено | |
| +добавлено | function seedTasks() { |
| +добавлено | fake.tasks = [ |
| +добавлено | { id: '1a2b3c4d-0000-4000-8000-000000000001', title: 'Сделать вход', description: 'OAuth', status: 'doing', assigneeId: ME.id, assigneeName: ME.displayName, priority: 'high', labels: ['auth'], dueAt: '2026-11-20', position: 0 }, |
| +добавлено | { id: '5e6f7a8b-0000-4000-8000-000000000002', title: 'Ревью API', description: '', status: 'todo', assigneeId: PETR.id, assigneeName: PETR.displayName, priority: 'normal', labels: [], dueAt: null, position: 0 }, |
| +добавлено | { id: '9c0d1e2f-0000-4000-8000-000000000003', title: 'Старое', description: '', status: 'done', assigneeId: ME.id, assigneeName: ME.displayName, priority: 'low', labels: [], dueAt: null, position: 0 }, |
| +добавлено | ]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const backend = http.createServer(async (req, res) => { |
| +добавлено | const url = new URL(req.url, 'http://x'); |
| +добавлено | const p = url.pathname; |
| +добавлено | const send = (code, obj) => { |
| +добавлено | const body = obj === undefined ? '' : JSON.stringify(obj); |
| +добавлено | res.writeHead(code, body ? { 'content-type': 'application/json' } : {}); |
| +добавлено | res.end(body); |
| +добавлено | }; |
| +добавлено | const chunks = []; |
| +добавлено | for await (const c of req) chunks.push(c); |
| +добавлено | const rawBody = Buffer.concat(chunks); |
| +добавлено | fake.requests.push({ method: req.method, path: p }); |
| +добавлено | const json = () => { try { return JSON.parse(rawBody.toString('utf8') || '{}'); } catch { return {}; } }; |
| +добавлено | const authed = req.headers.authorization === 'Bearer access-1'; |
| +добавлено | |
| +добавлено | if (req.method === 'POST' && p === '/v1/auth/login') { |
| +добавлено | const b = json(); |
| +добавлено | if (b.email === ME.email && b.password === fake.password) return send(200, { accessToken: 'access-1', refreshToken: 'refresh-1', expiresIn: 900 }); |
| +добавлено | return send(401, { message: 'Invalid email or password' }); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && p === '/v1/auth/refresh') return send(401, { message: 'Unauthorized' }); |
| +добавлено | if (!authed) return send(401, { message: 'Authentication required' }); |
| +добавлено | |
| +добавлено | const base = `/v1/teams/${TEAM}`; |
| +добавлено | if (req.method === 'GET' && p === '/v1/me') { |
| +добавлено | return send(200, { user: ME, teams: [{ id: TEAM, name: 'Alpha', role: 'owner', memberCount: 2 }], entitlements: [], admin: false }); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && p === '/v1/auth/password') { |
| +добавлено | const b = json(); |
| +добавлено | if (b.currentPassword !== fake.password) return send(401, { message: 'Current password is incorrect' }); |
| +добавлено | fake.password = b.newPassword; |
| +добавлено | return send(200, { ok: true }); |
| +добавлено | } |
| +добавлено | if (req.method === 'GET' && p === `${base}/board`) { |
| +добавлено | return send(200, { members: [{ ...ME, role: 'owner' }, { ...PETR, role: 'dev' }], projects: [], tasks: fake.tasks }); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && p === `${base}/tasks`) { |
| +добавлено | const b = json(); |
| +добавлено | const assignee = [ME, PETR].find((m) => m.id === (b.assigneeId ?? ME.id)); |
| +добавлено | const t = { id: crypto.randomUUID(), title: b.title, description: b.description ?? '', status: b.status ?? 'todo', assigneeId: assignee?.id ?? null, priority: b.priority ?? 'normal', labels: b.labels ?? [], due_at: b.dueAt ?? null, position: 0 }; |
| +добавлено | fake.tasks.push({ ...t, assigneeName: assignee?.displayName, dueAt: t.due_at }); |
| +добавлено | // Как настоящий taskResponse: snake_case поля строки + camelCase |
| +добавлено | return send(201, { ...t, assignee_id: t.assigneeId, labels: t.labels }); |
| +добавлено | } |
| +добавлено | let m = new RegExp(`^${base}/tasks/([^/]+)$`).exec(p); |
| +добавлено | if (m && req.method === 'PATCH') { |
| +добавлено | const t = fake.tasks.find((x) => x.id === m[1]); |
| +добавлено | if (!t) return send(404, { message: 'Not Found' }); |
| +добавлено | const b = json(); |
| +добавлено | Object.assign(t, b); |
| +добавлено | if ('assigneeId' in b) t.assigneeName = [ME, PETR].find((x) => x.id === b.assigneeId)?.displayName ?? null; |
| +добавлено | return send(200, { ...t }); |
| +добавлено | } |
| +добавлено | m = new RegExp(`^${base}/tasks/([^/]+)/(history|commits)$`).exec(p); |
| +добавлено | if (m && req.method === 'GET') { |
| +добавлено | return send(200, m[2] === 'history' ? [{ action: 'task.create', details: {}, createdAt: '2026-11-10T10:00:00.000Z', userName: 'Ivan' }] : []); |
| +добавлено | } |
| +добавлено | if (req.method === 'GET' && p === `${base}/activity`) { |
| +добавлено | return send(200, [{ id: 1, action: 'task.create', userName: 'Ivan', taskTitle: 'Сделать вход', createdAt: '2026-11-10T10:00:00.000Z' }]); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && p === `${base}/proxy-tokens`) { |
| +добавлено | const tok = { id: crypto.randomUUID(), token: `aura_pt_${crypto.randomBytes(8).toString('hex')}`, body: json() }; |
| +добавлено | fake.proxyTokens.push(tok); |
| +добавлено | return send(201, { id: tok.id, token: tok.token }); |
| +добавлено | } |
| +добавлено | m = new RegExp(`^${base}/proxy-tokens/([^/]+)$`).exec(p); |
| +добавлено | if (m && req.method === 'DELETE') { |
| +добавлено | fake.revoked.push(m[1]); |
| +добавлено | return send(204); |
| +добавлено | } |
| +добавлено | if (req.method === 'GET' && p === `${base}/keys`) return send(200, fake.keys.map(({ value, ...k }) => k)); |
| +добавлено | if (req.method === 'POST' && p === `${base}/keys`) { |
| +добавлено | const b = json(); |
| +добавлено | const k = b.value.trim(); |
| +добавлено | const key = { id: crypto.randomUUID(), ...b, keyHint: k.length <= 8 ? '••••' : `${k.slice(0, 3)}…${k.slice(-4)}` }; |
| +добавлено | fake.keys.push(key); |
| +добавлено | const { value, ...pub } = key; |
| +добавлено | return send(201, pub); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && p === `${base}/events-ticket`) return send(200, { ticket: 'tkt', expiresIn: 30 }); |
| +добавлено | if (req.method === 'POST' && p === `${base}/commits`) { |
| +добавлено | fake.commits.push(json()); |
| +добавлено | return send(201, { taskId: fake.tasks[0].id }); |
| +добавлено | } |
| +добавлено | if (req.method === 'POST' && (p === `${base}/files` || p === `${base}/archives`)) { |
| +добавлено | const ct = req.headers['content-type'] ?? ''; |
| +добавлено | const boundary = /boundary=(.+)$/.exec(ct)?.[1]; |
| +добавлено | if (!boundary) return send(400, { message: 'no boundary' }); |
| +добавлено | const headEnd = rawBody.indexOf('\r\n\r\n'); |
| +добавлено | const head = rawBody.subarray(0, headEnd).toString('utf8'); |
| +добавлено | const tail = Buffer.from(`\r\n--${boundary}--\r\n`); |
| +добавлено | if (!rawBody.subarray(rawBody.length - tail.length).equals(tail)) return send(400, { message: 'bad tail' }); |
| +добавлено | const content = rawBody.subarray(headEnd + 4, rawBody.length - tail.length); |
| +добавлено | const plain = /filename="([^"\r\n]*)"/.exec(head); |
| +добавлено | const up = { |
| +добавлено | kind: p.endsWith('/files') ? 'file' : 'archive', |
| +добавлено | query: Object.fromEntries(url.searchParams), |
| +добавлено | name: plain ? plain[1] : null, |
| +добавлено | bytes: content.length, |
| +добавлено | sha256: crypto.createHash('sha256').update(content).digest('hex'), |
| +добавлено | contentLength: Number(req.headers['content-length']), |
| +добавлено | received: rawBody.length, |
| +добавлено | }; |
| +добавлено | fake.uploads.push(up); |
| +добавлено | return send(201, { id: crypto.randomUUID(), ...up }); |
| +добавлено | } |
| +добавлено | return send(404, { message: `fake: no route ${req.method} ${p}` }); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // Минимальный WebSocket-эндпоинт бэкенда: рукопожатие + два текстовых кадра. |
| +добавлено | fake.ws = []; |
| +добавлено | backend.on('upgrade', (req, socket) => { |
| +добавлено | const url = new URL(req.url, 'http://x'); |
| +добавлено | if (url.pathname !== `/v1/teams/${TEAM}/events` || url.searchParams.get('ticket') !== 'tkt') { |
| +добавлено | socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n'); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const accept = crypto.createHash('sha1').update(`${req.headers['sec-websocket-key']}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64'); |
| +добавлено | socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); |
| +добавлено | socket.on('error', () => {}); |
| +добавлено | socket.on('data', () => {}); |
| +добавлено | fake.ws.push(socket); |
| +добавлено | const frame = (obj) => { |
| +добавлено | const payload = Buffer.from(JSON.stringify(obj)); |
| +добавлено | socket.write(Buffer.concat([Buffer.from([0x81, payload.length]), payload])); |
| +добавлено | }; |
| +добавлено | frame({ type: 'connected', at: new Date().toISOString() }); |
| +добавлено | setTimeout(() => frame({ type: 'task.changed', at: '2026-11-11T12:00:00.000Z' }), 100); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- окружение |
| +добавлено | |
| +добавлено | let tmp; |
| +добавлено | let backendUrl; |
| +добавлено | let svc; |
| +добавлено | let svcLog = ''; |
| +добавлено | let csrf; |
| +добавлено | const env = {}; |
| +добавлено | |
| +добавлено | function writeJson(file, value) { |
| +добавлено | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| +добавлено | fs.writeFileSync(file, JSON.stringify(value, null, 2)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8')); |
| +добавлено | |
| +добавлено | function providerDoc() { |
| +добавлено | return { |
| +добавлено | schemaVersion: 1, |
| +добавлено | config: { |
| +добавлено | providerOrder: ['local-openai', 'local-claude'], |
| +добавлено | providerConfigRules: { |
| +добавлено | providerRules: [ |
| +добавлено | { |
| +добавлено | providerId: 'local-openai', |
| +добавлено | providerName: 'Local GW', |
| +добавлено | enabled: true, |
| +добавлено | config: { |
| +добавлено | group: 'standard-personal', |
| +добавлено | access: { type: 'api-key', apiKey: LOCAL_KEY }, |
| +добавлено | api: { type: 'openai-chat-completions', baseUrl: 'https://gw.example.com/v1' }, |
| +добавлено | personalModelIds: ['gpt-x', 'gpt-y'], |
| +добавлено | modelOrder: ['gpt-y', 'gpt-x'], |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { |
| +добавлено | providerId: 'local-claude', |
| +добавлено | providerName: 'Claude', |
| +добавлено | config: { |
| +добавлено | group: 'standard-personal', |
| +добавлено | access: { type: 'api-key', apiKey: 'sk-ant-another-secret-0000' }, |
| +добавлено | api: { type: 'anthropic-messages', baseUrl: 'https://api.anthropic.com' }, |
| +добавлено | personalModelIds: ['claude-z'], |
| +добавлено | modelOrder: [], |
| +добавлено | }, |
| +добавлено | }, |
| +добавлено | { providerId: 'empty', providerName: 'Empty', config: { group: 'standard-personal', access: { type: 'api-key' }, personalModelIds: [], modelOrder: [] } }, |
| +добавлено | ], |
| +добавлено | }, |
| +добавлено | modelConfigRules: { |
| +добавлено | providerModelRules: [ |
| +добавлено | { modelId: 'gpt-x', config: { enabled: true, properties: { inputFormat: { supportsText: true, supportsImage: true } } }, providerId: 'local-openai' }, |
| +добавлено | ], |
| +добавлено | manualProviderModelRules: [], |
| +добавлено | }, |
| +добавлено | defaultModelSelection: { providerId: 'local-openai', modelId: 'gpt-y' }, |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function waitFor(fn, ms = 10_000) { |
| +добавлено | const end = Date.now() + ms; |
| +добавлено | let last; |
| +добавлено | while (Date.now() < end) { |
| +добавлено | try { |
| +добавлено | const v = await fn(); |
| +добавлено | if (v) return v; |
| +добавлено | } catch (err) { last = err; } |
| +добавлено | await new Promise((r) => setTimeout(r, 100)); |
| +добавлено | } |
| +добавлено | throw new Error(`timeout waiting: ${last?.message ?? ''}\n--- service log ---\n${svcLog}`); |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function rpc(method, params = {}, { headers = {} } = {}) { |
| +добавлено | const res = await fetch(`${SVC}/rpc`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', 'x-zteam-csrf': csrf, origin: ORIGIN, ...headers }, |
| +добавлено | body: JSON.stringify({ method, params }), |
| +добавлено | }); |
| +добавлено | const body = await res.json(); |
| +добавлено | return { status: res.status, body, result: body.result }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | async function agent(method, params = {}, token) { |
| +добавлено | const res = await fetch(`${SVC}/agent/rpc`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', ...(token ? { 'x-zteam-agent': token } : {}) }, |
| +добавлено | body: JSON.stringify({ method, params }), |
| +добавлено | }); |
| +добавлено | return { status: res.status, body: await res.json() }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function git(cwd, ...args) { |
| +добавлено | return execFileSync('git', args, { cwd, encoding: 'utf8', windowsHide: true }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | before(async () => { |
| +добавлено | tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'zteam-test-')); |
| +добавлено | seedTasks(); |
| +добавлено | await new Promise((r) => backend.listen(0, '127.0.0.1', r)); |
| +добавлено | backendUrl = `http://127.0.0.1:${backend.address().port}`; |
| +добавлено | |
| +добавлено | const cli = path.join(tmp, 'home', '.zcode', 'cli'); |
| +добавлено | writeJson(path.join(cli, 'config.json'), { plugins: { enabled: true, enabledPlugins: { 'aura-team@local-marketplace': true } } }); |
| +добавлено | writeJson(path.join(cli, 'plugins', 'installed_plugins.json'), { version: 1, plugins: [{ id: 'aura-team@local-marketplace', name: 'aura-team', marketplace: 'local-marketplace', version: '1.0.0' }] }); |
| +добавлено | writeJson(path.join(tmp, 'v2', 'provider_config.json'), providerDoc()); |
| +добавлено | writeJson(path.join(tmp, 'v2', 'key_pool.json'), { version: 1, providers: { 'local-openai': { keys: [POOL_KEY, LOCAL_KEY], tiers: {} } } }); |
| +добавлено | |
| +добавлено | Object.assign(env, { |
| +добавлено | ZTEAM_PORT: String(PORT), |
| +добавлено | ZTEAM_STATE_DIR: path.join(tmp, 'state'), |
| +добавлено | ZTEAM_ZCODE_HOME: cli, |
| +добавлено | ZTEAM_PROVIDER_CONFIG: path.join(tmp, 'v2', 'provider_config.json'), |
| +добавлено | ZTEAM_AGENT_FILE: path.join(tmp, 'aura-team', 'agent.json'), |
| +добавлено | ZTEAM_SERVER_URL: backendUrl, |
| +добавлено | }); |
| +добавлено | svc = spawn(process.execPath, [SERVICE], { env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }); |
| +добавлено | svc.stdout.on('data', (d) => { svcLog += d; }); |
| +добавлено | svc.stderr.on('data', (d) => { svcLog += d; }); |
| +добавлено | const st = await waitFor(async () => { |
| +добавлено | const r = await fetch(`${SVC}/state`); |
| +добавлено | return r.ok ? r.json() : null; |
| +добавлено | }); |
| +добавлено | csrf = st.csrfToken; |
| +добавлено | await waitFor(() => fs.existsSync(env.ZTEAM_AGENT_FILE)); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | after(async () => { |
| +добавлено | if (svc && svc.exitCode === null) { |
| +добавлено | svc.kill(); |
| +добавлено | await new Promise((r) => { svc.once('exit', r); setTimeout(r, 2000); }); |
| +добавлено | } |
| +добавлено | backend.closeAllConnections?.(); |
| +добавлено | for (const s of fake.ws ?? []) s.destroy(); |
| +добавлено | await new Promise((r) => backend.close(r)); |
| +добавлено | try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* Windows может держать файлы */ } |
| +добавлено | }); |
| +добавлено | |
| +добавлено | const agentToken = () => readJson(env.ZTEAM_AGENT_FILE).token; |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- тесты |
| +добавлено | |
| +добавлено | test('GET /state: shape, version 2, plugin state', async () => { |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.equal(st.version, '2'); |
| +добавлено | assert.equal(st.signedIn, false); |
| +добавлено | assert.equal(st.serverUrl, backendUrl); |
| +добавлено | assert.deepEqual(st.recentWorkspaces, []); |
| +добавлено | assert.deepEqual(st.ui, {}); |
| +добавлено | assert.deepEqual(st.plugin, { installed: true, enabled: true }); |
| +добавлено | assert.equal(st.ide, null); |
| +добавлено | assert.match(st.csrfToken, /^[0-9a-f]{48}$/); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('agent.json written with port, token, serviceDir', () => { |
| +добавлено | const a = readJson(env.ZTEAM_AGENT_FILE); |
| +добавлено | assert.equal(a.port, PORT); |
| +добавлено | assert.match(a.token, /^[0-9a-f]{64}$/); |
| +добавлено | assert.equal(path.resolve(a.serviceDir), path.dirname(SERVICE)); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('CSRF: POST /rpc without or with a wrong token is rejected', async () => { |
| +добавлено | const noToken = await fetch(`${SVC}/rpc`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"method":"teams"}' }); |
| +добавлено | assert.equal(noToken.status, 403); |
| +добавлено | assert.match((await noToken.json()).error, /csrf/); |
| +добавлено | const wrong = await rpc('teams', {}, { headers: { 'x-zteam-csrf': 'nope' } }); |
| +добавлено | assert.equal(wrong.status, 403); |
| +добавлено | const settings = await fetch(`${SVC}/settings`, { method: 'POST', body: '{"workspace":"x"}' }); |
| +добавлено | assert.equal(settings.status, 403); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('foreign Origin and Host are rejected even with a valid CSRF token', async () => { |
| +добавлено | const r = await rpc('teams', {}, { headers: { origin: 'http://evil.example' } }); |
| +добавлено | assert.equal(r.status, 403); |
| +добавлено | assert.match(r.body.error, /origin/); |
| +добавлено | const pre = await fetch(`${SVC}/rpc`, { method: 'OPTIONS', headers: { origin: 'http://evil.example' } }); |
| +добавлено | assert.equal(pre.status, 403); |
| +добавлено | const host = await new Promise((resolve) => { |
| +добавлено | http.get({ host: '127.0.0.1', port: PORT, path: '/state', headers: { host: 'evil.example' } }, (res) => { res.resume(); resolve(res.statusCode); }); |
| +добавлено | }); |
| +добавлено | assert.equal(host, 403); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('unknown method → 404; not signed in → 401 from upstream semantics', async () => { |
| +добавлено | assert.equal((await rpc('nope')).status, 404); |
| +добавлено | const s = await rpc('session'); |
| +добавлено | assert.equal(s.status, 401); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('login → session → teams → selectTeam', async () => { |
| +добавлено | const bad = await rpc('login', { email: ME.email, password: 'wrong' }); |
| +добавлено | assert.equal(bad.status, 401); |
| +добавлено | const ok = await rpc('login', { email: ME.email, password: fake.password }); |
| +добавлено | assert.equal(ok.status, 200, JSON.stringify(ok.body)); |
| +добавлено | const session = await rpc('session'); |
| +добавлено | assert.equal(session.result.user.email, ME.email); |
| +добавлено | const teams = await rpc('teams'); |
| +добавлено | assert.equal(teams.result[0].id, TEAM); |
| +добавлено | const sel = await rpc('selectTeam', { teamId: TEAM }); |
| +добавлено | assert.equal(sel.result.teamId, TEAM); |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.equal(st.signedIn, true); |
| +добавлено | assert.equal(st.teamId, TEAM); |
| +добавлено | // токены не утекают ни в /state, ни в state.json открытым текстом |
| +добавлено | assert.ok(!JSON.stringify(st).includes('access-1')); |
| +добавлено | assert.ok(!fs.readFileSync(path.join(env.ZTEAM_STATE_DIR, 'state.json'), 'utf8').includes('access-1')); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('board via /rpc (teamId defaults to the selected team)', async () => { |
| +добавлено | const r = await rpc('board'); |
| +добавлено | assert.equal(r.status, 200); |
| +добавлено | assert.equal(r.result.tasks.length, 3); |
| +добавлено | assert.equal(r.result.members.length, 2); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('updateTask passes changes through verbatim (null kept)', async () => { |
| +добавлено | const r = await rpc('updateTask', { taskId: fake.tasks[1].id, changes: { dueAt: null, priority: 'urgent' } }); |
| +добавлено | assert.equal(r.status, 200); |
| +добавлено | assert.equal(fake.tasks[1].dueAt, null); |
| +добавлено | assert.equal(fake.tasks[1].priority, 'urgent'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/agent/rpc: rejects without token, with Origin; createTask with token', async () => { |
| +добавлено | const none = await agent('myTasks'); |
| +добавлено | assert.equal(none.status, 401); |
| +добавлено | const wrong = await agent('myTasks', {}, 'f'.repeat(64)); |
| +добавлено | assert.equal(wrong.status, 401); |
| +добавлено | const withOrigin = await fetch(`${SVC}/agent/rpc`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', 'x-zteam-agent': agentToken(), origin: ORIGIN }, |
| +добавлено | body: '{"method":"myTasks"}', |
| +добавлено | }); |
| +добавлено | assert.equal(withOrigin.status, 403); |
| +добавлено | const forbidden = await agent('deleteTask', { taskId: fake.tasks[0].id }, agentToken()); |
| +добавлено | assert.equal(forbidden.status, 404); |
| +добавлено | |
| +добавлено | const created = await agent('createTask', { title: 'Из агента', priority: 'high', labels: ['ai'], dueAt: '2026-12-01' }, agentToken()); |
| +добавлено | assert.equal(created.status, 200, JSON.stringify(created.body)); |
| +добавлено | const t = created.body.result; |
| +добавлено | assert.equal(t.title, 'Из агента'); |
| +добавлено | assert.equal(t.assigneeId, ME.id, 'assignee defaults to me'); |
| +добавлено | assert.equal(t.shortId, t.id.slice(0, 8)); |
| +добавлено | assert.equal(t.dueAt, '2026-12-01'); |
| +добавлено | |
| +добавлено | const forPetr = await agent('createTask', { title: 'Для Петра', assignee: 'petr' }, agentToken()); |
| +добавлено | assert.equal(forPetr.body.result.assigneeId, PETR.id); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/agent/rpc: board, myTasks, getTask by prefix, moveTask, updateTask assignee', async () => { |
| +добавлено | const tok = agentToken(); |
| +добавлено | const board = (await agent('board', { status: 'doing' }, tok)).body.result; |
| +добавлено | assert.ok(board.tasks.every((t) => t.status === 'doing')); |
| +добавлено | assert.ok(board.tasks[0].shortId.length === 8); |
| +добавлено | const my = (await agent('myTasks', {}, tok)).body.result; |
| +добавлено | assert.equal(my.teamName, 'Alpha'); |
| +добавлено | assert.ok(my.tasks.every((t) => t.assigneeId === ME.id && t.status !== 'done')); |
| +добавлено | const got = await agent('getTask', { taskId: '#1a2b3c' }, tok); |
| +добавлено | assert.equal(got.status, 200); |
| +добавлено | assert.equal(got.body.result.id, fake.tasks[0].id); |
| +добавлено | assert.equal(got.body.result.history.length, 1); |
| +добавлено | const short = await agent('getTask', { taskId: '1a2b' }, tok); |
| +добавлено | assert.equal(short.status, 400); |
| +добавлено | const moved = await agent('moveTask', { taskId: '1a2b3c4d', status: 'review' }, tok); |
| +добавлено | assert.equal(moved.body.result.status, 'review'); |
| +добавлено | const badStatus = await agent('moveTask', { taskId: '1a2b3c4d', status: 'wip' }, tok); |
| +добавлено | assert.equal(badStatus.status, 400); |
| +добавлено | const re = await agent('updateTask', { taskId: '1a2b3c4d', assignee: 'Petr', priority: 'low' }, tok); |
| +добавлено | assert.equal(re.body.result.assigneeName, 'Petr'); |
| +добавлено | assert.equal(re.body.result.priority, 'low'); |
| +добавлено | const act = await agent('activity', { limit: 5 }, tok); |
| +добавлено | assert.equal(act.body.result[0].action, 'task.create'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/ide/context: requires agent token, sets workspace if empty, emits SSE', async () => { |
| +добавлено | const dir = fs.mkdtempSync(path.join(tmp, 'ws-')); |
| +добавлено | const noTok = await fetch(`${SVC}/ide/context`, { method: 'POST', body: JSON.stringify({ cwd: dir }) }); |
| +добавлено | assert.equal(noTok.status, 401); |
| +добавлено | const r = await fetch(`${SVC}/ide/context`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', 'x-zteam-agent': agentToken() }, |
| +добавлено | body: JSON.stringify({ cwd: dir, event: 'SessionStart', sessionId: 's1' }), |
| +добавлено | }); |
| +добавлено | assert.equal(r.status, 200); |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.equal(path.resolve(st.workspace), path.resolve(dir)); |
| +добавлено | assert.equal(path.resolve(st.ide.cwd), path.resolve(dir)); |
| +добавлено | assert.equal(st.recentWorkspaces.length, 1); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('SSE /events: hello + local state event after /settings', async () => { |
| +добавлено | const events = []; |
| +добавлено | const req = http.get({ host: '127.0.0.1', port: PORT, path: '/events', headers: { origin: ORIGIN } }); |
| +добавлено | const res = await new Promise((resolve) => req.on('response', resolve)); |
| +добавлено | assert.equal(res.statusCode, 200); |
| +добавлено | assert.match(res.headers['content-type'], /text\/event-stream/); |
| +добавлено | res.setEncoding('utf8'); |
| +добавлено | let buf = ''; |
| +добавлено | res.on('data', (c) => { |
| +добавлено | buf += c; |
| +добавлено | let i; |
| +добавлено | while ((i = buf.indexOf('\n\n')) >= 0) { |
| +добавлено | const block = buf.slice(0, i); |
| +добавлено | buf = buf.slice(i + 2); |
| +добавлено | const ev = /^event: (.+)$/m.exec(block)?.[1]; |
| +добавлено | const data = /^data: (.+)$/m.exec(block)?.[1]; |
| +добавлено | if (ev) events.push({ ev, data: JSON.parse(data) }); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | await waitFor(() => events.some((e) => e.data.type === 'hello'), 3000); |
| +добавлено | const s = await fetch(`${SVC}/settings`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'content-type': 'application/json', 'x-zteam-csrf': csrf, origin: ORIGIN }, |
| +добавлено | body: JSON.stringify({ ui: { theme: 'dark', dock: 420 } }), |
| +добавлено | }); |
| +добавлено | assert.equal(s.status, 200); |
| +добавлено | await waitFor(() => events.some((e) => e.ev === 'local' && e.data.type === 'state'), 3000); |
| +добавлено | req.destroy(); |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.deepEqual(st.ui, { theme: 'dark', dock: 420 }); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('localProviders: masked hints, key counts, never raw keys', async () => { |
| +добавлено | const r = await rpc('localProviders'); |
| +добавлено | assert.equal(r.status, 200); |
| +добавлено | const text = JSON.stringify(r.body); |
| +добавлено | assert.ok(!text.includes(LOCAL_KEY) && !text.includes(POOL_KEY) && !text.includes('another-secret'), 'raw key leaked'); |
| +добавлено | const gw = r.result.find((x) => x.providerId === 'local-openai'); |
| +добавлено | assert.equal(gw.keyHint, 'sk-…1234'); |
| +добавлено | assert.equal(gw.keyCount, 2, 'primary + pool extra, deduped'); |
| +добавлено | assert.deepEqual(gw.models, ['gpt-y', 'gpt-x'], 'modelOrder wins'); |
| +добавлено | assert.equal(gw.apiType, 'openai-chat-completions'); |
| +добавлено | assert.equal(gw.teamManaged, false); |
| +добавлено | const cl = r.result.find((x) => x.providerId === 'local-claude'); |
| +добавлено | assert.deepEqual(cl.models, ['claude-z'], 'falls back to personalModelIds'); |
| +добавлено | assert.ok(!r.result.some((x) => x.providerId === 'empty'), 'providers without endpoint skipped'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('shareLocalProvider: creates keys with raw value server-side, dedupes on repeat', async () => { |
| +добавлено | const first = await rpc('shareLocalProvider', { providerId: 'local-openai', models: ['gpt-x'], dailyLimit: 100, accessRole: 'dev', allKeys: true }); |
| +добавлено | assert.equal(first.status, 200, JSON.stringify(first.body)); |
| +добавлено | assert.equal(first.result.created, 2); |
| +добавлено | assert.equal(first.result.skipped, 0); |
| +добавлено | assert.ok(!JSON.stringify(first.body).includes(LOCAL_KEY)); |
| +добавлено | const k = fake.keys.find((x) => x.value === LOCAL_KEY); |
| +добавлено | assert.equal(k.provider, 'openai'); |
| +добавлено | assert.equal(k.baseUrl, 'https://gw.example.com/v1'); |
| +добавлено | assert.equal(k.model, 'gpt-x'); |
| +добавлено | assert.deepEqual(k.models, ['gpt-x']); |
| +добавлено | assert.equal(k.dailyLimit, 100); |
| +добавлено | assert.equal(k.label, 'Local GW (shared)'); |
| +добавлено | const again = await rpc('shareLocalProvider', { providerId: 'local-openai', models: ['gpt-x'], dailyLimit: null, accessRole: 'dev', allKeys: true }); |
| +добавлено | assert.equal(again.result.created, 0); |
| +добавлено | assert.equal(again.result.skipped, 2); |
| +добавлено | const cl = await rpc('shareLocalProvider', { providerId: 'local-claude', models: [], dailyLimit: null, accessRole: 'viewer' }); |
| +добавлено | assert.equal(cl.result.created, 1); |
| +добавлено | assert.equal(fake.keys.at(-1).provider, 'anthropic'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('connectTeamProvider writes a valid rule, preserves other fields; reconnect revokes; disconnect restores', async () => { |
| +добавлено | const file = env.ZTEAM_PROVIDER_CONFIG; |
| +добавлено | const original = readJson(file); |
| +добавлено | const r = await rpc('connectTeamProvider', { provider: 'openai', models: ['gpt-x', 'gpt-new'] }); |
| +добавлено | assert.equal(r.status, 200, JSON.stringify(r.body)); |
| +добавлено | const providerId = `team-openai-${TEAM.slice(0, 8)}`; |
| +добавлено | assert.deepEqual(r.result, { providerId, models: ['gpt-x', 'gpt-new'] }); |
| +добавлено | |
| +добавлено | const doc = readJson(file); |
| +добавлено | const rule = doc.config.providerConfigRules.providerRules.find((x) => x.providerId === providerId); |
| +добавлено | const token = fake.proxyTokens.at(-1); |
| +добавлено | assert.deepEqual(token.body, { provider: 'openai', model: '*' }); |
| +добавлено | assert.deepEqual(rule, { |
| +добавлено | providerId, |
| +добавлено | providerName: 'Team · Alpha', |
| +добавлено | enabled: true, |
| +добавлено | config: { |
| +добавлено | group: 'standard-personal', |
| +добавлено | access: { type: 'api-key', apiKey: token.token }, |
| +добавлено | api: { type: 'openai-chat-completions', baseUrl: `${backendUrl}/v1/teams/${TEAM}/proxy/openai/v1` }, |
| +добавлено | personalModelIds: ['gpt-x', 'gpt-new'], |
| +добавлено | modelOrder: ['gpt-x', 'gpt-new'], |
| +добавлено | }, |
| +добавлено | }, 'rule has no extra keys (ZCode schema is strict)'); |
| +добавлено | assert.deepEqual(doc.config.providerOrder, ['local-openai', 'local-claude', providerId]); |
| +добавлено | assert.deepEqual(doc.config.defaultModelSelection, original.config.defaultModelSelection); |
| +добавлено | assert.deepEqual(doc.config.providerConfigRules.providerRules.filter((x) => x.providerId !== providerId), original.config.providerConfigRules.providerRules); |
| +добавлено | const mr = doc.config.modelConfigRules.providerModelRules.filter((x) => x.providerId === providerId); |
| +добавлено | assert.deepEqual(mr.map((x) => x.modelId).sort(), ['gpt-new', 'gpt-x']); |
| +добавлено | assert.deepEqual(mr[0].config, { enabled: true, properties: { inputFormat: { supportsText: true } } }); |
| +добавлено | assert.deepEqual(doc.config.modelConfigRules.manualProviderModelRules, []); |
| +добавлено | assert.ok(fs.existsSync(path.join(path.dirname(file), 'provider_config.before-team.json')), 'backup made'); |
| +добавлено | assert.deepEqual(readJson(path.join(path.dirname(file), 'provider_config.before-team.json')), original); |
| +добавлено | |
| +добавлено | const lp = (await rpc('localProviders')).result.find((x) => x.providerId === providerId); |
| +добавлено | assert.equal(lp.teamManaged, true); |
| +добавлено | assert.ok(!JSON.stringify(lp).includes(token.token)); |
| +добавлено | |
| +добавлено | // повторное подключение: старый токен отзывается, правило заменяется, gpt-new уходит |
| +добавлено | const r2 = await rpc('connectTeamProvider', { provider: 'openai', models: ['gpt-x'], name: 'Моя команда' }); |
| +добавлено | assert.equal(r2.status, 200); |
| +добавлено | assert.ok(fake.revoked.includes(token.id), 'old proxy token revoked'); |
| +добавлено | const doc2 = readJson(file); |
| +добавлено | const rules2 = doc2.config.providerConfigRules.providerRules.filter((x) => x.providerId === providerId); |
| +добавлено | assert.equal(rules2.length, 1); |
| +добавлено | assert.equal(rules2[0].providerName, 'Моя команда'); |
| +добавлено | assert.equal(rules2[0].config.access.apiKey, fake.proxyTokens.at(-1).token); |
| +добавлено | assert.deepEqual(doc2.config.modelConfigRules.providerModelRules.filter((x) => x.providerId === providerId).map((x) => x.modelId), ['gpt-x']); |
| +добавлено | assert.equal(doc2.config.providerOrder.filter((x) => x === providerId).length, 1); |
| +добавлено | |
| +добавлено | // anthropic: без /v1 в base URL (ZCode сам добавляет /v1 для anthropic-messages) |
| +добавлено | const ra = await rpc('connectTeamProvider', { provider: 'anthropic', models: ['claude-z'] }); |
| +добавлено | const ruleA = readJson(file).config.providerConfigRules.providerRules.find((x) => x.providerId === ra.result.providerId); |
| +добавлено | assert.equal(ruleA.config.api.type, 'anthropic-messages'); |
| +добавлено | assert.equal(ruleA.config.api.baseUrl, `${backendUrl}/v1/teams/${TEAM}/proxy/anthropic`); |
| +добавлено | |
| +добавлено | const lastToken = fake.proxyTokens.at(-2).id; |
| +добавлено | assert.equal((await rpc('disconnectTeamProvider', { providerId })).status, 200); |
| +добавлено | assert.ok(fake.revoked.includes(lastToken)); |
| +добавлено | assert.equal((await rpc('disconnectTeamProvider', { providerId: ra.result.providerId })).status, 200); |
| +добавлено | assert.deepEqual(readJson(file), original, 'disconnect restores the original document'); |
| +добавлено | assert.equal((await rpc('disconnectTeamProvider', { providerId: 'local-openai' })).status, 404, 'cannot remove non-team providers'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/upload streams a 5 MB file to the backend as intact multipart', async () => { |
| +добавлено | const data = crypto.randomBytes(5 * 1024 * 1024); |
| +добавлено | const sha = crypto.createHash('sha256').update(data).digest('hex'); |
| +добавлено | const name = 'отчёт 2026 (финал).bin'; |
| +добавлено | const noCsrf = await fetch(`${SVC}/upload?kind=file`, { method: 'POST', headers: { 'x-file-name': encodeURIComponent(name) }, body: data }); |
| +добавлено | assert.equal(noCsrf.status, 403); |
| +добавлено | const res = await fetch(`${SVC}/upload?kind=file&recipientId=${PETR.id}¬e=${encodeURIComponent('привет')}`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'x-zteam-csrf': csrf, origin: ORIGIN, 'x-file-name': encodeURIComponent(name), 'content-type': 'application/octet-stream' }, |
| +добавлено | body: data, |
| +добавлено | }); |
| +добавлено | const body = await res.json(); |
| +добавлено | assert.equal(res.status, 200, JSON.stringify(body)); |
| +добавлено | const up = fake.uploads.at(-1); |
| +добавлено | assert.equal(up.kind, 'file'); |
| +добавлено | assert.equal(up.bytes, data.length); |
| +добавлено | assert.equal(up.sha256, sha); |
| +добавлено | assert.equal(up.name, name); |
| +добавлено | assert.equal(up.contentLength, up.received, 'explicit content-length matches the streamed body'); |
| +добавлено | assert.deepEqual(up.query, { recipientId: PETR.id, note: 'привет' }); |
| +добавлено | assert.equal(body.sha256, sha); |
| +добавлено | // временный файл удалён |
| +добавлено | const tmpDir = path.join(env.ZTEAM_STATE_DIR, '.tmp'); |
| +добавлено | await waitFor(() => !fs.existsSync(tmpDir) || fs.readdirSync(tmpDir).length === 0, 3000); |
| +добавлено | |
| +добавлено | const arch = await fetch(`${SVC}/upload?kind=archive&projectName=${encodeURIComponent('Проект')}`, { |
| +добавлено | method: 'POST', |
| +добавлено | headers: { 'x-zteam-csrf': csrf, origin: ORIGIN, 'x-file-name': encodeURIComponent('src.zip') }, |
| +добавлено | body: data.subarray(0, 1000), |
| +добавлено | }); |
| +добавлено | assert.equal(arch.status, 200); |
| +добавлено | assert.equal(fake.uploads.at(-1).kind, 'archive'); |
| +добавлено | assert.deepEqual(fake.uploads.at(-1).query, { projectName: 'Проект' }); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('git: status / stage / commit (+task link) / log / show / diff / unstage / discard / branches', async () => { |
| +добавлено | const repo = fs.mkdtempSync(path.join(tmp, 'repo-')); |
| +добавлено | git(repo, 'init', '-q', '-b', 'main'); |
| +добавлено | git(repo, 'config', 'user.email', 'ivan@example.com'); |
| +добавлено | git(repo, 'config', 'user.name', 'Ivan'); |
| +добавлено | git(repo, 'config', 'core.autocrlf', 'false'); |
| +добавлено | fs.writeFileSync(path.join(repo, 'a.txt'), 'one\n'); |
| +добавлено | fs.writeFileSync(path.join(repo, 'файл b.txt'), 'b\n'); |
| +добавлено | |
| +добавлено | let s = (await rpc('git', { dir: repo })).result; |
| +добавлено | assert.equal(s.isRepo, true); |
| +добавлено | assert.equal(s.branch, 'main'); |
| +добавлено | assert.deepEqual(s.untracked.sort(), ['a.txt', 'файл b.txt'].sort()); |
| +добавлено | |
| +добавлено | const none = await rpc('gitCommit', { dir: repo, message: 'empty' }); |
| +добавлено | assert.equal(none.status, 400); |
| +добавлено | assert.match(none.body.error, /Nothing staged/); |
| +добавлено | |
| +добавлено | assert.equal((await rpc('gitStage', { dir: repo, files: ['-rf'] })).status, 400, 'option-like file rejected'); |
| +добавлено | assert.equal((await rpc('gitStage', { dir: repo, files: ['a.txt'] })).status, 200); |
| +добавлено | s = (await rpc('git', { dir: repo })).result; |
| +добавлено | assert.deepEqual(s.staged.map((x) => [x.path, x.status]), [['a.txt', 'added']]); |
| +добавлено | assert.deepEqual(s.untracked, ['файл b.txt']); |
| +добавлено | |
| +добавлено | const c1 = await rpc('gitCommit', { dir: repo, message: 'feat: first #1a2b3c4d' }); |
| +добавлено | assert.equal(c1.status, 200, JSON.stringify(c1.body)); |
| +добавлено | assert.match(c1.result.hash, /^[0-9a-f]{40}$/); |
| +добавлено | assert.equal(c1.result.pushed, false); |
| +добавлено | assert.equal(fake.commits.at(-1).commitHash, c1.result.hash); |
| +добавлено | assert.equal(path.resolve(fake.commits.at(-1).repositoryUrl), path.resolve(repo), 'no remote → cwd'); |
| +добавлено | assert.equal(c1.result.linkedTaskId, fake.tasks[0].id); |
| +добавлено | |
| +добавлено | await rpc('gitStageAll', { dir: repo }); |
| +добавлено | const c2 = await rpc('gitCommit', { dir: repo, message: 'second\n\nbody line' }); |
| +добавлено | assert.equal(c2.status, 200); |
| +добавлено | |
| +добавлено | const logR = (await rpc('gitLog', { dir: repo, limit: 10 })).result; |
| +добавлено | assert.equal(logR.length, 2); |
| +добавлено | assert.equal(logR[0].subject, 'second'); |
| +добавлено | assert.equal(logR[0].parents[0], c1.result.hash); |
| +добавлено | assert.ok(logR[0].refs.some((x) => /main/.test(x))); |
| +добавлено | assert.ok(!Number.isNaN(Date.parse(logR[0].date))); |
| +добавлено | assert.equal((await rpc('gitLog', { dir: repo, limit: 10, skip: 1 })).result.length, 1); |
| +добавлено | assert.equal((await rpc('gitLog', { dir: repo, file: 'a.txt' })).result.length, 1); |
| +добавлено | |
| +добавлено | const shown = (await rpc('gitShow', { dir: repo, hash: c2.result.hash })).result; |
| +добавлено | assert.equal(shown.subject, 'second'); |
| +добавлено | assert.equal(shown.body, 'body line'); |
| +добавлено | assert.deepEqual(shown.files.map((f) => [f.path, f.status, f.additions, f.deletions]), [['файл b.txt', 'added', 1, 0]]); |
| +добавлено | assert.match(shown.patch, /\+b/); |
| +добавлено | assert.equal(shown.truncated, false); |
| +добавлено | assert.equal((await rpc('gitShow', { dir: repo, hash: '--all' })).status, 400); |
| +добавлено | |
| +добавлено | // изменения для unstage / discard |
| +добавлено | fs.writeFileSync(path.join(repo, 'a.txt'), 'one\ntwo\n'); |
| +добавлено | fs.writeFileSync(path.join(repo, 'new.txt'), 'n\n'); |
| +добавлено | const d = (await rpc('gitDiff', { dir: repo, file: 'a.txt' })).result; |
| +добавлено | assert.match(d.diff, /\+two/); |
| +добавлено | const du = (await rpc('gitDiff', { dir: repo, file: 'new.txt' })).result; |
| +добавлено | assert.equal(du.untracked, true); |
| +добавлено | assert.match(du.diff, /\+n/); |
| +добавлено | await rpc('gitStage', { dir: repo, files: ['a.txt'] }); |
| +добавлено | assert.match((await rpc('gitDiff', { dir: repo, staged: true })).result.diff, /\+two/); |
| +добавлено | assert.equal((await rpc('gitUnstage', { dir: repo, files: ['a.txt'] })).status, 200); |
| +добавлено | s = (await rpc('git', { dir: repo })).result; |
| +добавлено | assert.equal(s.staged.length, 0); |
| +добавлено | assert.deepEqual(s.unstaged.map((x) => x.path), ['a.txt']); |
| +добавлено | |
| +добавлено | assert.equal((await rpc('gitDiscard', { dir: repo, files: ['../outside.txt'] })).status, 400, 'path escape rejected'); |
| +добавлено | const disc = await rpc('gitDiscard', { dir: repo, files: ['a.txt', 'new.txt'] }); |
| +добавлено | assert.equal(disc.status, 200, JSON.stringify(disc.body)); |
| +добавлено | assert.deepEqual(disc.result.removed, ['new.txt']); |
| +добавлено | assert.equal(fs.readFileSync(path.join(repo, 'a.txt'), 'utf8'), 'one\n'); |
| +добавлено | assert.equal(fs.existsSync(path.join(repo, 'new.txt')), false); |
| +добавлено | s = (await rpc('git', { dir: repo })).result; |
| +добавлено | assert.equal(s.counts.total, 0); |
| +добавлено | |
| +добавлено | assert.equal((await rpc('gitCheckout', { dir: repo, branch: 'bad..name', create: true })).status, 400); |
| +добавлено | assert.equal((await rpc('gitCheckout', { dir: repo, branch: 'feat/x', create: true })).status, 200); |
| +добавлено | const br = (await rpc('gitBranches', { dir: repo })).result; |
| +добавлено | assert.deepEqual(br.map((b) => [b.name, b.current]).sort(), [['feat/x', true], ['main', false]]); |
| +добавлено | assert.equal(br[0].lastCommit.hash.length >= 7, true); |
| +добавлено | |
| +добавлено | const nr = (await rpc('git', { dir: tmp })).result; |
| +добавлено | assert.equal(nr.isRepo, false); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('realtime: backend WebSocket events (re-ticketed) are relayed to SSE as event: team', async () => { |
| +добавлено | const events = []; |
| +добавлено | const req = http.get({ host: '127.0.0.1', port: PORT, path: '/events', headers: { origin: ORIGIN } }); |
| +добавлено | const res = await new Promise((resolve) => req.on('response', resolve)); |
| +добавлено | res.setEncoding('utf8'); |
| +добавлено | let buf = ''; |
| +добавлено | res.on('data', (c) => { |
| +добавлено | buf += c; |
| +добавлено | let i; |
| +добавлено | while ((i = buf.indexOf('\n\n')) >= 0) { |
| +добавлено | const block = buf.slice(0, i); |
| +добавлено | buf = buf.slice(i + 2); |
| +добавлено | const ev = /^event: (.+)$/m.exec(block)?.[1]; |
| +добавлено | const data = /^data: (.+)$/m.exec(block)?.[1]; |
| +добавлено | if (ev) events.push({ ev, data: JSON.parse(data) }); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | try { |
| +добавлено | const ticketsBefore = fake.requests.filter((r) => r.path.endsWith('/events-ticket')).length; |
| +добавлено | // Принудительный реконнект: закрываем текущие сокеты на стороне бэкенда. |
| +добавлено | for (const s of fake.ws) s.destroy(); |
| +добавлено | await waitFor(() => events.some((e) => e.ev === 'team' && e.data.type === 'task.changed'), 8000); |
| +добавлено | const team = events.find((e) => e.ev === 'team' && e.data.type === 'task.changed'); |
| +добавлено | assert.deepEqual(team.data, { type: 'task.changed', at: '2026-11-11T12:00:00.000Z' }); |
| +добавлено | assert.ok(fake.requests.filter((r) => r.path.endsWith('/events-ticket')).length > ticketsBefore, 'new ticket per connection'); |
| +добавлено | await waitFor(async () => (await (await fetch(`${SVC}/state`)).json()).realtime === 'connected', 3000); |
| +добавлено | } finally { |
| +добавлено | req.destroy(); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/plugin-state reflects config.json toggles without restart (CORS *)', async () => { |
| +добавлено | const cfgFile = path.join(env.ZTEAM_ZCODE_HOME, 'config.json'); |
| +добавлено | let r = await fetch(`${SVC}/plugin-state`, { headers: { origin: 'app://zcode' } }); |
| +добавлено | assert.equal(r.headers.get('access-control-allow-origin'), '*'); |
| +добавлено | let s = await r.json(); |
| +добавлено | assert.equal(s.installed, true); |
| +добавлено | assert.equal(s.enabled, true); |
| +добавлено | assert.equal(s.signedIn, true); |
| +добавлено | assert.equal(typeof s.pending, 'number'); |
| +добавлено | assert.equal(s.pending, fake.tasks.filter((t) => t.assigneeId === ME.id && t.status !== 'done').length); |
| +добавлено | |
| +добавлено | const cfg = readJson(cfgFile); |
| +добавлено | cfg.plugins.enabledPlugins['aura-team@local-marketplace'] = false; |
| +добавлено | writeJson(cfgFile, cfg); |
| +добавлено | s = await (await fetch(`${SVC}/plugin-state`)).json(); |
| +добавлено | assert.equal(s.enabled, false); |
| +добавлено | assert.equal(s.installed, true); |
| +добавлено | |
| +добавлено | cfg.plugins.enabledPlugins['aura-team@local-marketplace'] = true; |
| +добавлено | cfg.plugins.enabled = false; |
| +добавлено | writeJson(cfgFile, cfg); |
| +добавлено | assert.equal((await (await fetch(`${SVC}/plugin-state`)).json()).enabled, false, 'global plugins.enabled=false wins'); |
| +добавлено | |
| +добавлено | cfg.plugins.enabled = true; |
| +добавлено | writeJson(cfgFile, cfg); |
| +добавлено | assert.equal((await (await fetch(`${SVC}/plugin-state`)).json()).enabled, true); |
| +добавлено | assert.deepEqual((await (await fetch(`${SVC}/state`)).json()).plugin, { installed: true, enabled: true }); |
| +добавлено | |
| +добавлено | const notify = await (await fetch(`${SVC}/notify/pending`)).json(); |
| +добавлено | assert.equal(typeof notify.count, 'number'); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('/panel and /panel/assets', async () => { |
| +добавлено | const p = await fetch(`${SVC}/panel`); |
| +добавлено | assert.equal(p.status, 200); |
| +добавлено | assert.equal(p.headers.get('cache-control'), 'no-store'); |
| +добавлено | assert.match(p.headers.get('content-type'), /text\/html/); |
| +добавлено | const assetsDir = path.resolve(HERE, '..', 'assets'); |
| +добавлено | fs.mkdirSync(assetsDir, { recursive: true }); |
| +добавлено | const probe = path.join(assetsDir, `zteam-test-${process.pid}.css`); |
| +добавлено | fs.writeFileSync(probe, 'body{}'); |
| +добавлено | try { |
| +добавлено | const a = await fetch(`${SVC}/panel/assets/${path.basename(probe)}`); |
| +добавлено | assert.equal(a.status, 200); |
| +добавлено | assert.match(a.headers.get('content-type'), /text\/css/); |
| +добавлено | assert.equal(await a.text(), 'body{}'); |
| +добавлено | } finally { |
| +добавлено | fs.rmSync(probe, { force: true }); |
| +добавлено | } |
| +добавлено | assert.equal((await fetch(`${SVC}/panel/assets/..%2Fserver.mjs`)).status, 400); |
| +добавлено | assert.equal((await fetch(`${SVC}/panel/assets/missing.png`)).status, 404); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('changePassword re-logs in with the new password', async () => { |
| +добавлено | const r = await rpc('changePassword', { currentPassword: fake.password, newPassword: 'new-secret-pass' }); |
| +добавлено | assert.equal(r.status, 200, JSON.stringify(r.body)); |
| +добавлено | assert.equal(r.result.relogged, true); |
| +добавлено | assert.equal((await rpc('session')).status, 200); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // ---------------------------------------------------------------- плагин: MCP и хук |
| +добавлено | |
| +добавлено | function mcpSession() { |
| +добавлено | const child = spawn(process.execPath, [path.join(PLUGIN_SCRIPTS, 'mcp-server.mjs')], { |
| +добавлено | env: { ...process.env, ZTEAM_AGENT_FILE: env.ZTEAM_AGENT_FILE }, |
| +добавлено | stdio: ['pipe', 'pipe', 'pipe'], |
| +добавлено | windowsHide: true, |
| +добавлено | }); |
| +добавлено | let buf = ''; |
| +добавлено | const waiting = new Map(); |
| +добавлено | child.stdout.setEncoding('utf8'); |
| +добавлено | child.stdout.on('data', (c) => { |
| +добавлено | buf += c; |
| +добавлено | let i; |
| +добавлено | while ((i = buf.indexOf('\n')) >= 0) { |
| +добавлено | const line = buf.slice(0, i); |
| +добавлено | buf = buf.slice(i + 1); |
| +добавлено | if (!line.trim()) continue; |
| +добавлено | const msg = JSON.parse(line); |
| +добавлено | waiting.get(msg.id)?.(msg); |
| +добавлено | waiting.delete(msg.id); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | let next = 1; |
| +добавлено | return { |
| +добавлено | child, |
| +добавлено | request(method, params) { |
| +добавлено | const id = next++; |
| +добавлено | child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`); |
| +добавлено | return new Promise((resolve, reject) => { |
| +добавлено | waiting.set(id, resolve); |
| +добавлено | setTimeout(() => reject(new Error(`MCP timeout on ${method}`)), 8000); |
| +добавлено | }); |
| +добавлено | }, |
| +добавлено | notify(method, params) { |
| +добавлено | child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params })}\n`); |
| +добавлено | }, |
| +добавлено | close() { child.stdin.end(); }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | test('MCP server: initialize, tools/list, tools/call team_my_tasks + team_create_task', async () => { |
| +добавлено | const s = mcpSession(); |
| +добавлено | try { |
| +добавлено | const init = await s.request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'test', version: '0' } }); |
| +добавлено | assert.equal(init.result.protocolVersion, '2025-03-26'); |
| +добавлено | assert.equal(init.result.serverInfo.name, 'aura-team'); |
| +добавлено | s.notify('notifications/initialized'); |
| +добавлено | assert.deepEqual((await s.request('ping')).result, {}); |
| +добавлено | |
| +добавлено | const list = await s.request('tools/list', {}); |
| +добавлено | const names = list.result.tools.map((t) => t.name).sort(); |
| +добавлено | assert.deepEqual(names, ['team_activity', 'team_board', 'team_create_task', 'team_get_task', 'team_members', 'team_move_task', 'team_my_tasks', 'team_update_task', 'team_whoami']); |
| +добавлено | const board = list.result.tools.find((t) => t.name === 'team_board'); |
| +добавлено | assert.equal(board.annotations.readOnlyHint, true); |
| +добавлено | assert.equal(list.result.tools.find((t) => t.name === 'team_create_task').annotations.readOnlyHint, false); |
| +добавлено | assert.deepEqual(list.result.tools.find((t) => t.name === 'team_create_task').inputSchema.required, ['title']); |
| +добавлено | |
| +добавлено | const my = await s.request('tools/call', { name: 'team_my_tasks', arguments: {} }); |
| +добавлено | assert.equal(my.result.isError, undefined, JSON.stringify(my.result)); |
| +добавлено | const text = my.result.content[0].text; |
| +добавлено | assert.match(text, /Команда «Alpha»/); |
| +добавлено | assert.match(text, /\[(todo|doing|review)\] #[0-9a-f]{8} «/); |
| +добавлено | assert.ok(Array.isArray(my.result.structuredContent.tasks)); |
| +добавлено | |
| +добавлено | const created = await s.request('tools/call', { name: 'team_create_task', arguments: { title: 'Из MCP', dueAt: '2026-11-30', priority: 'high' } }); |
| +добавлено | assert.match(created.result.content[0].text, /Создана задача \[todo\] #[0-9a-f]{8} «Из MCP» — @Ivan · high · до 2026-11-30/); |
| +добавлено | |
| +добавлено | const bad = await s.request('tools/call', { name: 'team_get_task', arguments: { taskId: 'zzzzzzzz' } }); |
| +добавлено | assert.equal(bad.result.isError, true); |
| +добавлено | |
| +добавлено | const unknown = await s.request('nope/method', {}); |
| +добавлено | assert.equal(unknown.error.code, -32601); |
| +добавлено | } finally { |
| +добавлено | s.close(); |
| +добавлено | } |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('MCP server: clear error when the service is down', async () => { |
| +добавлено | const fakeAgent = path.join(tmp, 'down-agent.json'); |
| +добавлено | writeJson(fakeAgent, { port: 1, token: 'a'.repeat(64), serviceDir: tmp }); |
| +добавлено | const child = spawn(process.execPath, [path.join(PLUGIN_SCRIPTS, 'mcp-server.mjs')], { |
| +добавлено | env: { ...process.env, ZTEAM_AGENT_FILE: fakeAgent }, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, |
| +добавлено | }); |
| +добавлено | child.stdin.end(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'team_my_tasks', arguments: {} } })}\n`); |
| +добавлено | let out = ''; |
| +добавлено | for await (const c of child.stdout) out += c; |
| +добавлено | const msg = JSON.parse(out.trim().split('\n')[0]); |
| +добавлено | assert.equal(msg.result.isError, true); |
| +добавлено | assert.match(msg.result.content[0].text, /Aura Team сервис не запущен/); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('SessionStart hook: posts ide context and prints additionalContext JSON; silent when down', async () => { |
| +добавлено | const run = (agentFile, stdin) => new Promise((resolve) => { |
| +добавлено | const child = spawn(process.execPath, [path.join(PLUGIN_SCRIPTS, 'session-start.mjs')], { |
| +добавлено | env: { ...process.env, ZTEAM_AGENT_FILE: agentFile }, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, |
| +добавлено | }); |
| +добавлено | let out = ''; |
| +добавлено | child.stdout.on('data', (c) => { out += c; }); |
| +добавлено | child.on('exit', (code) => resolve({ code, out })); |
| +добавлено | child.stdin.end(stdin); |
| +добавлено | }); |
| +добавлено | const r = await run(env.ZTEAM_AGENT_FILE, JSON.stringify({ cwd: tmp, hook_event_name: 'SessionStart', session_id: 'sess_x' })); |
| +добавлено | assert.equal(r.code, 0); |
| +добавлено | const out = JSON.parse(r.out); |
| +добавлено | assert.equal(out.hookSpecificOutput.hookEventName, 'SessionStart'); |
| +добавлено | assert.match(out.hookSpecificOutput.additionalContext, /^Aura Team · команда «Alpha»: у вас \d+ открыт/); |
| +добавлено | assert.ok(out.hookSpecificOutput.additionalContext.split('\n').length <= 12); |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.equal(path.resolve(st.ide.cwd), path.resolve(tmp)); |
| +добавлено | assert.equal(st.ide.sessionId, 'sess_x'); |
| +добавлено | |
| +добавлено | const down = await run(path.join(tmp, 'down-agent.json'), JSON.stringify({ cwd: tmp })); |
| +добавлено | assert.equal(down.code, 0); |
| +добавлено | assert.equal(down.out, ''); |
| +добавлено | const garbage = await run(env.ZTEAM_AGENT_FILE, 'not json'); |
| +добавлено | assert.equal(garbage.code, 0); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | test('logout clears session', async () => { |
| +добавлено | assert.equal((await rpc('logout')).status, 200); |
| +добавлено | const st = await (await fetch(`${SVC}/state`)).json(); |
| +добавлено | assert.equal(st.signedIn, false); |
| +добавлено | assert.equal(st.teamId, null); |
| +добавлено | const ps = await (await fetch(`${SVC}/plugin-state`)).json(); |
| +добавлено | assert.equal(ps.signedIn, false); |
| +добавлено | assert.equal(ps.pending, 0); |
| +добавлено | }); |
| +добавлено | @echo off |
| +добавлено | setlocal |
| +добавлено | rem Запуск терминального воркера ZCode с уведомлением оператору. |
| +добавлено | rem Использование: worker.cmd "текст задачи" [путь-к-проекту] |
| +добавлено | set "ROOT=%~dp0" |
| +добавлено | set "HOME_DIR=%ROOT%home" |
| +добавлено | set "TASK=%~1" |
| +добавлено | set "WORKDIR=%~2" |
| +добавлено | if "%TASK%"=="" ( |
| +добавлено | echo Использование: worker.cmd "текст задачи" [путь-к-проекту] |
| +добавлено | exit /b 1 |
| +добавлено | ) |
| +добавлено | if "%WORKDIR%"=="" set "WORKDIR=%CD%" |
| +добавлено | |
| +добавлено | set "ZCODE_PERSONAL_PROVIDER_CONFIG_FILE=" |
| +добавлено | set "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE=" |
| +добавлено | set "USERPROFILE=%HOME_DIR%" |
| +добавлено | set "HOME=%HOME_DIR%" |
| +добавлено | set "ZCODE_DATA_BASE_DIR=%HOME_DIR%" |
| +добавлено | set "ZCODE_ENDPOINT_ORIGIN=http://127.0.0.1:9" |
| +добавлено | set "ZCODE_BASE_URL=http://127.0.0.1:9" |
| +добавлено | set "ZCODE_MODEL_TELEMETRY_ENABLED=false" |
| +добавлено | set "OTEL_SDK_DISABLED=true" |
| +добавлено | |
| +добавлено | echo [worker] задача: %TASK% |
| +добавлено | echo [worker] каталог: %WORKDIR% |
| +добавлено | |
| +добавлено | cd /d "%WORKDIR%" |
| +добавлено | node "%ROOT%resources\glm\zcode.cjs" -p "%TASK%" --surface terminal --mode yolo |
| +добавлено | |
| +добавлено | set "CODE=%ERRORLEVEL%" |
| +добавлено | rem Дублирующее уведомление на случай, если хук не сработал. |
| +добавлено | node "%ROOT%hooks\notify.mjs" %([%CODE%]==[0] && echo stop || echo error) --task "%~nx2" --detail "exit=%CODE%" |
| +добавлено | echo [worker] завершено с кодом %CODE% |
| +добавлено | exit /b %CODE% |
| +добавлено | #!/usr/bin/env bash |
| +добавлено | # Запуск терминального воркера ZCode с уведомлением оператору. |
| +добавлено | # Использование: ./worker.sh "текст задачи" [путь-к-проекту] |
| +добавлено | set -uo pipefail |
| +добавлено | ROOT="$(cd "$(dirname "$0")" && pwd)" |
| +добавлено | TASK="${1:-}" |
| +добавлено | WORKDIR="${2:-$PWD}" |
| +добавлено | |
| +добавлено | if [ -z "$TASK" ]; then |
| +добавлено | echo "Использование: ./worker.sh \"текст задачи\" [путь-к-проекту]" >&2 |
| +добавлено | exit 1 |
| +добавлено | fi |
| +добавлено | |
| +добавлено | unset ZCODE_PERSONAL_PROVIDER_CONFIG_FILE ZCODE_BUILTIN_PROVIDER_CONFIG_FILE || true |
| +добавлено | export HOME="$ROOT/home" |
| +добавлено | export USERPROFILE="$ROOT/home" |
| +добавлено | export ZCODE_DATA_BASE_DIR="$ROOT/home" |
| +добавлено | export ZCODE_ENDPOINT_ORIGIN="http://127.0.0.1:9" |
| +добавлено | export ZCODE_BASE_URL="http://127.0.0.1:9" |
| +добавлено | export ZCODE_MODEL_TELEMETRY_ENABLED=false |
| +добавлено | export OTEL_SDK_DISABLED=true |
| +добавлено | |
| +добавлено | echo "[worker] задача: $TASK" |
| +добавлено | echo "[worker] каталог: $WORKDIR" |
| +добавлено | |
| +добавлено | cd "$WORKDIR" || exit 1 |
| +добавлено | node "$ROOT/resources/glm/zcode.cjs" -p "$TASK" --surface terminal --mode yolo |
| +добавлено | CODE=$? |
| +добавлено | |
| +добавлено | # Дублирующее уведомление, если хук не сработал. |
| +добавлено | node "$ROOT/hooks/notify.mjs" "$([ "$CODE" -eq 0 ] && echo stop || echo error)" \ |
| +добавлено | --task "$(basename "$WORKDIR")" --detail "exit=$CODE" |
| +добавлено | |
| +добавлено | echo "[worker] завершено с кодом $CODE" |
| +добавлено | exit "$CODE" |