mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
refactor: update projects and remove legacy components
This commit is contained in:
1 parent
79e593b97f
commit
f5a1407aa3
182 files changed
+18333
-12332
No files matched your search
@@ -27,7 +27,7 @@
|
||||
|
||||
```text
|
||||
例如:
|
||||
- uv run main.py / uv run granian ... 启动正常
|
||||
- uv run granian ... app.main:app 启动正常
|
||||
- 调用 /v1/chat/completions 返回符合预期
|
||||
```
|
||||
|
||||
|
||||
@@ -21,26 +21,19 @@ jobs:
|
||||
contents: read
|
||||
packages: write
|
||||
id-token: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# AMD64 平台
|
||||
- platform: linux/amd64
|
||||
suffix: amd64
|
||||
# ARM64 平台
|
||||
- platform: linux/arm64
|
||||
suffix: arm64
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
@@ -53,57 +46,19 @@ jobs:
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
# 分支推送
|
||||
type=ref,event=branch,suffix=-${{ matrix.suffix }}
|
||||
# 语义化版本:完整版本号
|
||||
type=semver,pattern={{version}},suffix=-${{ matrix.suffix }}
|
||||
# latest标签
|
||||
type=raw,value=latest-${{ matrix.suffix }},enable={{is_default_branch}}
|
||||
# push main → latest(排除 tag 触发)
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
# tag 推送 → 版本号
|
||||
type=semver,pattern={{version}}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: ${{ matrix.platform }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha,scope=${{ matrix.suffix }}
|
||||
cache-to: type=gha,mode=max,scope=${{ matrix.suffix }}
|
||||
pull: true
|
||||
|
||||
merge-manifests:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push
|
||||
if: github.event_name != 'pull_request'
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Log in to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Create and push manifest
|
||||
run: |
|
||||
TAGS="${{ steps.meta.outputs.tags }}"
|
||||
for tag in $TAGS; do
|
||||
echo "合并标签: $tag"
|
||||
docker buildx imagetools create -t $tag \
|
||||
${tag}-amd64 \
|
||||
${tag}-arm64
|
||||
done
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
pull: true
|
||||
@@ -54,5 +54,4 @@ app/data/
|
||||
htmlcov/
|
||||
|
||||
# Project specific
|
||||
config.local.toml
|
||||
.ace-tool/
|
||||
+1
-2
@@ -64,7 +64,6 @@ COPY --from=builder /opt/venv /opt/venv
|
||||
COPY config.defaults.toml ./
|
||||
COPY app ./app
|
||||
COPY _public ./_public
|
||||
COPY main.py ./
|
||||
COPY scripts ./scripts
|
||||
|
||||
RUN mkdir -p /app/data /app/logs \
|
||||
@@ -74,4 +73,4 @@ EXPOSE 8000
|
||||
|
||||
ENTRYPOINT ["/app/scripts/entrypoint.sh"]
|
||||
|
||||
CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} main:app"]
|
||||
CMD ["sh", "-c", "granian --interface asgi --host ${SERVER_HOST:-0.0.0.0} --port ${SERVER_PORT:-8000} --workers ${SERVER_WORKERS:-1} app.main:app"]
|
||||
@@ -1,81 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="cache.pageTitle">Grok2API - 缓存管理</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="admin"></div>
|
||||
|
||||
<main class="page-body fade-in">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold" data-i18n="cache.title">缓存管理</h2>
|
||||
<p class="text-sm text-muted mt-1" data-i18n="cache.subtitle">查看和管理本地缓存文件。</p>
|
||||
</div>
|
||||
<button onclick="loadStats()" class="btn btn-outline gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
|
||||
<span data-i18n="common.refresh">刷新</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="grid-4 mb-6">
|
||||
<div class="card stat-card"><div class="stat-value" id="img-count">-</div><div class="stat-label">图片数量</div></div>
|
||||
<div class="card stat-card"><div class="stat-value" id="img-size">-</div><div class="stat-label">图片大小</div></div>
|
||||
<div class="card stat-card"><div class="stat-value" id="video-count">-</div><div class="stat-label">视频数量</div></div>
|
||||
<div class="card stat-card"><div class="stat-value" id="video-size">-</div><div class="stat-label">视频大小</div></div>
|
||||
</div>
|
||||
|
||||
<div class="tabs mb-4">
|
||||
<button class="tab-item active" data-tab="image" onclick="switchTab('image')">图片</button>
|
||||
<button class="tab-item" data-tab="video" onclick="switchTab('video')">视频</button>
|
||||
</div>
|
||||
|
||||
<div class="table-shell mb-4">
|
||||
<div class="pagination-bar">
|
||||
<div class="pagination-left">
|
||||
<button id="list-prev" class="pagination-icon-btn" onclick="listPrev()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg></button>
|
||||
<span id="list-info" class="pagination-info">-</span>
|
||||
<button id="list-next" class="pagination-icon-btn" onclick="listNext()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg></button>
|
||||
</div>
|
||||
<div class="pagination-right">
|
||||
<button onclick="clearLocalCache()" class="btn btn-danger btn-sm">清理全部</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table><thead><tr>
|
||||
<th>文件名</th><th style="width:100px;text-align:right">大小</th><th style="width:80px;text-align:center">操作</th>
|
||||
</tr></thead><tbody id="file-list-body"></tbody></table>
|
||||
</div>
|
||||
<div id="file-empty" class="table-empty hidden">暂无文件</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div id="confirm-dialog" class="modal-overlay hidden">
|
||||
<div class="modal-content modal-md"><div style="padding:8px 0">
|
||||
<div class="font-semibold mb-2">请确认</div>
|
||||
<div id="confirm-message" class="text-sm text-muted"></div>
|
||||
<div class="flex justify-end gap-2 mt-4">
|
||||
<button id="confirm-cancel" class="btn btn-outline btn-sm">取消</button>
|
||||
<button id="confirm-ok" class="btn btn-danger btn-sm">确定</button>
|
||||
</div>
|
||||
</div></div>
|
||||
</div>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/ui.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/admin/cache.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="config.pageTitle">Grok2API - 配置管理</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="admin"></div>
|
||||
|
||||
<main class="page-body fade-in">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold" data-i18n="config.title">配置管理</h2>
|
||||
<p class="text-sm text-muted mt-1" data-i18n="config.subtitle">管理 API 密钥及系统参数设置。</p>
|
||||
</div>
|
||||
<button onclick="saveConfig()" id="save-btn" class="btn btn-primary gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
|
||||
<span data-i18n="common.save">保存</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="divider"></div>
|
||||
<div id="config-container">
|
||||
<div class="text-center py-2 text-muted" data-i18n="common.loading">加载中...</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/ui.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/admin/config.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,36 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="login.adminPageTitle">Grok2API - 登录</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="login-body">
|
||||
<div class="login-bg"></div>
|
||||
<div class="login-shell">
|
||||
<div class="login-card">
|
||||
<div class="login-brand">
|
||||
<a href="https://github.com/chenyme/grok2api" target="_blank" rel="noopener" class="flex items-center gap-2" style="color:inherit">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.58 2 12.26c0 4.5 2.87 8.32 6.84 9.67.5.1.68-.22.68-.48 0-.24-.01-.86-.01-1.69-2.78.62-3.37-1.37-3.37-1.37-.45-1.17-1.11-1.48-1.11-1.48-.91-.64.07-.63.07-.63 1.01.07 1.54 1.06 1.54 1.06.9 1.58 2.36 1.12 2.94.86.09-.67.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.04 1.03-2.76-.1-.26-.45-1.3.1-2.71 0 0 .84-.27 2.75 1.05A9.3 9.3 0 0 1 12 6.79c.85 0 1.7.12 2.5.36 1.9-1.32 2.74-1.05 2.74-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.64 1.03 2.76 0 3.94-2.34 4.81-4.58 5.06.36.32.68.95.68 1.92 0 1.38-.01 2.49-.01 2.83 0 .26.18.58.69.48A10.05 10.05 0 0 0 22 12.26C22 6.58 17.52 2 12 2Z"/></svg>
|
||||
<span>Grok2API</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="login-title" data-i18n="login.adminTitle">管理后台</div>
|
||||
<div class="login-subtitle" data-i18n="login.adminSubtitle">请输入后台密码以继续</div>
|
||||
<div class="login-form">
|
||||
<input type="password" id="api-key-input" placeholder="后台密码 (app_key)" data-i18n-placeholder="login.adminPlaceholder" class="input" style="height:32px;font-size:12px">
|
||||
<button onclick="login()" class="btn btn-primary w-full" style="font-size:12px" data-i18n="login.continue">继续</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="app-footer"></div>
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/admin/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,186 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="token.pageTitle">Grok2API - Token 管理</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="admin"></div>
|
||||
|
||||
<main class="page-body fade-in">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold" data-i18n="token.title">Token 列表</h2>
|
||||
<p class="text-sm text-muted mt-1" data-i18n="token.subtitle">管理 Grok2API 的 Token 服务号池。</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="openImportModal()" class="btn btn-outline gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
|
||||
<span data-i18n="token.import">导入</span>
|
||||
</button>
|
||||
<button onclick="addToken()" class="btn btn-primary gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
|
||||
<span data-i18n="token.add">添加</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- Stats -->
|
||||
<div class="grid-4 mb-6" id="stats-container">
|
||||
<div class="card stat-card"><div class="stat-value" id="stat-total">-</div><div class="stat-label" data-i18n="token.statTotal">Token 总数</div></div>
|
||||
<div class="card stat-card"><div class="stat-value text-success" id="stat-active">-</div><div class="stat-label" data-i18n="token.statActive">正常</div></div>
|
||||
<div class="card stat-card"><div class="stat-value text-orange" id="stat-cooling">-</div><div class="stat-label" data-i18n="token.statCooling">限流</div></div>
|
||||
<div class="card stat-card"><div class="stat-value text-error" id="stat-invalid">-</div><div class="stat-label" data-i18n="token.statInvalid">失效</div></div>
|
||||
<div class="card stat-card"><div class="stat-value" id="stat-chat-quota">-</div><div class="stat-label" data-i18n="token.statChatQuota">Chat 剩余</div></div>
|
||||
<div class="card stat-card"><div class="stat-value text-blue" id="stat-image-quota">-</div><div class="stat-label" data-i18n="token.statImageQuota">Image 剩余</div></div>
|
||||
<div class="card stat-card"><div class="stat-value text-subtle" data-i18n="token.statVideoUnavailable">-</div><div class="stat-label" data-i18n="token.statVideoQuota">Video 剩余</div></div>
|
||||
<div class="card stat-card"><div class="stat-value" id="stat-total-calls">-</div><div class="stat-label" data-i18n="token.statTotalCalls">总调用</div></div>
|
||||
</div>
|
||||
|
||||
<!-- Tabs -->
|
||||
<div class="tabs mb-4" id="status-tabs">
|
||||
<button class="tab-item active" data-filter="all" onclick="filterByStatus('all')"><span data-i18n="token.tabAll">全部</span> <span class="badge" id="tab-count-all">0</span></button>
|
||||
<button class="tab-item" data-filter="active" onclick="filterByStatus('active')"><span data-i18n="token.tabActive">正常</span> <span class="badge badge-green" id="tab-count-active">0</span></button>
|
||||
<button class="tab-item" data-filter="cooling" onclick="filterByStatus('cooling')"><span data-i18n="token.tabCooling">限流</span> <span class="badge badge-orange" id="tab-count-cooling">0</span></button>
|
||||
<button class="tab-item" data-filter="expired" onclick="filterByStatus('expired')"><span data-i18n="token.tabExpired">失效</span> <span class="badge badge-red" id="tab-count-expired">0</span></button>
|
||||
<span class="tab-sep"></span>
|
||||
<button class="tab-item" data-filter="nsfw" onclick="filterByStatus('nsfw')"><span data-i18n="token.tabNsfw">NSFW</span> <span class="badge badge-purple" id="tab-count-nsfw">0</span></button>
|
||||
<button class="tab-item" data-filter="no-nsfw" onclick="filterByStatus('no-nsfw')"><span data-i18n="token.tabNoNsfw">未开NSFW</span> <span class="badge" id="tab-count-no-nsfw">0</span></button>
|
||||
</div>
|
||||
|
||||
<!-- Table -->
|
||||
<div class="table-shell mb-4">
|
||||
<div class="pagination-bar">
|
||||
<div class="pagination-left">
|
||||
<button id="page-prev" class="pagination-icon-btn" onclick="goPrevPage()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg></button>
|
||||
<div id="pagination-info" class="pagination-info">0 / 0</div>
|
||||
<button id="page-next" class="pagination-icon-btn" onclick="goNextPage()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg></button>
|
||||
</div>
|
||||
<div class="pagination-right">
|
||||
<div id="select-all-wrap" class="select-menu-wrap">
|
||||
<button id="select-all-trigger" class="pagination-action-btn" onclick="handleSelectAllPrimary(event)">
|
||||
<span id="select-all-label" data-i18n="common.selectAll">全选</span>
|
||||
<svg id="select-all-caret" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
|
||||
</button>
|
||||
<div id="select-all-popover" class="select-all-popover hidden">
|
||||
<button class="select-all-option" onclick="selectVisibleAllFromMenu()" data-i18n="token.selectPage">本页</button>
|
||||
<button class="select-all-option" onclick="selectAllFilteredFromMenu()" data-i18n="token.selectAllFiltered">全部</button>
|
||||
</div>
|
||||
</div>
|
||||
<select id="page-size" class="pagination-size-select" onchange="changePageSize()">
|
||||
<option value="50" selected>50</option>
|
||||
<option value="100">100</option>
|
||||
<option value="200">200</option>
|
||||
<option value="500">500</option>
|
||||
<option value="1000">1000</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table style="min-width:860px">
|
||||
<thead><tr>
|
||||
<th style="width:40px;text-align:center"><input type="checkbox" id="select-all" class="checkbox" onclick="toggleSelectAll()"></th>
|
||||
<th style="width:220px" data-i18n="token.tableToken">Token</th>
|
||||
<th style="width:80px;text-align:center" data-i18n="token.tableType">类型</th>
|
||||
<th style="width:100px;text-align:center" data-i18n="token.tableStatus">状态</th>
|
||||
<th style="width:60px;text-align:center" id="th-quota" data-i18n="token.tableQuota">额度</th>
|
||||
<th data-i18n="token.tableNote">备注</th>
|
||||
<th style="width:160px;text-align:center" data-i18n="token.tableActions">操作</th>
|
||||
</tr></thead>
|
||||
<tbody id="token-table-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="loading" class="text-center py-2 text-muted" data-i18n="common.loading">加载中...</div>
|
||||
<div id="empty-state" class="hidden table-empty" data-i18n="token.emptyState">暂无 Token</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Batch Toolbar -->
|
||||
<div id="batch-actions" class="batch-toolbar">
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<span class="text-muted" data-i18n="common.selected">已选</span>
|
||||
<span class="badge" id="selected-count">0</span>
|
||||
</div>
|
||||
<span class="toolbar-sep"></span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button id="btn-batch-export" onclick="batchExport()" class="btn btn-ghost btn-sm" data-i18n="token.batchExport">导出</button>
|
||||
<button id="btn-batch-update" onclick="batchUpdate()" class="btn btn-ghost btn-sm" data-i18n="token.batchRefresh">刷新</button>
|
||||
<button id="btn-batch-disable" onclick="batchDisableTokens()" class="btn btn-ghost btn-sm" data-i18n="token.batchDisable">禁用</button>
|
||||
<button id="btn-batch-enable" onclick="batchEnableTokens()" class="btn btn-ghost btn-sm" data-i18n="token.batchEnable">启用</button>
|
||||
<button id="btn-batch-nsfw" onclick="batchEnableNSFW()" class="btn btn-ghost btn-sm" disabled>NSFW</button>
|
||||
<button id="btn-batch-delete" onclick="batchDelete()" class="btn btn-danger btn-sm" data-i18n="token.batchDelete">删除</button>
|
||||
</div>
|
||||
<div id="batch-progress" class="hidden flex items-center gap-2 text-xs text-muted">
|
||||
<span class="toolbar-sep"></span>
|
||||
<span id="batch-progress-text"></span>
|
||||
<button id="btn-stop-action" class="batch-link hidden" onclick="stopBatchRefresh()" data-i18n="common.stop">终止</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Import Modal -->
|
||||
<div id="import-modal" class="modal-overlay hidden">
|
||||
<div class="modal-content modal-lg">
|
||||
<div class="modal-header">
|
||||
<h3 class="modal-title" data-i18n="token.importTitle">批量导入</h3>
|
||||
<button onclick="closeImportModal()" class="modal-close"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div><label class="modal-label mb-2" data-i18n="token.importTargetPool">目标 Pool</label><select id="import-pool" class="input"><option value="ssoBasic">ssoBasic</option><option value="ssoSuper">ssoSuper</option></select></div>
|
||||
<div><label class="modal-label mb-2" data-i18n="token.importTokenList">Token 列表</label><textarea id="import-text" class="input font-mono" rows="8" placeholder="一行一个" data-i18n-placeholder="token.importPlaceholder"></textarea></div>
|
||||
<div class="flex justify-end gap-2"><button onclick="closeImportModal()" class="btn btn-outline btn-sm" data-i18n="common.cancel">取消</button><button onclick="submitImport()" class="btn btn-primary btn-sm" data-i18n="token.startImport">开始导入</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Edit Modal -->
|
||||
<div id="edit-modal" class="modal-overlay hidden">
|
||||
<div class="modal-content modal-md">
|
||||
<div class="modal-header">
|
||||
<h3 class="modal-title" data-i18n="token.editTitle">编辑 Token</h3>
|
||||
<button onclick="closeEditModal()" class="modal-close"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<input type="hidden" id="edit-original-token"><input type="hidden" id="edit-original-pool">
|
||||
<div><label class="modal-label mb-2" data-i18n="token.tableToken">Token</label><input type="text" id="edit-token-display" class="input font-mono" disabled></div>
|
||||
<div><label class="modal-label mb-2" data-i18n="token.editType">类型</label><select id="edit-pool" class="input"><option value="ssoBasic">ssoBasic</option><option value="ssoSuper">ssoSuper</option></select></div>
|
||||
<div><label class="modal-label mb-2" data-i18n="token.editQuota">额度</label><input type="number" id="edit-quota" class="input" min="0"></div>
|
||||
<div><label class="modal-label mb-2" data-i18n="token.editNote">备注</label><input type="text" id="edit-note" class="input" maxlength="50" placeholder="可选"></div>
|
||||
<div class="flex justify-end gap-2"><button onclick="closeEditModal()" class="btn btn-outline btn-sm" data-i18n="common.cancel">取消</button><button onclick="saveEdit()" class="btn btn-primary btn-sm" data-i18n="common.save">保存</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Confirm Dialog -->
|
||||
<div id="confirm-dialog" class="modal-overlay hidden">
|
||||
<div class="modal-content modal-md">
|
||||
<div style="padding:8px 0">
|
||||
<div class="font-semibold mb-2" data-i18n="common.pleaseConfirm">请确认</div>
|
||||
<div id="confirm-message" class="text-sm text-muted"></div>
|
||||
<div class="flex justify-end gap-2 mt-4">
|
||||
<button id="confirm-cancel" class="btn btn-outline btn-sm" data-i18n="common.cancel">取消</button>
|
||||
<button id="confirm-ok" class="btn btn-danger btn-sm" data-i18n="common.ok">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/ui.js"></script>
|
||||
<script src="/static/js/core/sse.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/admin/token.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,579 +0,0 @@
|
||||
/* ============================================================
|
||||
Grok2API — Unified Design System
|
||||
Pure CSS, zero dependencies. Replaces Tailwind CDN + all page CSS.
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 1. Variables ---------- */
|
||||
:root {
|
||||
--bg: #fafafa;
|
||||
--bg-card: #fff;
|
||||
--fg: #000;
|
||||
--fg-muted: #666;
|
||||
--fg-subtle: #999;
|
||||
--fg-dim: #444;
|
||||
--border: #e5e5e5;
|
||||
--border-hover: #000;
|
||||
--radius: 6px;
|
||||
--radius-lg: 10px;
|
||||
--radius-xl: 14px;
|
||||
--success: #059669;
|
||||
--success-bg: #ecfdf5;
|
||||
--error: #dc2626;
|
||||
--error-bg: #fef2f2;
|
||||
--warning: #f5a623;
|
||||
--blue: #0070f3;
|
||||
--purple: #7c3aed;
|
||||
--orange: #f97316;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,.06);
|
||||
--shadow-md: 0 4px 16px rgba(0,0,0,.08);
|
||||
--shadow-lg: 0 20px 50px rgba(0,0,0,.08);
|
||||
--font-sans: 'Geist Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
--font-mono: 'Geist Mono', ui-monospace, 'SF Mono', monospace;
|
||||
--header-h: 56px;
|
||||
--max-w: 960px;
|
||||
}
|
||||
|
||||
/* ---------- 2. Reset ---------- */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
min-height: 100vh;
|
||||
}
|
||||
a { color: inherit; text-decoration: none; }
|
||||
button, input, select, textarea {
|
||||
font: inherit; border: none; outline: none; background: none; color: inherit;
|
||||
}
|
||||
button { cursor: pointer; }
|
||||
img, video { display: block; max-width: 100%; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
::-webkit-scrollbar { width: 6px; height: 6px; }
|
||||
::-webkit-scrollbar-thumb { background: #ccc; border-radius: 3px; }
|
||||
.hidden { display: none !important; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }
|
||||
.font-mono { font-family: var(--font-mono); }
|
||||
|
||||
/* ---------- 3. Layout ---------- */
|
||||
.page { display: flex; flex-direction: column; min-height: 100vh; }
|
||||
.page-body { flex: 1; max-width: var(--max-w); width: 100%; margin: 0 auto; padding: calc(var(--header-h) + 24px) 24px 64px; }
|
||||
.page-body.wide { max-width: 1060px; }
|
||||
|
||||
/* ---------- 4. Header ---------- */
|
||||
.app-header {
|
||||
position: fixed; top: 0; left: 0; right: 0; z-index: 40;
|
||||
height: var(--header-h);
|
||||
background: rgba(250,250,250,.85);
|
||||
backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.app-header-inner {
|
||||
max-width: var(--max-w); margin: 0 auto;
|
||||
height: 100%; padding: 0 24px;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
}
|
||||
.header-left { display: flex; align-items: center; gap: 16px; min-width: 0; }
|
||||
.header-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
|
||||
.brand { display: inline-flex; align-items: center; gap: 6px; font-weight: 600; font-size: 14px; white-space: nowrap; }
|
||||
.brand svg { width: 16px; height: 16px; fill: currentColor; }
|
||||
.brand-sub { font-size: 12px; color: var(--fg-muted); }
|
||||
.header-sep { width: 1px; height: 16px; background: var(--border); flex-shrink: 0; }
|
||||
.nav-link { font-size: 13px; color: var(--fg-muted); transition: color .15s; white-space: nowrap; }
|
||||
.nav-link:hover { color: var(--fg); }
|
||||
.nav-link.active { color: var(--fg); font-weight: 500; }
|
||||
.header-btn {
|
||||
height: 26px; padding: 0 10px; border-radius: 999px;
|
||||
border: 1px solid var(--border); font-size: 11px; font-weight: 500;
|
||||
color: var(--fg-muted); display: inline-flex; align-items: center; transition: all .15s;
|
||||
}
|
||||
.header-btn:hover { border-color: var(--fg); color: var(--fg); }
|
||||
.header-btn.ready { background: #ecfdf3; border-color: #a7f3d0; color: #047857; }
|
||||
|
||||
/* ---------- 5. Footer ---------- */
|
||||
.app-footer {
|
||||
position: fixed; right: 16px; bottom: 12px; z-index: 10;
|
||||
font-size: 12px; color: var(--fg-subtle);
|
||||
}
|
||||
.app-footer a:hover { color: var(--fg); }
|
||||
|
||||
/* ---------- 6. Buttons ---------- */
|
||||
.btn {
|
||||
height: 32px; padding: 0 14px; border-radius: 8px;
|
||||
font-size: 13px; font-weight: 600; display: inline-flex;
|
||||
align-items: center; justify-content: center; gap: 6px;
|
||||
transition: opacity .15s; white-space: nowrap;
|
||||
}
|
||||
.btn:disabled { opacity: .45; pointer-events: none; }
|
||||
.btn-primary { background: var(--fg); color: var(--bg-card); }
|
||||
.btn-primary:hover { opacity: .88; }
|
||||
.btn-outline { border: 1px solid var(--border); color: var(--fg); }
|
||||
.btn-outline:hover { border-color: var(--fg); }
|
||||
.btn-danger { background: var(--error); color: #fff; }
|
||||
.btn-danger:hover { opacity: .88; }
|
||||
.btn-ghost { color: var(--fg-muted); }
|
||||
.btn-ghost:hover { color: var(--fg); background: rgba(0,0,0,.04); }
|
||||
.btn-sm { height: 26px; padding: 0 10px; font-size: 12px; font-weight: 500; }
|
||||
.btn-icon { width: 32px; padding: 0; }
|
||||
.btn-icon svg { width: 14px; height: 14px; }
|
||||
.btn-round { border-radius: 999px; }
|
||||
|
||||
/* ---------- 7. Inputs ---------- */
|
||||
.input {
|
||||
width: 100%; height: 34px; padding: 0 10px;
|
||||
font-size: 13px; border-radius: 8px;
|
||||
border: 1px solid var(--border); background: var(--bg-card);
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: #bbb; box-shadow: 0 0 0 2px rgba(0,0,0,.04); }
|
||||
.input:disabled { background: #f5f5f5; color: var(--fg-muted); cursor: not-allowed; }
|
||||
.input::placeholder { color: var(--fg-subtle); }
|
||||
textarea.input { height: auto; padding: 8px 10px; resize: vertical; }
|
||||
select.input { cursor: pointer; appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 28px; }
|
||||
|
||||
/* ---------- 8. Cards ---------- */
|
||||
.card {
|
||||
background: var(--bg-card); border-radius: var(--radius-lg);
|
||||
border: 1px solid transparent; transition: border-color .15s;
|
||||
}
|
||||
.card:hover { border-color: var(--border); }
|
||||
.stat-card { padding: 14px 18px; }
|
||||
.stat-value { font-size: 20px; font-weight: 600; line-height: 1.2; letter-spacing: -.01em; }
|
||||
.stat-label { font-size: 12px; color: var(--fg-muted); margin-top: 2px; }
|
||||
|
||||
/* ---------- 9. Table ---------- */
|
||||
.table-shell { background: var(--bg-card); border-radius: var(--radius-lg); overflow: hidden; }
|
||||
.table-shell table { min-width: 100%; }
|
||||
.table-shell th {
|
||||
font-size: 12px; font-weight: 500; color: var(--fg-muted);
|
||||
padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--border);
|
||||
background: #fafafa; white-space: nowrap;
|
||||
}
|
||||
.table-shell td {
|
||||
font-size: 13px; padding: 10px 12px;
|
||||
border-bottom: 1px solid #f5f5f5; vertical-align: middle;
|
||||
}
|
||||
.table-shell tr:last-child td { border-bottom: none; }
|
||||
.table-shell tr.row-selected { background: #f8f8ff; }
|
||||
.table-empty { color: var(--fg-muted); font-size: 12px; padding: 48px 0; text-align: center; }
|
||||
.text-center { text-align: center; }
|
||||
.text-right { text-align: right; }
|
||||
|
||||
/* ---------- 10. Badges ---------- */
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; height: 20px;
|
||||
padding: 0 8px; border-radius: 999px; font-size: 11px; font-weight: 500;
|
||||
background: #f5f5f5; color: var(--fg-dim);
|
||||
}
|
||||
.badge-green { background: #ecfdf5; color: #059669; }
|
||||
.badge-orange { background: #fff7ed; color: #ea580c; }
|
||||
.badge-red { background: #fef2f2; color: #dc2626; }
|
||||
.badge-purple { background: #f5f3ff; color: #7c3aed; }
|
||||
.badge-blue { background: #eff6ff; color: #2563eb; }
|
||||
|
||||
/* ---------- 11. Tabs ---------- */
|
||||
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); overflow-x: auto; padding-bottom: -1px; }
|
||||
.tabs::-webkit-scrollbar { display: none; }
|
||||
.tab-item {
|
||||
padding: 8px 12px; font-size: 13px; color: var(--fg-muted);
|
||||
border-bottom: 2px solid transparent; transition: all .15s;
|
||||
display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; flex-shrink: 0;
|
||||
}
|
||||
.tab-item:hover { color: var(--fg); }
|
||||
.tab-item.active { color: var(--fg); font-weight: 500; border-bottom-color: var(--fg); }
|
||||
.tab-sep { width: 1px; height: 16px; background: var(--border); align-self: center; flex-shrink: 0; }
|
||||
|
||||
/* ---------- 12. Modal ---------- */
|
||||
.modal-overlay {
|
||||
position: fixed; inset: 0; z-index: 100;
|
||||
background: rgba(0,0,0,.4); display: flex;
|
||||
align-items: center; justify-content: center; padding: 24px;
|
||||
opacity: 0; transition: opacity .2s;
|
||||
}
|
||||
.modal-overlay.is-open { opacity: 1; }
|
||||
.modal-content {
|
||||
background: var(--bg-card); border-radius: var(--radius-xl);
|
||||
width: 100%; box-shadow: var(--shadow-lg); padding: 20px 24px;
|
||||
transform: translateY(8px); transition: transform .2s;
|
||||
}
|
||||
.modal-overlay.is-open .modal-content { transform: translateY(0); }
|
||||
.modal-md { max-width: 460px; }
|
||||
.modal-lg { max-width: 560px; }
|
||||
.modal-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
|
||||
.modal-title { font-size: 15px; font-weight: 600; }
|
||||
.modal-close { width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 6px; color: var(--fg-muted); }
|
||||
.modal-close:hover { background: #f5f5f5; color: var(--fg); }
|
||||
.modal-label { font-size: 12px; font-weight: 500; color: var(--fg-dim); }
|
||||
|
||||
/* ---------- 13. Toast ---------- */
|
||||
.toast-container {
|
||||
position: fixed; top: 24px; left: 50%; transform: translateX(-50%);
|
||||
z-index: 200; display: flex; flex-direction: column; gap: 10px;
|
||||
pointer-events: none; align-items: center;
|
||||
}
|
||||
.toast {
|
||||
background: var(--bg-card); border: 1px solid var(--border);
|
||||
border-radius: var(--radius); padding: 10px 14px;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
min-width: 260px; max-width: 400px; pointer-events: auto;
|
||||
animation: toastIn .3s cubic-bezier(.16,1,.3,1) forwards;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
.toast.out { animation: toastOut .2s ease forwards; }
|
||||
.toast-icon {
|
||||
flex-shrink: 0; width: 20px; height: 20px;
|
||||
display: flex; align-items: center; justify-content: center; border-radius: 50%;
|
||||
}
|
||||
.toast-success .toast-icon { background: var(--success-bg); color: var(--success); }
|
||||
.toast-error .toast-icon { background: var(--error-bg); color: var(--error); }
|
||||
.toast-content { flex: 1; font-size: 12px; font-weight: 500; }
|
||||
@keyframes toastIn { from { opacity:0; transform: translateY(16px) scale(.96); } to { opacity:1; transform: translateY(0) scale(1); } }
|
||||
@keyframes toastOut { from { opacity:1; } to { opacity:0; transform: translateY(8px) scale(.96); } }
|
||||
|
||||
/* ---------- 14. Notice dialog ---------- */
|
||||
.notice-backdrop {
|
||||
position: fixed; inset: 0; background: rgba(0,0,0,.35);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
z-index: 200; padding: 24px;
|
||||
}
|
||||
.notice-dialog {
|
||||
background: var(--bg-card); border-radius: 12px;
|
||||
width: min(520px, 92vw); box-shadow: var(--shadow-lg); padding: 20px 22px 16px;
|
||||
}
|
||||
.notice-dialog-title { font-size: 14px; font-weight: 600; margin-bottom: 8px; }
|
||||
.notice-dialog-content { font-size: 13px; line-height: 1.6; color: var(--fg-dim); }
|
||||
.notice-dialog-actions { display: flex; justify-content: flex-end; margin-top: 16px; }
|
||||
|
||||
/* ---------- 15. Login ---------- */
|
||||
.login-body { min-height: 100vh; display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden; }
|
||||
.login-bg {
|
||||
position: fixed; inset: 0; z-index: 0;
|
||||
background: radial-gradient(600px 280px at 20% 20%, rgba(0,0,0,.06), transparent 60%),
|
||||
radial-gradient(500px 260px at 80% 80%, rgba(0,0,0,.04), transparent 55%),
|
||||
linear-gradient(180deg, #fafafa, #f6f6f6);
|
||||
}
|
||||
.login-shell { position: relative; z-index: 1; width: min(420px, 92vw); padding: 24px; }
|
||||
.login-card {
|
||||
background: var(--bg-card); border: 1px solid transparent; border-radius: var(--radius-xl);
|
||||
padding: 22px; box-shadow: var(--shadow-lg); transition: border-color .2s, box-shadow .2s;
|
||||
}
|
||||
.login-card:hover { border-color: var(--fg); }
|
||||
.login-brand { font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: var(--fg-muted); font-weight: 600; }
|
||||
.login-title { margin-top: 6px; font-size: 18px; font-weight: 600; }
|
||||
.login-subtitle { margin-top: 4px; font-size: 12px; color: var(--fg-muted); }
|
||||
.login-form { margin-top: 16px; display: grid; gap: 10px; }
|
||||
|
||||
/* ---------- 16. Config page ---------- */
|
||||
.config-section { margin-bottom: 32px; }
|
||||
.config-section-title { font-size: 15px; font-weight: 600; margin-bottom: 8px; }
|
||||
.config-section-desc { font-size: 13px; color: var(--fg-muted); margin-bottom: 16px; }
|
||||
.config-grid { display: grid; gap: 16px; }
|
||||
.config-field { display: grid; gap: 4px; }
|
||||
.config-field-title { font-size: 13px; font-weight: 500; }
|
||||
.config-field-desc { font-size: 12px; color: var(--fg-subtle); line-height: 1.4; }
|
||||
.config-field-input { margin-top: 4px; }
|
||||
.config-field.has-action { display: flex; align-items: flex-end; gap: 8px; }
|
||||
.config-field.has-action .config-field-input { flex: 1; }
|
||||
|
||||
/* ---------- 17. Token page ---------- */
|
||||
.pagination-bar {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 12px;
|
||||
}
|
||||
.pagination-left { display: flex; align-items: center; gap: 8px; }
|
||||
.pagination-right { display: flex; align-items: center; gap: 8px; }
|
||||
.pagination-info { color: var(--fg-muted); font-size: 12px; }
|
||||
.pagination-icon-btn {
|
||||
width: 28px; height: 28px; display: flex; align-items: center; justify-content: center;
|
||||
border-radius: 6px; color: var(--fg-muted); transition: all .15s;
|
||||
}
|
||||
.pagination-icon-btn:hover { background: #f5f5f5; color: var(--fg); }
|
||||
.pagination-icon-btn:disabled { opacity: .3; pointer-events: none; }
|
||||
.pagination-size-select {
|
||||
height: 28px; padding: 0 24px 0 8px; border-radius: 6px;
|
||||
border: 1px solid var(--border); font-size: 12px; cursor: pointer;
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 6px center;
|
||||
}
|
||||
.select-menu-wrap { position: relative; }
|
||||
.select-all-popover {
|
||||
position: absolute; top: 100%; right: 0; margin-top: 4px;
|
||||
background: var(--bg-card); border: 1px solid var(--border);
|
||||
border-radius: 8px; padding: 4px; min-width: 120px;
|
||||
box-shadow: var(--shadow-md); z-index: 30;
|
||||
}
|
||||
.select-all-option {
|
||||
display: block; width: 100%; padding: 6px 10px; text-align: left;
|
||||
font-size: 12px; border-radius: 6px; color: var(--fg-dim);
|
||||
}
|
||||
.select-all-option:hover { background: #f5f5f5; color: var(--fg); }
|
||||
.pagination-action-btn {
|
||||
height: 28px; padding: 0 10px; border-radius: 6px;
|
||||
border: 1px solid var(--border); font-size: 12px;
|
||||
display: inline-flex; align-items: center; gap: 4px; color: var(--fg-muted);
|
||||
}
|
||||
.pagination-action-btn:hover { border-color: var(--fg); color: var(--fg); }
|
||||
.pagination-action-btn.is-active { background: var(--fg); color: var(--bg-card); border-color: var(--fg); }
|
||||
|
||||
/* checkbox */
|
||||
.checkbox { width: 14px; height: 14px; cursor: pointer; accent-color: var(--fg); }
|
||||
|
||||
/* Batch toolbar */
|
||||
.batch-toolbar {
|
||||
position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%);
|
||||
z-index: 30; background: var(--bg-card); border: 1px solid var(--border);
|
||||
border-radius: 999px; padding: 6px 14px;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
box-shadow: var(--shadow-md); white-space: nowrap;
|
||||
touch-action: none; user-select: none;
|
||||
}
|
||||
.toolbar-sep { width: 1px; height: 16px; background: var(--border); flex-shrink: 0; }
|
||||
.batch-link { font-size: 12px; color: var(--fg-muted); text-decoration: underline; }
|
||||
.batch-link:hover { color: var(--fg); }
|
||||
|
||||
/* ---------- 18. Cache page ---------- */
|
||||
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
|
||||
.grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
|
||||
|
||||
/* ---------- 19. Toggle switch ---------- */
|
||||
.toggle { position: relative; display: inline-flex; align-items: center; cursor: pointer; }
|
||||
.toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.toggle-track {
|
||||
width: 36px; height: 20px; border-radius: 999px;
|
||||
background: var(--fg-subtle); transition: background .2s;
|
||||
}
|
||||
.toggle-track::after {
|
||||
content: ''; position: absolute; top: 2px; left: 2px;
|
||||
width: 16px; height: 16px; border-radius: 50%;
|
||||
background: #fff; transition: transform .2s;
|
||||
}
|
||||
.toggle input:checked + .toggle-track { background: var(--fg); }
|
||||
.toggle input:checked + .toggle-track::after { transform: translateX(16px); }
|
||||
|
||||
/* ---------- 20. Imagine page ---------- */
|
||||
.waterfall { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.waterfall-item {
|
||||
border-radius: var(--radius); overflow: hidden;
|
||||
cursor: pointer; position: relative; flex: 0 0 auto;
|
||||
}
|
||||
.waterfall-item img { width: 100%; height: auto; display: block; }
|
||||
.lightbox {
|
||||
position: fixed; inset: 0; z-index: 100;
|
||||
background: rgba(0,0,0,.85); display: flex;
|
||||
align-items: center; justify-content: center;
|
||||
}
|
||||
.lightbox img { max-width: 90vw; max-height: 90vh; object-fit: contain; border-radius: 8px; }
|
||||
.lightbox-close {
|
||||
position: absolute; top: 16px; right: 16px;
|
||||
width: 36px; height: 36px; border-radius: 50%;
|
||||
background: rgba(255,255,255,.2); color: #fff;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
|
||||
/* ---------- 21. Shared card components ---------- */
|
||||
.card-title { font-size: 14px; font-weight: 600; margin-bottom: 12px; }
|
||||
.meta-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px; }
|
||||
.meta-item { background: #fafafa; border-radius: 6px; padding: 8px 10px; }
|
||||
.meta-label { font-size: 10px; color: var(--fg-subtle); text-transform: uppercase; letter-spacing: .05em; }
|
||||
.meta-value { font-size: 12px; font-weight: 500; margin-top: 2px; }
|
||||
.status-text { font-size: 12px; color: var(--fg-subtle); }
|
||||
.status-text.connected { color: var(--success); }
|
||||
.status-text.connecting { color: var(--warning); }
|
||||
.status-text.error { color: var(--error); }
|
||||
.field-label { font-size: 12px; font-weight: 500; color: var(--fg-dim); display: block; margin-bottom: 4px; }
|
||||
.range-value { font-size: 12px; font-weight: 600; font-family: var(--font-mono); }
|
||||
|
||||
/* ---------- 21b. Voice page ---------- */
|
||||
.voice-grid { display: grid; grid-template-columns: 1fr 320px; gap: 16px; }
|
||||
.voice-card { background: var(--bg-card); border-radius: var(--radius-lg); padding: 16px; margin-bottom: 16px; border: 1px solid var(--border); }
|
||||
.voice-hint { font-size: 11px; color: var(--fg-subtle); }
|
||||
.voice-log { max-height: 300px; overflow-y: auto; background: #1a1a1a; color: #ccc; border-radius: var(--radius); padding: 10px; font-family: var(--font-mono); font-size: 12px; }
|
||||
.voice-log p { margin-bottom: 2px; }
|
||||
.voice-log .log-error { color: #f87171; }
|
||||
.voice-log .log-warn { color: #fbbf24; }
|
||||
.voice-log-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
|
||||
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.visualizer { display: flex; align-items: flex-end; gap: 2px; height: 40px; }
|
||||
.visualizer .bar { width: 4px; background: var(--fg); border-radius: 2px; transition: height .15s; height: 6px; }
|
||||
.log-box {
|
||||
background: #1a1a1a; color: #ccc; border-radius: var(--radius);
|
||||
padding: 12px; font-family: var(--font-mono); font-size: 12px;
|
||||
max-height: 300px; overflow-y: auto;
|
||||
}
|
||||
.log-box p { margin-bottom: 2px; }
|
||||
.log-box .log-error { color: #f87171; }
|
||||
.log-box .log-warn { color: #fbbf24; }
|
||||
|
||||
/* ---------- 22. Video page ---------- */
|
||||
.progress-bar { height: 6px; background: #f0f0f0; border-radius: 3px; overflow: hidden; position: relative; }
|
||||
.progress-fill { height: 100%; background: var(--fg); border-radius: 3px; transition: width .3s; width: 0; }
|
||||
.progress-bar.indeterminate .progress-fill {
|
||||
width: 40% !important; animation: indeterminate 1.4s ease infinite;
|
||||
}
|
||||
@keyframes indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(350%); } }
|
||||
.video-item { border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; margin-bottom: 12px; }
|
||||
.video-item.is-pending { opacity: .6; }
|
||||
.video-item-bar { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid #f5f5f5; }
|
||||
.video-item-title { font-size: 13px; font-weight: 500; }
|
||||
.video-item-actions { display: flex; gap: 6px; }
|
||||
.video-item-body { padding: 12px 14px; }
|
||||
.video-item-body video { width: 100%; border-radius: var(--radius); }
|
||||
.video-item-placeholder { text-align: center; padding: 32px 0; color: var(--fg-subtle); font-size: 13px; }
|
||||
.video-item-link { padding: 0 14px 10px; font-size: 11px; color: var(--fg-subtle); word-break: break-all; }
|
||||
|
||||
/* ---------- 23. Chat page ---------- */
|
||||
.chat-layout { display: flex; height: 100vh; overflow: hidden; }
|
||||
.chat-sidebar {
|
||||
width: 260px; flex-shrink: 0; background: #f8f8f8;
|
||||
border-right: 1px solid var(--border); display: flex; flex-direction: column;
|
||||
transition: margin-left .2s;
|
||||
}
|
||||
.chat-sidebar.collapsed { margin-left: -260px; }
|
||||
.chat-sidebar-header { padding: 12px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border); }
|
||||
.chat-sidebar-list { flex: 1; overflow-y: auto; padding: 8px; }
|
||||
.session-item {
|
||||
padding: 8px 12px; border-radius: var(--radius); font-size: 13px;
|
||||
cursor: pointer; margin-bottom: 2px; display: flex; align-items: center; justify-content: space-between;
|
||||
}
|
||||
.session-item:hover { background: #f0f0f0; }
|
||||
.session-item.active { background: #e8e8e8; font-weight: 500; }
|
||||
.chat-main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
.chat-header { padding: 12px 16px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; }
|
||||
.chat-messages { flex: 1; overflow-y: auto; padding: 16px; }
|
||||
.chat-input-bar { padding: 12px 16px; border-top: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-end; }
|
||||
.chat-input-bar textarea { flex: 1; resize: none; max-height: 120px; }
|
||||
.chat-bubble { margin-bottom: 16px; max-width: 80%; }
|
||||
.chat-bubble.user { margin-left: auto; }
|
||||
.chat-bubble-inner {
|
||||
padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.6;
|
||||
}
|
||||
.chat-bubble.user .chat-bubble-inner { background: var(--fg); color: var(--bg-card); border-bottom-right-radius: 4px; }
|
||||
.chat-bubble.assistant .chat-bubble-inner { background: #f0f0f0; border-bottom-left-radius: 4px; }
|
||||
.chat-bubble-inner pre { background: #1a1a1a; color: #e5e5e5; padding: 12px; border-radius: 6px; overflow-x: auto; font-size: 13px; margin: 8px 0; }
|
||||
.chat-bubble-inner code { font-family: var(--font-mono); font-size: .9em; }
|
||||
.chat-bubble-inner p { margin-bottom: 8px; }
|
||||
.chat-bubble-inner p:last-child { margin-bottom: 0; }
|
||||
.chat-empty { text-align: center; padding: 80px 24px; color: var(--fg-subtle); }
|
||||
|
||||
/* ---------- 23b. Divider ---------- */
|
||||
.divider { height: 1px; background: var(--border); margin-bottom: 24px; }
|
||||
|
||||
/* ---------- 23c. Compat aliases (for JS-created elements) ---------- */
|
||||
.geist-button { height:32px;font-size:13px;font-weight:600;background:#000;color:#fff;border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:opacity .15s;white-space:nowrap; }
|
||||
.geist-button:hover { opacity:.88; }
|
||||
.geist-button:disabled { opacity:.45;pointer-events:none; }
|
||||
.geist-button-outline { height:32px;font-size:13px;font-weight:500;background:transparent;color:var(--fg);border:1px solid var(--border);border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:all .15s;white-space:nowrap; }
|
||||
.geist-button-outline:hover { border-color:#000; }
|
||||
.geist-button-outline:disabled { opacity:.45;pointer-events:none; }
|
||||
.geist-button-danger { height:32px;font-size:13px;font-weight:500;background:var(--error);color:#fff;border-radius:8px;padding:0 14px;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:opacity .15s;white-space:nowrap; }
|
||||
.geist-button-danger:hover { opacity:.88; }
|
||||
.geist-input { width:100%;font-size:13px;border-radius:8px;padding:6px 10px;border:1px solid var(--border);background:#fff;transition:border-color .15s; }
|
||||
.geist-input:focus { border-color:#bbb; }
|
||||
.geist-input:disabled { background:#f5f5f5;color:var(--fg-muted); }
|
||||
.tracking-tight { letter-spacing: -0.025em; }
|
||||
.hover\:bg-gray-100:hover { background: #f3f4f6; }
|
||||
.hover\:bg-red-100:hover { background: #fee2e2; }
|
||||
.min-h-screen { min-height: 100vh; }
|
||||
.flex-1 { flex: 1; }
|
||||
.container { width: 100%; margin: 0 auto; }
|
||||
.mx-auto { margin-left: auto; margin-right: auto; }
|
||||
.max-w-5xl { max-width: 960px; }
|
||||
.px-6 { padding-left: 24px; padding-right: 24px; }
|
||||
.py-8 { padding-top: 32px; padding-bottom: 32px; }
|
||||
.inline-flex { display: inline-flex; }
|
||||
.justify-center { justify-content: center; }
|
||||
.rounded-lg { border-radius: 8px; }
|
||||
.border { border: 1px solid var(--border); }
|
||||
.border-0 { border: 0; }
|
||||
.p-1 { padding: 4px; }
|
||||
.gap-1 { gap: 4px; }
|
||||
.mb-1 { margin-bottom: 4px; }
|
||||
.mt-3 { margin-top: 12px; }
|
||||
.pt-2 { padding-top: 8px; }
|
||||
.h-px { height: 1px; }
|
||||
|
||||
/* ---------- 24. Helpers ---------- */
|
||||
.flex { display: flex; }
|
||||
.flex-col { flex-direction: column; }
|
||||
.items-center { align-items: center; }
|
||||
.justify-between { justify-content: space-between; }
|
||||
.justify-end { justify-content: flex-end; }
|
||||
.gap-2 { gap: 8px; }
|
||||
.gap-3 { gap: 12px; }
|
||||
.gap-4 { gap: 16px; }
|
||||
.gap-6 { gap: 24px; }
|
||||
.mt-1 { margin-top: 4px; }
|
||||
.mt-2 { margin-top: 8px; }
|
||||
.mt-4 { margin-top: 16px; }
|
||||
.mb-2 { margin-bottom: 8px; }
|
||||
.mb-4 { margin-bottom: 16px; }
|
||||
.mb-6 { margin-bottom: 24px; }
|
||||
.py-2 { padding-top: 8px; padding-bottom: 8px; }
|
||||
.px-3 { padding-left: 12px; padding-right: 12px; }
|
||||
.text-xs { font-size: 12px; }
|
||||
.text-sm { font-size: 13px; }
|
||||
.text-lg { font-size: 18px; }
|
||||
.text-xl { font-size: 20px; }
|
||||
.text-2xl { font-size: 24px; }
|
||||
.font-medium { font-weight: 500; }
|
||||
.font-semibold { font-weight: 600; }
|
||||
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.overflow-x-auto { overflow-x: auto; }
|
||||
.text-success { color: var(--success); }
|
||||
.text-error { color: var(--error); }
|
||||
.text-orange { color: var(--orange); }
|
||||
.text-blue { color: var(--blue); }
|
||||
.text-muted { color: var(--fg-muted); }
|
||||
.text-subtle { color: var(--fg-subtle); }
|
||||
.w-full { width: 100%; }
|
||||
.space-y-4 > * + * { margin-top: 16px; }
|
||||
.space-y-6 > * + * { margin-top: 24px; }
|
||||
|
||||
/* ---------- 25. Status indicator ---------- */
|
||||
.status-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; background: var(--fg-subtle); }
|
||||
.status-dot.connected { background: var(--success); }
|
||||
.status-dot.connecting { background: var(--warning); animation: pulse 1.5s infinite; }
|
||||
.status-dot.error { background: var(--error); }
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } }
|
||||
|
||||
/* ---------- 26. Speed range ---------- */
|
||||
input[type="range"] {
|
||||
-webkit-appearance: none; appearance: none;
|
||||
width: 100%; height: 4px; border-radius: 2px;
|
||||
background: linear-gradient(to right, var(--fg) var(--range-progress, 50%), #ddd var(--range-progress, 50%));
|
||||
}
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
-webkit-appearance: none; width: 16px; height: 16px;
|
||||
border-radius: 50%; background: var(--fg); cursor: pointer;
|
||||
}
|
||||
|
||||
/* ---------- 27. Animations ---------- */
|
||||
.fade-in { animation: fadeIn .4s ease-out; }
|
||||
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
|
||||
.spin { animation: spin 1s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* ---------- 28. Responsive ---------- */
|
||||
@media (max-width: 768px) {
|
||||
.page-body { padding: calc(var(--header-h) + 16px) 12px 64px; }
|
||||
.app-header-inner { padding: 0 12px; }
|
||||
.header-left { gap: 8px; overflow-x: auto; }
|
||||
.header-left::-webkit-scrollbar { display: none; }
|
||||
.brand span { display: none; }
|
||||
.grid-4 { grid-template-columns: repeat(2, 1fr); }
|
||||
.grid-3 { grid-template-columns: 1fr 1fr; }
|
||||
.batch-toolbar { bottom: 12px; padding: 6px 10px; gap: 6px; font-size: 11px; }
|
||||
.app-footer { right: 12px; left: 12px; text-align: center; }
|
||||
.chat-sidebar { position: fixed; z-index: 50; left: 0; top: 0; bottom: 0; }
|
||||
.chat-sidebar.collapsed { margin-left: -260px; }
|
||||
.voice-grid { grid-template-columns: 1fr; }
|
||||
.form-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.grid-2 { grid-template-columns: 1fr; }
|
||||
.grid-4 { grid-template-columns: 1fr; }
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,155 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="chat.pageTitle">Grok2API - Chat 聊天</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="function"></div>
|
||||
|
||||
<main class="chat-main">
|
||||
<div class="chat-layout">
|
||||
<aside class="chat-sidebar" id="chatSidebar">
|
||||
<div class="sidebar-header">
|
||||
<span class="sidebar-title" data-i18n="chat.sessions">会话</span>
|
||||
<div class="sidebar-actions">
|
||||
<button id="newChatBtn" class="sidebar-action-btn icon-btn" type="button" title="新增" data-i18n-title="chat.newChat">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="12" y1="5" x2="12" y2="19"></line>
|
||||
<line x1="5" y1="12" x2="19" y2="12"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<button id="collapseSidebarBtn" class="sidebar-action-btn icon-btn" type="button" title="折叠" data-i18n-title="chat.collapseSidebar">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="15 6 9 12 15 18"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sidebar-list" id="sessionList"></div>
|
||||
</aside>
|
||||
<div class="sidebar-overlay" id="sidebarOverlay"></div>
|
||||
<button id="sidebarExpandBtn" class="sidebar-expand-btn icon-btn" type="button" title="展开" data-i18n-title="chat.expandSidebar">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="9 6 15 12 9 18"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="chat-shell">
|
||||
<div class="chat-title">
|
||||
<div style="display:flex;align-items:center;gap:10px;">
|
||||
<button id="sidebarToggle" class="sidebar-toggle" type="button" title="会话列表" data-i18n-title="chat.sessionList">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="6" x2="21" y2="6"></line>
|
||||
<line x1="3" y1="12" x2="21" y2="12"></line>
|
||||
<line x1="3" y1="18" x2="21" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<div>
|
||||
<h2 class="chat-title-text" data-i18n="chat.title">Chat 聊天</h2>
|
||||
<p class="chat-subtitle" data-i18n="chat.subtitle">通过 chat 接口与 Grok 进行会话聊天</p>
|
||||
</div>
|
||||
</div>
|
||||
<span id="statusText" class="status-text" data-i18n="chat.ready">就绪</span>
|
||||
</div>
|
||||
|
||||
<div id="chatLog" class="chat-thread">
|
||||
<div id="emptyState" class="chat-empty" data-i18n="chat.emptyState">输入一条消息开始对话。</div>
|
||||
</div>
|
||||
|
||||
<div class="composer-shell">
|
||||
<div class="composer-input">
|
||||
<button id="attachBtn" class="icon-btn" type="button" title="上传文件" data-i18n-title="chat.uploadFile">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21.44 11.05l-9.19 9.19a5 5 0 0 1-7.07-7.07l9.9-9.9a3.5 3.5 0 0 1 4.95 4.95l-9.9 9.9a2 2 0 0 1-2.83-2.83l8.49-8.49"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<input id="fileInput" class="file-input" type="file" />
|
||||
<div id="fileBadge" class="file-badge hidden">
|
||||
<span id="fileName" class="file-name"></span>
|
||||
<button id="fileRemoveBtn" class="file-remove" type="button">×</button>
|
||||
</div>
|
||||
<textarea id="promptInput" class="composer-textarea" placeholder="询问任何内容" data-i18n-placeholder="chat.placeholder"></textarea>
|
||||
<div class="composer-actions">
|
||||
<div class="model-chip" id="modelChip">
|
||||
<svg class="model-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
|
||||
<line x1="8" y1="21" x2="16" y2="21"></line>
|
||||
<line x1="12" y1="17" x2="12" y2="21"></line>
|
||||
</svg>
|
||||
<span class="model-label" id="modelLabel">grok-4.20-beta</span>
|
||||
<svg class="model-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="6 9 12 15 18 9"></polyline>
|
||||
</svg>
|
||||
<div class="model-dropdown hidden" id="modelDropdown"></div>
|
||||
</div>
|
||||
<div class="popover hidden">
|
||||
<button id="settingsToggle" class="icon-btn" type="button" title="设置" data-i18n-title="chat.settings">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="3"></circle>
|
||||
<path
|
||||
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01A1.65 1.65 0 0 0 9 4.6V4a2 2 0 0 1 4 0v.09c0 .69.4 1.31 1.02 1.58.52.23 1.12.2 1.6-.07l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06c-.45.45-.58 1.12-.33 1.72.25.6.82 1 1.51 1H21a2 2 0 0 1 0 4h-.09c-.69 0-1.31.4-1.51 1Z">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="settingsPanel" class="settings-panel hidden">
|
||||
<div class="settings-grid">
|
||||
<div class="settings-block">
|
||||
<label class="field-label" for="tempRange" data-i18n="chat.temperature">温度</label>
|
||||
<div class="range-row">
|
||||
<input id="tempRange" type="range" min="0" max="2" step="0.05" value="0.8">
|
||||
<span id="tempValue" class="range-value">0.8</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block">
|
||||
<label class="field-label" for="topPRange" data-i18n="chat.topP">Top P</label>
|
||||
<div class="range-row">
|
||||
<input id="topPRange" type="range" min="0" max="1" step="0.05" value="0.95">
|
||||
<span id="topPValue" class="range-value">0.95</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-full">
|
||||
<label class="field-label" for="systemInput" data-i18n="chat.systemPrompt">System Prompt</label>
|
||||
<textarea id="systemInput" class="geist-input chat-input" placeholder="可选,设置系统提示词" data-i18n-placeholder="chat.systemPromptPlaceholder"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button id="sendBtn" class="send-btn" type="button" aria-label="Send" title="发送" data-i18n-title="chat.send" data-i18n-aria-label="chat.send">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M22 2L11 13"></path>
|
||||
<path d="M22 2L15 22L11 13L2 9L22 2Z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/webui/chat.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,247 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="imagine.pageTitle">Grok2API - Imagine 瀑布流</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="function"></div>
|
||||
|
||||
<main class="page-body wide fade-in">
|
||||
<div class="space-y-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold tracking-tight" data-i18n="imagine.title">Imagine 瀑布流</h2>
|
||||
<p class="text-muted mt-1 text-sm" data-i18n="imagine.subtitle">通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。</p>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="imagine-top-grid">
|
||||
<div class="imagine-card imagine-card-collapsible settings-card">
|
||||
<div class="card-content" id="settingsContent">
|
||||
<div class="card-title" data-i18n="imagine.genSettings">生成设置</div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-block settings-block-prompt">
|
||||
<div class="settings-prompt">
|
||||
<label class="field-label" for="promptInput" data-i18n="imagine.prompt">提示词</label>
|
||||
<textarea id="promptInput" class="geist-input imagine-textarea" placeholder="描述你想要的画面,例如:未来城市霓虹雨夜,广角摄影" data-i18n-placeholder="imagine.promptPlaceholder"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-duo">
|
||||
<div class="toggle-row">
|
||||
<div class="toggle-text">
|
||||
<div class="toggle-title" data-i18n="imagine.autoFollow">自动跟随</div>
|
||||
<div class="toggle-desc" data-i18n="imagine.autoFollowDesc">滚动到最新</div>
|
||||
</div>
|
||||
<label class="toggle">
|
||||
<input id="autoScrollToggle" type="checkbox" checked>
|
||||
<span class="toggle-track"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="toggle-row">
|
||||
<div class="toggle-text">
|
||||
<div class="toggle-title" data-i18n="imagine.autoSave">自动保存</div>
|
||||
<div class="toggle-desc" data-i18n="imagine.autoSaveDesc">自动保存图片</div>
|
||||
</div>
|
||||
<label class="toggle">
|
||||
<input id="autoDownloadToggle" type="checkbox">
|
||||
<span class="toggle-track"></span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-row2">
|
||||
<div class="settings-row">
|
||||
<div class="settings-field">
|
||||
<label class="field-label" for="ratioSelect" data-i18n="imagine.aspectRatio">宽高比</label>
|
||||
<select id="ratioSelect" class="geist-input">
|
||||
<option value="2:3" selected data-i18n="imagine.ratio2_3">2:3 竖图</option>
|
||||
<option value="1:1" data-i18n="imagine.ratio1_1">1:1 方图</option>
|
||||
<option value="3:2" data-i18n="imagine.ratio3_2">3:2 横图</option>
|
||||
<option value="16:9" data-i18n="imagine.ratio16_9">16:9 宽屏</option>
|
||||
<option value="9:16" data-i18n="imagine.ratio9_16">9:16 竖屏</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label class="field-label" for="concurrentSelect" data-i18n="imagine.concurrent">并发数量</label>
|
||||
<select id="concurrentSelect" class="geist-input">
|
||||
<option value="1" selected data-i18n="imagine.concurrentTask1">1 个任务</option>
|
||||
<option value="2" data-i18n="imagine.concurrentTask2">2 个任务</option>
|
||||
<option value="3" data-i18n="imagine.concurrentTask3">3 个任务</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-row2b settings-block-single">
|
||||
<div class="toggle-row toggle-row-fill">
|
||||
<div class="toggle-text">
|
||||
<div class="toggle-title" data-i18n="imagine.autoFilter">自动过滤</div>
|
||||
<div class="toggle-desc" data-i18n="imagine.autoFilterDesc">过滤不达标图片</div>
|
||||
</div>
|
||||
<label class="toggle">
|
||||
<input id="autoFilterToggle" type="checkbox">
|
||||
<span class="toggle-track"></span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-row3">
|
||||
<div class="settings-row">
|
||||
<div class="settings-field">
|
||||
<label class="field-label" for="nsfwSelect" data-i18n="imagine.nsfwLabel">是否 NSFW</label>
|
||||
<select id="nsfwSelect" class="geist-input">
|
||||
<option value="true" data-i18n="imagine.nsfwOn">开启</option>
|
||||
<option value="false" data-i18n="imagine.nsfwOff">关闭</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-folder">
|
||||
<label class="field-label" data-i18n="imagine.saveLocation">保存位置</label>
|
||||
<button id="selectFolderBtn" class="btn btn-outline folder-select-btn" disabled>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
|
||||
</svg>
|
||||
<span id="folderPath" data-i18n="imagine.browserDefault">浏览器默认位置</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block settings-block-row3b settings-block-single">
|
||||
<div class="toggle-row toggle-row-fill">
|
||||
<div class="toggle-text">
|
||||
<div class="toggle-title" data-i18n="imagine.reverseOrder">反向新增</div>
|
||||
<div class="toggle-desc" data-i18n="imagine.reverseOrderDesc">最新显示在上方</div>
|
||||
</div>
|
||||
<label class="toggle">
|
||||
<input id="reverseInsertToggle" type="checkbox">
|
||||
<span class="toggle-track"></span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="imagine-card imagine-card-collapsible">
|
||||
<div class="status-header-row" id="statusToggle">
|
||||
<div class="card-title" data-i18n="imagine.connectionStatus">连接状态</div>
|
||||
<span id="statusText" class="status-text" data-i18n="common.notConnected">未连接</span>
|
||||
<svg class="collapse-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="6 9 12 15 18 9"></polyline>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="card-content" id="statusContent">
|
||||
<div class="meta-grid">
|
||||
<div class="meta-item mode-item">
|
||||
<div class="meta-label" data-i18n="imagine.connectionMode">连接模式</div>
|
||||
<div class="mode-switch" role="group" aria-label="Connection mode" data-i18n-aria-label="imagine.connectionModeAria">
|
||||
<button class="mode-btn" data-mode="auto" type="button">Auto</button>
|
||||
<button class="mode-btn" data-mode="ws" type="button">WS</button>
|
||||
<button class="mode-btn" data-mode="sse" type="button">SSE</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="imagine.imageCount">图片数量</div>
|
||||
<div id="countValue" class="meta-value">0</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="imagine.activeTasks">活跃任务</div>
|
||||
<div id="activeValue" class="meta-value">0</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="imagine.avgTime">平均耗时</div>
|
||||
<div id="latencyValue" class="meta-value">-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="imagine-card" style="overflow: hidden;">
|
||||
<div class="waterfall-header">
|
||||
<div class="card-title" data-i18n="imagine.gallery">瀑布流</div>
|
||||
<div class="waterfall-actions">
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="imagine-empty">
|
||||
<div class="empty-title" data-i18n="imagine.waitingTitle">等待连接中</div>
|
||||
<div class="empty-subtitle" data-i18n="imagine.waitingSubtitle">启动任务后,生成的图片会自动汇聚到这里</div>
|
||||
</div>
|
||||
<div id="waterfall" class="waterfall"></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- 图片放大预览 -->
|
||||
<div id="lightbox" class="image-lightbox">
|
||||
<button class="lightbox-close" id="closeLightbox">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="lightbox-nav lightbox-prev" id="lightboxPrev">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="15 18 9 12 15 6"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="lightbox-nav lightbox-next" id="lightboxNext">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="9 18 15 12 9 6"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<img id="lightboxImg" src="" alt="">
|
||||
</div>
|
||||
|
||||
<div id="floatingActions" class="floating-actions">
|
||||
<button id="startBtn" class="btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-gray-100">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polygon points="5 3 19 12 5 21 5 3" />
|
||||
</svg>
|
||||
<span data-i18n="imagine.start">开始</span>
|
||||
</button>
|
||||
<button id="stopBtn" class="btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-gray-100 hidden">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="5" y="5" width="14" height="14" />
|
||||
</svg>
|
||||
<span data-i18n="common.stop">停止</span>
|
||||
</button>
|
||||
<span class="toolbar-sep"></span>
|
||||
<button id="clearBtn" class="btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-red-100">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
<span data-i18n="cache.clear">清空</span>
|
||||
</button>
|
||||
<span class="toolbar-sep"></span>
|
||||
<button id="batchDownloadBtn" class="batch-download-btn btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-gray-100" title="批量下载" data-i18n-title="imagine.batchDownloadTitle">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
||||
<polyline points="7 10 12 15 17 10"></polyline>
|
||||
<line x1="12" y1="15" x2="12" y2="3"></line>
|
||||
</svg>
|
||||
<span data-i18n="imagine.batch">批量</span>
|
||||
</button>
|
||||
<div id="selectionToolbar" class="selection-toolbar hidden">
|
||||
<button id="toggleSelectAllBtn" class="btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-gray-100" data-i18n="imagine.selectAll">全选</button>
|
||||
<button id="downloadSelectedBtn" class="btn btn-outline text-xs px-3 gap-1 border-0 hover:bg-gray-100"><span data-i18n="imagine.download">下载</span> <span id="selectedCount" class="selected-count">0</span></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
|
||||
<script src="/static/js/webui/imagine.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,39 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Grok2API - Public</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="login-body">
|
||||
<div class="login-bg"></div>
|
||||
<div class="login-shell">
|
||||
<div class="login-card">
|
||||
<div class="login-brand">
|
||||
<a href="https://github.com/chenyme/grok2api" target="_blank" class="flex items-center gap-2" style="color:inherit">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.58 2 12.26c0 4.5 2.87 8.32 6.84 9.67.5.1.68-.22.68-.48 0-.24-.01-.86-.01-1.69-2.78.62-3.37-1.37-3.37-1.37-.45-1.17-1.11-1.48-1.11-1.48-.91-.64.07-.63.07-.63 1.01.07 1.54 1.06 1.54 1.06.9 1.58 2.36 1.12 2.94.86.09-.67.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.04 1.03-2.76-.1-.26-.45-1.3.1-2.71 0 0 .84-.27 2.75 1.05A9.3 9.3 0 0 1 12 6.79c.85 0 1.7.12 2.5.36 1.9-1.32 2.74-1.05 2.74-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.64 1.03 2.76 0 3.94-2.34 4.81-4.58 5.06.36.32.68.95.68 1.92 0 1.38-.01 2.49-.01 2.83 0 .26.18.58.69.48A10.05 10.05 0 0 0 22 12.26C22 6.58 17.52 2 12 2Z"/></svg>
|
||||
<span>Grok2API</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="login-title" data-i18n="login.publicTitle">Public Access</div>
|
||||
<div class="login-subtitle" data-i18n="login.publicSubtitle">请输入 Function Key(如未配置可直接进入)</div>
|
||||
<div class="login-form">
|
||||
<input type="password" id="function-key-input" placeholder="Function Key" class="input" style="height:32px;font-size:12px">
|
||||
<button onclick="login()" class="btn btn-primary w-full" style="font-size:12px" data-i18n="login.enter">进入</button>
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-muted">
|
||||
<a href="/admin/login" style="transition:color .15s" data-i18n="login.goToAdmin">进入管理后台</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="app-footer"></div>
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/webui/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,163 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="video.pageTitle">Grok2API - Video 视频生成</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="function"></div>
|
||||
|
||||
<main class="page-body wide fade-in">
|
||||
<div class="space-y-6">
|
||||
<div class="video-header-row">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold tracking-tight" data-i18n="video.title">Video 视频生成</h2>
|
||||
<p class="text-muted mt-1 text-sm" data-i18n="video.subtitle">生成短视频,支持参考图与多种预设风格。</p>
|
||||
</div>
|
||||
<div class="video-actions">
|
||||
<button id="startBtn" class="btn btn-primary gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<polygon points="5 3 19 12 5 21 5 3" />
|
||||
</svg>
|
||||
<span data-i18n="video.startGenerate">开始生成</span>
|
||||
</button>
|
||||
<button id="stopBtn" class="btn btn-outline gap-2 hidden">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="5" y="5" width="14" height="14" />
|
||||
</svg>
|
||||
<span data-i18n="common.stop">停止</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="video-top-grid">
|
||||
<div class="video-card">
|
||||
<div class="card-title" data-i18n="video.genSettings">生成设置</div>
|
||||
<div class="settings-grid">
|
||||
<div class="settings-block prompt-block">
|
||||
<label class="field-label" for="promptInput" data-i18n="video.prompt">提示词</label>
|
||||
<textarea id="promptInput" class="geist-input video-textarea" placeholder="例如:@图1街头霓虹雨夜,@图2人物回头微笑,慢镜头,胶片质感" data-i18n-placeholder="video.promptPlaceholder"></textarea>
|
||||
<div class="prompt-tip" data-i18n="video.promptTip">多图参考可在提示词中使用 @图1 到 @图7,按参考图顺序对应。</div>
|
||||
</div>
|
||||
<div class="settings-block ref-block">
|
||||
<label class="field-label" for="imageUrlInput" data-i18n="video.referenceImage">参考图</label>
|
||||
<div class="ref-controls">
|
||||
<textarea id="imageUrlInput" class="geist-input ref-textarea" placeholder="每行一个 https://... 或 data:image/...,最多 7 张" data-i18n-placeholder="video.referenceImagePlaceholder"></textarea>
|
||||
</div>
|
||||
<div class="ref-meta">
|
||||
<span id="imageFileName" class="ref-name" data-i18n="video.noReferenceSelected">未选择参考图</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-block ratio-block">
|
||||
<label class="field-label" for="ratioSelect" data-i18n="video.aspectRatio">画面比例</label>
|
||||
<select id="ratioSelect" class="geist-input">
|
||||
<option value="3:2" selected data-i18n="video.ratio3_2">3:2 横构图</option>
|
||||
<option value="2:3" data-i18n="video.ratio2_3">2:3 竖构图</option>
|
||||
<option value="16:9" data-i18n="video.ratio16_9">16:9 宽屏</option>
|
||||
<option value="9:16" data-i18n="video.ratio9_16">9:16 竖屏</option>
|
||||
<option value="1:1" data-i18n="video.ratio1_1">1:1 方形</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-block length-block">
|
||||
<label class="field-label" for="lengthSelect" data-i18n="video.duration">视频时长</label>
|
||||
<input id="lengthSelect" class="geist-input" type="number" min="6" max="30" step="1" value="6" />
|
||||
</div>
|
||||
<div class="settings-block resolution-block">
|
||||
<label class="field-label" for="resolutionSelect" data-i18n="video.resolution">分辨率</label>
|
||||
<select id="resolutionSelect" class="geist-input">
|
||||
<option value="480p" selected>480p</option>
|
||||
<option value="720p">720p</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-block preset-block">
|
||||
<label class="field-label" for="presetSelect" data-i18n="video.stylePreset">风格预设</label>
|
||||
<select id="presetSelect" class="geist-input">
|
||||
<option value="normal" selected>Normal</option>
|
||||
<option value="fun">Fun</option>
|
||||
<option value="spicy">Spicy</option>
|
||||
<option value="custom">Custom</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-block upload-block">
|
||||
<label class="field-label"> </label>
|
||||
<button id="selectImageFileBtn" class="btn btn-outline text-xs px-3" type="button" data-i18n="video.upload">上传</button>
|
||||
<input id="imageFileInput" class="ref-file-input" type="file" accept="image/*" multiple>
|
||||
</div>
|
||||
<div class="settings-block clear-block">
|
||||
<label class="field-label"> </label>
|
||||
<button id="clearImageFileBtn" class="btn btn-outline text-xs px-3" type="button" data-i18n="video.clearImage">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="video-card">
|
||||
<div class="status-header">
|
||||
<div class="card-title" data-i18n="video.runStatus">运行状态</div>
|
||||
<span id="statusText" class="status-text" data-i18n="common.notConnected">未连接</span>
|
||||
</div>
|
||||
<div class="progress-wrap">
|
||||
<div id="progressBar" class="progress-bar">
|
||||
<div id="progressFill" class="progress-fill"></div>
|
||||
</div>
|
||||
<div class="progress-meta">
|
||||
<span id="progressText">0%</span>
|
||||
<span id="durationValue" data-i18n="video.elapsedTimeNone">耗时 -</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta-grid">
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="video.metaRatio">比例</div>
|
||||
<div id="aspectValue" class="meta-value">-</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="video.metaDuration">时长</div>
|
||||
<div id="lengthValue" class="meta-value">-</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="video.metaResolution">分辨率</div>
|
||||
<div id="resolutionValue" class="meta-value">-</div>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<div class="meta-label" data-i18n="video.metaPreset">预设</div>
|
||||
<div id="presetValue" class="meta-value">-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="video-card video-preview-card">
|
||||
<div class="video-preview-header">
|
||||
<div class="card-title" data-i18n="video.videoPreview">视频预览</div>
|
||||
<div class="preview-actions">
|
||||
<button id="clearBtn" class="btn btn-outline text-xs px-3" data-i18n="video.clearPreview">清空</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="videoEmpty" class="video-empty" data-i18n="video.waitingGenerate">等待生成视频</div>
|
||||
<div id="videoStage" class="video-stage hidden"></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/webui/video.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,108 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n="voice.pageTitle">Grok2API - LiveKit 陪聊</title>
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-mono/style.css" rel="stylesheet">
|
||||
<link href="/static/css/app.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2.7.3/dist/livekit-client.umd.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div id="app-header" data-type="function"></div>
|
||||
|
||||
<main class="page-body wide fade-in">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-semibold" data-i18n="voice.title">LiveKit 陪聊</h2>
|
||||
<p class="text-sm text-muted mt-1" data-i18n="voice.subtitle">LiveKit 语音会话,连接 Grok Voice。</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button id="startBtn" class="btn btn-primary gap-2">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
||||
<span data-i18n="voice.startSession">开始会话</span>
|
||||
</button>
|
||||
<button id="stopBtn" class="btn btn-outline gap-2 hidden">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="5" width="14" height="14"/></svg>
|
||||
<span data-i18n="voice.stopSession">停止会话</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="voice-grid">
|
||||
<section>
|
||||
<div class="voice-card">
|
||||
<div class="card-title" data-i18n="voice.connectionSettings">连接设置</div>
|
||||
<div class="form-grid">
|
||||
<div>
|
||||
<label class="field-label" data-i18n="voice.voiceLabel">声音</label>
|
||||
<select id="voiceSelect" class="input">
|
||||
<option value="ara" selected>Ara</option><option value="eve">Eve</option>
|
||||
<option value="leo">Leo</option><option value="rex">Rex</option>
|
||||
<option value="sal">Sal</option><option value="gork">Gork</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="field-label" data-i18n="voice.personalityLabel">个性</label>
|
||||
<select id="personalitySelect" class="input">
|
||||
<option value="assistant" selected>Assistant</option><option value="custom">Custom</option>
|
||||
<option value="therapist">Therapist</option><option value="storyteller">Storyteller</option>
|
||||
<option value="kids_story_time">Kids Story Time</option><option value="meditation">Meditation</option>
|
||||
<option value="unhinged">Unhinged 18+</option><option value="sexy">Sexy 18+</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="grid-column:1/-1">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<label class="field-label" data-i18n="voice.speedLabel">语速</label>
|
||||
<span class="range-value"><span id="speedValue">1.0</span>x</span>
|
||||
</div>
|
||||
<input type="range" id="speedRange" min="0.5" max="2.0" step="0.1" value="1.0" style="width:100%">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="voice-card">
|
||||
<div class="voice-log-header">
|
||||
<div class="card-title" data-i18n="voice.sessionLog">会话日志</div>
|
||||
<div class="flex gap-2">
|
||||
<button id="clearLogBtn" class="btn btn-outline btn-sm">清空</button>
|
||||
<button id="copyLogBtn" class="btn btn-outline btn-sm">复制</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="log" class="voice-log"></div>
|
||||
</div>
|
||||
</section>
|
||||
<aside>
|
||||
<div class="voice-card">
|
||||
<div class="voice-log-header">
|
||||
<div class="card-title" data-i18n="voice.sessionStatus">状态</div>
|
||||
<span id="statusText" class="status-text">未连接</span>
|
||||
</div>
|
||||
<div class="meta-grid">
|
||||
<div class="meta-item"><div class="meta-label">Voice</div><div id="statusVoice" class="meta-value">-</div></div>
|
||||
<div class="meta-item"><div class="meta-label">Personality</div><div id="statusPersonality" class="meta-value">-</div></div>
|
||||
<div class="meta-item"><div class="meta-label">Speed</div><div id="statusSpeed" class="meta-value">-</div></div>
|
||||
<div class="meta-item"><div class="meta-label">LiveKit</div><div class="meta-value">wss://livekit.grok.com</div></div>
|
||||
</div>
|
||||
<div class="visualizer" id="visualizer"></div>
|
||||
</div>
|
||||
<div class="voice-card">
|
||||
<div class="card-title" data-i18n="voice.audioOutput">音频输出</div>
|
||||
<div id="audioRoot" class="mt-2"></div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div id="app-footer"></div>
|
||||
</div>
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/js/core/auth.js"></script>
|
||||
<script src="/static/js/core/toast.js"></script>
|
||||
<script src="/static/js/core/header.js"></script>
|
||||
<script src="/static/js/webui/voice.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,213 +0,0 @@
|
||||
# Grok2API i18n Developer Guide
|
||||
|
||||
## Architecture
|
||||
|
||||
The i18n system is a single-file, zero-dependency module (`i18n.js`) that:
|
||||
|
||||
1. **Detects** the user's language: `localStorage` > `?lang=` URL param > browser `navigator.language` > fallback (`zh`)
|
||||
2. **Fetches** the matching locale JSON (`/static/i18n/locales/{lang}.json`)
|
||||
3. **Applies** translations to the DOM via `data-i18n-*` attributes
|
||||
4. **Exposes** a global `t(key, params)` function for JS-driven strings
|
||||
|
||||
The script self-initializes on DOM ready. No import/export — it attaches `window.I18n` and `window.t`.
|
||||
|
||||
## File structure
|
||||
|
||||
```
|
||||
public/static/i18n/
|
||||
i18n.js # Core module (IIFE, ~110 lines)
|
||||
locales/
|
||||
zh.json # Chinese (default/fallback)
|
||||
en.json # English
|
||||
README.md # This file
|
||||
```
|
||||
|
||||
Each HTML page includes the script before page-specific JS:
|
||||
|
||||
```html
|
||||
<script src="/static/i18n/i18n.js"></script>
|
||||
<script src="/static/public/js/chat.js"></script>
|
||||
```
|
||||
|
||||
## Translation key conventions
|
||||
|
||||
Keys use **dot-notation** with a two-level namespace: `{page}.{name}`
|
||||
|
||||
| Namespace | Scope |
|
||||
|-----------|-------|
|
||||
| `common` | Shared strings (save, cancel, loading, errors) |
|
||||
| `nav` | Navigation links and header labels |
|
||||
| `login` | Login pages (admin + public) |
|
||||
| `config` | Admin config page |
|
||||
| `token` | Token management page |
|
||||
| `cache` | Cache management page |
|
||||
| `chat` | Chat page |
|
||||
| `imagine` | Image generation page |
|
||||
| `video` | Video generation page |
|
||||
| `voice` | Voice/LiveKit page |
|
||||
|
||||
Naming patterns:
|
||||
- `page.pageTitle` — browser tab `<title>`
|
||||
- `page.title` / `page.subtitle` — heading/subheading
|
||||
- `page.placeholder` — main input placeholder
|
||||
- `common.{verb}Failed` / `common.{verb}Error` — error messages
|
||||
- `page.confirm{Action}` — confirmation dialog text
|
||||
|
||||
## Translating a static HTML element
|
||||
|
||||
Add one of these attributes to the HTML element:
|
||||
|
||||
### `data-i18n` — sets `textContent`
|
||||
|
||||
```html
|
||||
<h2 data-i18n="chat.title">Chat 聊天</h2>
|
||||
```
|
||||
|
||||
### `data-i18n-placeholder` — sets `placeholder`
|
||||
|
||||
```html
|
||||
<textarea data-i18n-placeholder="chat.placeholder" placeholder="询问任何内容"></textarea>
|
||||
```
|
||||
|
||||
### `data-i18n-title` — sets `title` (tooltip)
|
||||
|
||||
```html
|
||||
<button data-i18n-title="chat.send" title="发送">▶</button>
|
||||
```
|
||||
|
||||
### `data-i18n-html` — sets `innerHTML` (available, not currently used)
|
||||
|
||||
```html
|
||||
<span data-i18n-html="chat.richContent"></span>
|
||||
```
|
||||
|
||||
> Use only when the translation contains HTML markup. Prefer `data-i18n` for plain text to avoid XSS risks.
|
||||
|
||||
> Keep the Chinese fallback as the element's default content/attribute so the page renders correctly before translations load.
|
||||
|
||||
## Translating a dynamic JS string
|
||||
|
||||
Use the global `t(key, params?)` function:
|
||||
|
||||
```js
|
||||
showToast(t('cache.clearSuccess', { size: data.result.size_mb }), 'success');
|
||||
```
|
||||
|
||||
The `params` object replaces `{var}` placeholders in the locale string:
|
||||
|
||||
```json
|
||||
{ "clearSuccess": "Cleared successfully, freed {size} MB" }
|
||||
```
|
||||
|
||||
### Guard pattern for shared modules
|
||||
|
||||
Shared code (e.g., `toast.js`, `admin-auth.js`) may run before `i18n.js` loads. Guard with `typeof t`:
|
||||
|
||||
```js
|
||||
const label = typeof t === 'function' ? t('common.notice') : '提示';
|
||||
```
|
||||
|
||||
## Translating dynamically injected HTML
|
||||
|
||||
When HTML is injected at runtime (e.g., fetching a header fragment), call `I18n.applyToDOM(container)` after insertion:
|
||||
|
||||
```js
|
||||
container.innerHTML = await res.text();
|
||||
|
||||
if (window.I18n) {
|
||||
I18n.applyToDOM(container);
|
||||
}
|
||||
```
|
||||
|
||||
This scans the container for `data-i18n-*` attributes and applies translations. The language toggle button text is set separately since it isn't a translation key:
|
||||
|
||||
```js
|
||||
var toggle = container.querySelector('#lang-toggle');
|
||||
if (toggle) toggle.textContent = I18n.getLang() === 'zh' ? 'EN' : '中';
|
||||
```
|
||||
|
||||
## API reference
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `t(key, params?)` | Translate a key. Returns the key itself if not found. |
|
||||
| `I18n.applyToDOM(root?)` | Scan `root` (default: `document`) for `data-i18n-*` attrs and apply translations. |
|
||||
| `I18n.setLang(lang)` | Set language, persist to localStorage, reload page. |
|
||||
| `I18n.toggleLang()` | Toggle between `zh` and `en`, reload. |
|
||||
| `I18n.getLang()` | Return current language code (`'zh'` or `'en'`). |
|
||||
| `I18n.onReady(cb)` | Run `cb` after translations have loaded. Runs immediately if already loaded. |
|
||||
|
||||
## How to add a new language
|
||||
|
||||
1. Create `public/static/i18n/locales/{code}.json` — copy `en.json` as a template
|
||||
2. Translate every key (545+ keys across 10 namespaces)
|
||||
3. In `i18n.js`, add the code to the `SUPPORTED` array:
|
||||
```js
|
||||
var SUPPORTED = ['zh', 'en', 'ja'];
|
||||
```
|
||||
4. Update the `toggleLang` function if you want rotation instead of binary toggle
|
||||
5. Update `#lang-toggle` button logic in `header.js` / `public-header.js`
|
||||
|
||||
## How to add a new page
|
||||
|
||||
Checklist:
|
||||
|
||||
- [ ] Add a new namespace in both `zh.json` and `en.json` (e.g., `"mypage": { ... }`)
|
||||
- [ ] In the HTML: add `<script src="/static/i18n/i18n.js"></script>` before your page JS
|
||||
- [ ] In the HTML: add `data-i18n` / `data-i18n-placeholder` / `data-i18n-title` attributes to all user-visible elements
|
||||
- [ ] In the JS: use `t('mypage.keyName')` for any strings built in code
|
||||
- [ ] If injecting HTML dynamically: call `I18n.applyToDOM(container)` after insertion
|
||||
- [ ] If the page loads before `i18n.js`: use the `typeof t === 'function'` guard
|
||||
|
||||
## Common patterns
|
||||
|
||||
### Button with icon + translated text
|
||||
|
||||
```html
|
||||
<button class="btn" type="button">
|
||||
<svg>...</svg>
|
||||
<span data-i18n="voice.startSession">开始会话</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
Wrap the text in a `<span>` so the icon is preserved.
|
||||
|
||||
### Select options translated in JS
|
||||
|
||||
```js
|
||||
const option = document.createElement('option');
|
||||
option.value = 'value';
|
||||
option.textContent = t('voice.optionLabel');
|
||||
select.appendChild(option);
|
||||
```
|
||||
|
||||
### Interpolation for dynamic values
|
||||
|
||||
```js
|
||||
// Locale: "lastClear": "Last cleared: {time}"
|
||||
setText(el, t('cache.lastClear', { time: timeText }));
|
||||
```
|
||||
|
||||
### Table rows with inline translated strings
|
||||
|
||||
```js
|
||||
body.innerHTML = `<tr><td colspan="5">${t('common.loading')}</td></tr>`;
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
1. **Script order matters.** `i18n.js` must be loaded before page JS if the page JS calls `t()` at the top level. Otherwise use the `typeof t === 'function'` guard.
|
||||
|
||||
2. **`t()` returns the key on miss.** If you see a raw key like `chat.title` in the UI, the key is missing from the locale JSON or was misspelled.
|
||||
|
||||
3. **Keep both locale files in sync.** Every key in `zh.json` must exist in `en.json` and vice versa. Missing keys fall through to displaying the raw key string.
|
||||
|
||||
4. **`innerHTML` vs `textContent`.** Use `data-i18n-html` only when the translation contains HTML markup. For plain text, always use `data-i18n` to avoid XSS risks.
|
||||
|
||||
5. **Default content is Chinese.** The HTML files keep Chinese as inline fallback text. This means the page briefly shows Chinese before translations load — this is intentional and ensures the page is never blank.
|
||||
|
||||
6. **`setLang()` reloads the page.** Language switching is not live — it persists to localStorage and triggers a full page reload.
|
||||
|
||||
7. **`applyToDOM()` is idempotent.** Safe to call multiple times on the same container.
|
||||
|
||||
8. **Shared modules need guards.** Files under `common/js/` (toast, header, admin-auth) may be loaded by pages that don't include `i18n.js`. Always guard `t()` calls in shared code.
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* Grok2API i18n module — lightweight, zero-dependency internationalization.
|
||||
* Detects language from: localStorage > ?lang= URL param > browser > fallback (zh).
|
||||
* Translates static HTML via data-i18n / data-i18n-placeholder / data-i18n-title attrs.
|
||||
* Provides global t(key, params) for dynamic JS strings with {var} interpolation.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var STORAGE_KEY = 'grok2api_lang';
|
||||
var SUPPORTED = ['zh', 'en'];
|
||||
var DEFAULT = 'zh';
|
||||
|
||||
var lang = DEFAULT;
|
||||
var data = {};
|
||||
var ready = false;
|
||||
var queue = [];
|
||||
|
||||
function getStaticVersion() {
|
||||
var script = document.querySelector('script[src*="?v="]');
|
||||
if (!script || !script.src) return '';
|
||||
var m = script.src.match(/[?&]v=([^&]+)/);
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
function detect() {
|
||||
try {
|
||||
var s = localStorage.getItem(STORAGE_KEY);
|
||||
if (s && SUPPORTED.indexOf(s) !== -1) return s;
|
||||
} catch (e) { /* ignore */ }
|
||||
try {
|
||||
var p = new URLSearchParams(location.search).get('lang');
|
||||
if (p && SUPPORTED.indexOf(p) !== -1) {
|
||||
try { localStorage.setItem(STORAGE_KEY, p); } catch (e) { /* ignore */ }
|
||||
return p;
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
var b = (navigator.language || '').split('-')[0];
|
||||
if (SUPPORTED.indexOf(b) !== -1) return b;
|
||||
return DEFAULT;
|
||||
}
|
||||
|
||||
function get(obj, key) {
|
||||
for (var parts = key.split('.'), i = 0; i < parts.length; i++) {
|
||||
if (obj == null) return undefined;
|
||||
obj = obj[parts[i]];
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function t(key, params) {
|
||||
var v = get(data, key);
|
||||
if (v === undefined) return key;
|
||||
if (params) {
|
||||
Object.keys(params).forEach(function (k) {
|
||||
v = v.replace(new RegExp('\\{' + k + '\\}', 'g'), params[k]);
|
||||
});
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function applyToDOM(root) {
|
||||
var c = root || document;
|
||||
c.querySelectorAll('[data-i18n]').forEach(function (el) {
|
||||
var v = get(data, el.getAttribute('data-i18n'));
|
||||
if (v !== undefined) el.textContent = v;
|
||||
});
|
||||
c.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) {
|
||||
var v = get(data, el.getAttribute('data-i18n-placeholder'));
|
||||
if (v !== undefined) el.placeholder = v;
|
||||
});
|
||||
c.querySelectorAll('[data-i18n-title]').forEach(function (el) {
|
||||
var v = get(data, el.getAttribute('data-i18n-title'));
|
||||
if (v !== undefined) el.title = v;
|
||||
});
|
||||
c.querySelectorAll('[data-i18n-aria-label]').forEach(function (el) {
|
||||
var v = get(data, el.getAttribute('data-i18n-aria-label'));
|
||||
if (v !== undefined) el.setAttribute('aria-label', v);
|
||||
});
|
||||
c.querySelectorAll('[data-i18n-html]').forEach(function (el) {
|
||||
var v = get(data, el.getAttribute('data-i18n-html'));
|
||||
if (v !== undefined) el.innerHTML = v;
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
lang = detect();
|
||||
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : lang;
|
||||
var version = getStaticVersion();
|
||||
var url = '/static/i18n/locales/' + lang + '.json' + (version ? ('?v=' + encodeURIComponent(version)) : '');
|
||||
fetch(url)
|
||||
.then(function (r) { if (!r.ok) throw r; return r.json(); })
|
||||
.then(function (j) { data = j; })
|
||||
.catch(function () { data = {}; })
|
||||
.then(function () {
|
||||
ready = true;
|
||||
applyToDOM(document);
|
||||
queue.forEach(function (cb) { cb(); });
|
||||
queue = [];
|
||||
});
|
||||
}
|
||||
|
||||
function setLang(l) {
|
||||
if (SUPPORTED.indexOf(l) === -1) return;
|
||||
try { localStorage.setItem(STORAGE_KEY, l); } catch (e) { /* ignore */ }
|
||||
location.reload();
|
||||
}
|
||||
|
||||
window.I18n = {
|
||||
t: t,
|
||||
applyToDOM: applyToDOM,
|
||||
setLang: setLang,
|
||||
toggleLang: function () { setLang(lang === 'zh' ? 'en' : 'zh'); },
|
||||
getLang: function () { return lang; },
|
||||
onReady: function (cb) { if (ready) cb(); else queue.push(cb); }
|
||||
};
|
||||
window.t = t;
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -1,589 +0,0 @@
|
||||
{
|
||||
"common": {
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"confirm": "Confirm",
|
||||
"delete": "Delete",
|
||||
"loading": "Loading...",
|
||||
"invalidKey": "Invalid key",
|
||||
"connectionFailed": "Connection failed",
|
||||
"requestFailed": "Request failed",
|
||||
"operationSuccess": "Operation successful",
|
||||
"gotIt": "Got it",
|
||||
"notice": "Notice",
|
||||
"rateLimitNotice": "The official GROK website update did not expose the rate-limits API, making it impossible to accurately calculate remaining Token usage. Please wait for the official API. Currently the count resets to 8 after auto-refresh.",
|
||||
"pleaseConfirm": "Please confirm",
|
||||
"ok": "OK",
|
||||
"close": "Close",
|
||||
"error": "Error",
|
||||
"unknownError": "Unknown error",
|
||||
"connectionInterrupted": "Connection interrupted",
|
||||
"taskInProgress": "A task is already in progress",
|
||||
"taskNoPause": "Current task does not support pausing",
|
||||
"batchNoPause": "Current batch task does not support pausing",
|
||||
"waitTaskFinish": "Please wait for the current task to finish",
|
||||
"pause": "Pause",
|
||||
"stop": "Stop",
|
||||
"selectAll": "Select all",
|
||||
"selected": "Selected",
|
||||
"items": "items",
|
||||
"export": "Export",
|
||||
"refresh": "Refresh",
|
||||
"load": "Load",
|
||||
"files": "files",
|
||||
"view": "View",
|
||||
"retry": "Retry",
|
||||
"copy": "Copy",
|
||||
"edit": "Edit",
|
||||
"loadFailed": "Load failed",
|
||||
"loadError": "Load failed: {msg}",
|
||||
"saveFailed": "Save failed",
|
||||
"saveError": "Save error: {msg}",
|
||||
"deleteFailed": "Delete failed",
|
||||
"deleteSuccess": "Deleted successfully",
|
||||
"notConnected": "Not connected",
|
||||
"connecting": "Connecting",
|
||||
"connected": "Connected",
|
||||
"connectionError": "Connection error",
|
||||
"generating": "Generating",
|
||||
"done": "Done",
|
||||
"failed": "Failed",
|
||||
"stopped": "Stopped",
|
||||
"terminated": "Terminated",
|
||||
"sending": "Sending",
|
||||
"fileReadFailed": "File read failed",
|
||||
"noFileSelected": "No file selected",
|
||||
"configurePublicKey": "Please configure Public Key first",
|
||||
"enterPrompt": "Please enter a prompt",
|
||||
"enterContent": "Please enter content",
|
||||
"alreadyRunning": "Already running",
|
||||
"createTaskFailed": "Failed to create task",
|
||||
"copyFailed": "Copy failed",
|
||||
"copied": "Copied",
|
||||
"generationFailed": "Generation failed",
|
||||
"partialError": "Partial error",
|
||||
"loadingInProgress": "Loading in progress, please wait",
|
||||
"cleaningInProgress": "Cleaning in progress, please wait",
|
||||
"noTokenSelected": "No Token selected",
|
||||
"clearCache": "Clear cache",
|
||||
"failureDetails": "Failure Details",
|
||||
"retryFailed": "Retry failed items"
|
||||
},
|
||||
"nav": {
|
||||
"tokenManage": "Token Mgmt",
|
||||
"configManage": "Config Mgmt",
|
||||
"cacheManage": "Cache Mgmt",
|
||||
"chat": "Chat",
|
||||
"imagine": "Imagine Gallery",
|
||||
"video": "Video Generation",
|
||||
"voice": "LiveKit Voice",
|
||||
"feedback": "Feedback",
|
||||
"logout": "Logout",
|
||||
"adminPanel": "Admin Panel",
|
||||
"storageMode": "Storage Mode"
|
||||
},
|
||||
"login": {
|
||||
"adminPageTitle": "Grok2API - Login",
|
||||
"adminTitle": "Admin Panel",
|
||||
"adminSubtitle": "Enter admin password to continue",
|
||||
"adminPlaceholder": "Admin Password (app_key)",
|
||||
"continue": "Continue",
|
||||
"publicPageTitle": "Grok2API - Public",
|
||||
"publicTitle": "Public Access",
|
||||
"publicSubtitle": "Enter Public Key (leave empty if not configured)",
|
||||
"publicPlaceholder": "Public Key",
|
||||
"enter": "Enter",
|
||||
"goToAdmin": "Go to Admin Panel"
|
||||
},
|
||||
"config": {
|
||||
"pageTitle": "Grok2API - Config",
|
||||
"title": "Configuration",
|
||||
"subtitle": "Manage API keys and system parameters.",
|
||||
"saving": "Saving...",
|
||||
"saved": "Saved",
|
||||
"configSaved": "Configuration saved",
|
||||
"invalidJson": "Invalid JSON: {field}",
|
||||
"appKeyRequired": "app_key cannot be empty (admin password)",
|
||||
"flaresolverrRequired": "FlareSolverr URL is required when auto-refresh is enabled",
|
||||
"generate": "Generate",
|
||||
"publicAccess": "Public Access",
|
||||
"noDesc": "No description available. Please refer to the documentation.",
|
||||
"sectionFallback": "{section} Settings",
|
||||
"sections": {
|
||||
"app": "App Settings",
|
||||
"proxy": "Proxy Config",
|
||||
"retry": "Retry Strategy",
|
||||
"chat": "Chat Config",
|
||||
"video": "Video Config",
|
||||
"image": "Image Config",
|
||||
"imagine_fast": "Imagine Fast Config",
|
||||
"asset": "Asset Config",
|
||||
"voice": "Voice Config",
|
||||
"token": "Token Pool Mgmt",
|
||||
"cache": "Cache Mgmt",
|
||||
"nsfw": "NSFW Config",
|
||||
"usage": "Usage Config"
|
||||
},
|
||||
"sectionDescs": {
|
||||
"proxy": "Incorrect configuration will cause 403 errors. The IP of the first request to Grok must match the IP used to obtain the CF Clearance. Subsequent IP changes will not cause 403."
|
||||
},
|
||||
"fields": {
|
||||
"app": {
|
||||
"api_key": {"title": "API Key", "desc": "Token for calling Grok2API services (optional, supports multiple, comma-separated or array)."},
|
||||
"app_key": {"title": "Admin Password", "desc": "Password for logging into the Grok2API admin panel (required)."},
|
||||
"function_enabled": {"title": "Enable Function Access", "desc": "Whether to enable the function access entry (disabled means function pages are inaccessible)."},
|
||||
"function_key": {"title": "Function Password", "desc": "Access password for function pages (optional)."},
|
||||
"app_url": {"title": "App URL", "desc": "External access URL for the Grok2API service, used for file link access."},
|
||||
"image_format": {"title": "Image Format", "desc": "Default image format (url or base64)."},
|
||||
"video_format": {"title": "Video Format", "desc": "Default video format (html or url, url is the processed link)."},
|
||||
"temporary": {"title": "Temporary Chat", "desc": "Whether to enable temporary chat mode by default."},
|
||||
"disable_memory": {"title": "Disable Memory", "desc": "Whether to disable Grok memory feature by default."},
|
||||
"stream": {"title": "Streaming", "desc": "Whether to enable streaming output by default."},
|
||||
"thinking": {"title": "Chain of Thought", "desc": "Whether to enable chain of thought output by default."},
|
||||
"dynamic_statsig": {"title": "Dynamic Fingerprint", "desc": "Whether to enable dynamic Statsig fingerprint generation by default."},
|
||||
"custom_instruction": {"title": "Custom Instruction", "desc": "Multi-line text passed through as Grok request parameter customPersonality."},
|
||||
"filter_tags": {"title": "Filter Tags", "desc": "Configure automatic filtering of special tags in Grok responses."}
|
||||
},
|
||||
"proxy": {
|
||||
"base_proxy_url": {"title": "Base Proxy URL", "desc": "Base service address for proxying requests to Grok website."},
|
||||
"asset_proxy_url": {"title": "Asset Proxy URL", "desc": "Address for proxying static resource (image/video) requests to Grok website."},
|
||||
"skip_proxy_ssl_verify": {"title": "Skip Proxy SSL Verify", "desc": "Enable when your proxy uses a self-signed certificate (only bypasses proxy certificate validation)."},
|
||||
"enabled": {"title": "Enable CF Auto-Refresh", "desc": "When enabled, automatically obtains cf_clearance through FlareSolverr."},
|
||||
"flaresolverr_url": {"title": "FlareSolverr URL", "desc": "HTTP address of FlareSolverr service (e.g. http://flaresolverr:8191)."},
|
||||
"refresh_interval": {"title": "Refresh Interval (sec)", "desc": "Time interval for auto-refreshing cf_clearance, recommended minimum 300 seconds."},
|
||||
"timeout": {"title": "Challenge Timeout (sec)", "desc": "Maximum time to wait for FlareSolverr to solve CF challenge."},
|
||||
"cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie for bypassing anti-bot verification. Automatically managed when auto-refresh is enabled."},
|
||||
"browser": {"title": "Browser Fingerprint", "desc": "curl_cffi browser fingerprint identifier (e.g. chrome136). Automatically managed when auto-refresh is enabled."},
|
||||
"user_agent": {"title": "User-Agent", "desc": "HTTP request User-Agent string. Automatically managed when auto-refresh is enabled."}
|
||||
},
|
||||
"retry": {
|
||||
"max_retry": {"title": "Max Retries", "desc": "Maximum number of retries when Grok service request fails."},
|
||||
"retry_status_codes": {"title": "Retry Status Codes", "desc": "HTTP status codes that trigger a retry."},
|
||||
"reset_session_status_codes": {"title": "Session Reset Status Codes", "desc": "HTTP status codes that trigger session rebuild (used for proxy rotation)."},
|
||||
"retry_backoff_base": {"title": "Backoff Base", "desc": "Base delay (seconds) for retry backoff."},
|
||||
"retry_backoff_factor": {"title": "Backoff Factor", "desc": "Exponential multiplier for retry backoff."},
|
||||
"retry_backoff_max": {"title": "Backoff Max", "desc": "Maximum delay (seconds) for a single retry wait."},
|
||||
"retry_budget": {"title": "Backoff Budget", "desc": "Maximum total retry time (seconds) for a single request."}
|
||||
},
|
||||
"chat": {
|
||||
"concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."},
|
||||
"timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."},
|
||||
"stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."}
|
||||
},
|
||||
"video": {
|
||||
"enable_public_asset": {"title": "Public Asset Link", "desc": "Whether to create a public asset link after video generation finishes."},
|
||||
"concurrent": {"title": "Concurrency Limit", "desc": "Reverse API concurrency limit."},
|
||||
"timeout": {"title": "Request Timeout", "desc": "Reverse API timeout (seconds)."},
|
||||
"stream_timeout": {"title": "Stream Idle Timeout", "desc": "Streaming idle timeout (seconds)."},
|
||||
"upscale_timing": {"title": "Upscale Timing", "desc": "Basic pool 720p upscale mode: single upscales after each extension round, complete upscales once after all rounds."}
|
||||
},
|
||||
"image": {
|
||||
"timeout": {"title": "Request Timeout", "desc": "WebSocket request timeout (seconds)."},
|
||||
"stream_timeout": {"title": "Stream Idle Timeout", "desc": "WebSocket streaming idle timeout (seconds)."},
|
||||
"final_timeout": {"title": "Final Image Timeout", "desc": "Timeout (seconds) to wait for final image after receiving medium image."},
|
||||
"blocked_grace_seconds": {"title": "Review Grace Seconds", "desc": "Grace seconds for suspected review/censorship after receiving medium image (default 10, configurable)."},
|
||||
"nsfw": {"title": "NSFW Mode", "desc": "Whether to enable NSFW for WebSocket requests."},
|
||||
"medium_min_bytes": {"title": "Medium Min Bytes", "desc": "Minimum byte size for medium quality image detection."},
|
||||
"final_min_bytes": {"title": "Final Min Bytes", "desc": "Minimum byte size for final image detection (typically JPG > 100KB)."},
|
||||
"blocked_parallel_enabled": {"title": "Enable Parallel Compensation", "desc": "Whether to enable parallel compensation when suspected review/blocking occurs."},
|
||||
"blocked_parallel_attempts": {"title": "Block Compensation Concurrency", "desc": "Number of parallel compensation attempts when suspected review/blocking prevents final image."}
|
||||
},
|
||||
"imagine_fast": {
|
||||
"n": {"title": "Generation Count", "desc": "Server-side unified generation count for grok-imagine-1.0-fast only (1-10)."},
|
||||
"size": {"title": "Image Size", "desc": "Server-side unified size for grok-imagine-1.0-fast only."},
|
||||
"response_format": {"title": "Response Format", "desc": "Server-side unified response format for grok-imagine-1.0-fast only."}
|
||||
},
|
||||
"asset": {
|
||||
"upload_concurrent": {"title": "Upload Concurrency", "desc": "Maximum concurrent uploads. Recommended: 30."},
|
||||
"upload_timeout": {"title": "Upload Timeout", "desc": "Upload timeout (seconds). Recommended: 60."},
|
||||
"download_concurrent": {"title": "Download Concurrency", "desc": "Maximum concurrent downloads. Recommended: 30."},
|
||||
"download_timeout": {"title": "Download Timeout", "desc": "Download timeout (seconds). Recommended: 60."},
|
||||
"list_concurrent": {"title": "Query Concurrency", "desc": "Maximum concurrent asset queries. Recommended: 10."},
|
||||
"list_timeout": {"title": "Query Timeout", "desc": "Asset query timeout (seconds). Recommended: 60."},
|
||||
"list_batch_size": {"title": "Query Batch Size", "desc": "Number of tokens per query batch. Recommended: 10."},
|
||||
"delete_concurrent": {"title": "Delete Concurrency", "desc": "Maximum concurrent asset deletions. Recommended: 10."},
|
||||
"delete_timeout": {"title": "Delete Timeout", "desc": "Asset deletion timeout (seconds). Recommended: 60."},
|
||||
"delete_batch_size": {"title": "Delete Batch Size", "desc": "Number of tokens per delete batch. Recommended: 10."}
|
||||
},
|
||||
"voice": {
|
||||
"timeout": {"title": "Request Timeout", "desc": "Voice request timeout (seconds)."}
|
||||
},
|
||||
"token": {
|
||||
"auto_refresh": {"title": "Auto Refresh", "desc": "Whether to enable automatic Token refresh."},
|
||||
"refresh_interval_hours": {"title": "Refresh Interval", "desc": "Time interval (hours) for regular Token refresh."},
|
||||
"super_refresh_interval_hours": {"title": "Super Refresh Interval", "desc": "Time interval (hours) for Super Token refresh."},
|
||||
"fail_threshold": {"title": "Failure Threshold", "desc": "Number of consecutive failures before a Token is marked unavailable."},
|
||||
"save_delay_ms": {"title": "Save Delay", "desc": "Delay (ms) for batching Token change writes."},
|
||||
"usage_flush_interval_sec": {"title": "Usage Flush Interval", "desc": "Minimum interval (seconds) for writing usage data to database."},
|
||||
"reload_interval_sec": {"title": "Sync Interval", "desc": "Token state refresh interval (seconds) in multi-worker scenarios."}
|
||||
},
|
||||
"cache": {
|
||||
"enable_auto_clean": {"title": "Auto Clean", "desc": "Whether to enable automatic cache cleanup based on size limit."},
|
||||
"limit_mb": {"title": "Clean Threshold", "desc": "Cache size threshold (MB) that triggers cleanup."}
|
||||
},
|
||||
"nsfw": {
|
||||
"concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch NSFW enable. Recommended: 10."},
|
||||
"batch_size": {"title": "Batch Size", "desc": "Batch processing count for NSFW enable. Recommended: 50."},
|
||||
"timeout": {"title": "Request Timeout", "desc": "Timeout for NSFW-related requests (seconds). Recommended: 60."}
|
||||
},
|
||||
"usage": {
|
||||
"concurrent": {"title": "Concurrency Limit", "desc": "Maximum concurrent requests for batch usage refresh. Recommended: 10."},
|
||||
"batch_size": {"title": "Batch Size", "desc": "Batch processing count for usage refresh. Recommended: 50."},
|
||||
"timeout": {"title": "Request Timeout", "desc": "Usage query timeout (seconds). Recommended: 60."}
|
||||
}
|
||||
}
|
||||
},
|
||||
"token": {
|
||||
"pageTitle": "Grok2API - Token Mgmt",
|
||||
"title": "Token List",
|
||||
"subtitle": "Manage the Grok2API Token service pool.",
|
||||
"import": "Import",
|
||||
"add": "Add",
|
||||
"statTotal": "Total Tokens",
|
||||
"statActive": "Active",
|
||||
"statCooling": "Rate Limited",
|
||||
"statInvalid": "Invalid",
|
||||
"statChatQuota": "Chat Remaining",
|
||||
"statImageQuota": "Image Remaining",
|
||||
"statChatConsumed": "Chat Consumed",
|
||||
"statImageConsumed": "Image Consumed",
|
||||
"statVideoQuota": "Video Remaining",
|
||||
"statVideoUnavailable": "N/A",
|
||||
"statTotalCalls": "Total Calls",
|
||||
"tabAll": "All",
|
||||
"tabActive": "Active",
|
||||
"tabCooling": "Rate Limited",
|
||||
"tabExpired": "Expired",
|
||||
"tabNsfw": "NSFW On",
|
||||
"tabNoNsfw": "NSFW Off",
|
||||
"statusFilterAria": "Token status filter",
|
||||
"tableToken": "Token",
|
||||
"tableType": "Type",
|
||||
"tableStatus": "Status",
|
||||
"tableQuota": "Quota",
|
||||
"tableQuotaConsumed": "Consumed",
|
||||
"tableNote": "Note",
|
||||
"tableActions": "Actions",
|
||||
"refreshStatus": "Refresh status",
|
||||
"emptyState": "No Tokens yet. Click Import or Add above.",
|
||||
"emptyFilterState": "No results for current filter. Try a different filter.",
|
||||
"selectPage": "Select page",
|
||||
"selectAllFiltered": "Select all",
|
||||
"clearSelection": "Clear selection",
|
||||
"prevPage": "Prev",
|
||||
"nextPage": "Next",
|
||||
"perPage": "{size} / page",
|
||||
"pagination": "Page {current} / {total} \u00b7 {count} items",
|
||||
"batchExport": "Export",
|
||||
"batchRefresh": "Refresh",
|
||||
"batchDisable": "Disable",
|
||||
"batchEnable": "Enable",
|
||||
"batchDelete": "Delete",
|
||||
"importTitle": "Batch Import Tokens",
|
||||
"importTargetPool": "Target Pool",
|
||||
"importTokenList": "Token List (one per line)",
|
||||
"importPlaceholder": "Paste Tokens, one per line...",
|
||||
"startImport": "Start Import",
|
||||
"editTitle": "Edit Token",
|
||||
"addTitle": "Add Token",
|
||||
"editType": "Type",
|
||||
"editQuota": "Quota",
|
||||
"editNote": "Note",
|
||||
"editNotePlaceholder": "Optional note",
|
||||
"tokenEmpty": "Token cannot be empty",
|
||||
"tokenExists": "Token already exists",
|
||||
"confirmDelete": "Are you sure you want to delete this Token?",
|
||||
"confirmDisable": "Are you sure you want to disable this Token?\n{token}",
|
||||
"confirmEnable": "Are you sure you want to enable this Token?\n{token}",
|
||||
"confirmBatchDelete": "Are you sure you want to delete {count} selected Tokens?",
|
||||
"confirmBatchDisable": "Are you sure you want to disable {count} selected Tokens?",
|
||||
"confirmBatchEnable": "Are you sure you want to enable {count} selected Tokens?",
|
||||
"disableToken": "Disable",
|
||||
"enableToken": "Enable",
|
||||
"disableDone": "Token disabled",
|
||||
"enableDone": "Token enabled",
|
||||
"batchDisableDone": "Batch disable complete",
|
||||
"batchEnableDone": "Batch enable complete",
|
||||
"noTokenToDisable": "All selected Tokens are already disabled",
|
||||
"noTokenToEnable": "All selected Tokens are already enabled",
|
||||
"deleteDone": "Delete complete",
|
||||
"refreshDone": "Refresh complete",
|
||||
"refreshSuccess": "Refresh successful",
|
||||
"refreshFailed": "Refresh failed",
|
||||
"refreshError": "Refresh failed: {msg}",
|
||||
"requestError": "Request error",
|
||||
"notValidJson": "Response is not valid JSON (HTTP {status})",
|
||||
"listEmpty": "List is empty",
|
||||
"stopRefresh": "Refresh stopped",
|
||||
"stopDelete": "Delete stopped",
|
||||
"stopNsfw": "NSFW stopped",
|
||||
"nsfwConfirm": "Enable NSFW mode for {count} selected Tokens?",
|
||||
"nsfwEnable": "Enable NSFW",
|
||||
"nsfwDone": "NSFW enable complete",
|
||||
"nsfwResult": "NSFW enable complete: {ok} succeeded, {fail} failed",
|
||||
"nsfwFailed": "Enable failed: {msg}",
|
||||
"emptyResponse": "Empty response (HTTP {status})"
|
||||
},
|
||||
"cache": {
|
||||
"pageTitle": "Grok2API - Cache Mgmt",
|
||||
"title": "Cache Management",
|
||||
"subtitle": "Manage local resources and online asset cache.",
|
||||
"localImages": "Local Images",
|
||||
"localVideos": "Local Videos",
|
||||
"onlineAssets": "Online Assets",
|
||||
"tableFile": "File",
|
||||
"tableSize": "Size",
|
||||
"tableTime": "Time",
|
||||
"tableActions": "Actions",
|
||||
"tableToken": "Token",
|
||||
"tableType": "Type",
|
||||
"tableAssetCount": "Asset Count",
|
||||
"tableLastClear": "Last Cleared",
|
||||
"selectPage": "Select page",
|
||||
"selectAllFiles": "Select all",
|
||||
"clearSelection": "Clear selection",
|
||||
"prevPage": "Prev",
|
||||
"nextPage": "Next",
|
||||
"perPageLabel": "Per page",
|
||||
"perPage": "{size} / page",
|
||||
"pagination": "Page {current} / {total} · {count} items",
|
||||
"notLoaded": "Not loaded",
|
||||
"noAccounts": "No accounts available",
|
||||
"noFiles": "No files",
|
||||
"noTokenAvailable": "No Token available",
|
||||
"cannotConnect": "Cannot connect",
|
||||
"lastClear": "Last cleared: {time}",
|
||||
"clear": "Clear",
|
||||
"clean": "Clean",
|
||||
"confirmClearImage": "Clear all local image cache?",
|
||||
"confirmClearVideo": "Clear all local video cache?",
|
||||
"clearSuccess": "Cleanup successful, freed {size} MB",
|
||||
"clearFailed": "Cleanup failed",
|
||||
"confirmDeleteFile": "Are you sure you want to delete this file?",
|
||||
"confirmBatchDeleteFiles": "Are you sure you want to delete {count} selected files?",
|
||||
"noFilesSelected": "No files selected",
|
||||
"deletedFiles": "Deleted {count} files",
|
||||
"deleteResult": "Delete complete: {success} succeeded, {failed} failed",
|
||||
"loadStatsFailed": "Failed to load statistics",
|
||||
"selectAccountsToLoad": "Please select accounts to load",
|
||||
"selectAccountsToClear": "Please select accounts to clear",
|
||||
"confirmClearAccounts": "Clear online assets for {count} selected accounts?",
|
||||
"confirmClearAccount": "Clear online assets for account {label}?",
|
||||
"batchCleanInProgress": "Batch cleaning online assets, please wait...",
|
||||
"cleanInProgress": "Cleaning online assets, please wait...",
|
||||
"batchCleanDone": "Batch cleanup complete",
|
||||
"cleanResult": "Cleanup complete (succeeded: {success}, failed: {failed})",
|
||||
"cleanFailedEntry": "Cleanup failed",
|
||||
"requestTimeout": "Request timed out or failed",
|
||||
"loadDone": "Load complete",
|
||||
"loadingStatus": "Loading",
|
||||
"loadStopped": "Load stopped",
|
||||
"loadFailedMsg": "Load failed: {msg}",
|
||||
"stoppedLoadRequests": "Remaining load requests stopped",
|
||||
"cleanStopped": "Clean stopped",
|
||||
"cleanFailedMsg": "Clean failed: {msg}",
|
||||
"stoppedCleanRequests": "Remaining clean requests stopped"
|
||||
},
|
||||
"chat": {
|
||||
"pageTitle": "Grok2API - Chat",
|
||||
"title": "Chat",
|
||||
"subtitle": "Chat with Grok via the chat API",
|
||||
"sessions": "Sessions",
|
||||
"newChat": "New",
|
||||
"collapseSidebar": "Collapse",
|
||||
"expandSidebar": "Expand",
|
||||
"sessionList": "Session list",
|
||||
"newSession": "New Session",
|
||||
"ready": "Ready",
|
||||
"emptyState": "Type a message to start a conversation.",
|
||||
"uploadFile": "Upload file",
|
||||
"placeholder": "Ask anything",
|
||||
"settings": "Settings",
|
||||
"send": "Send",
|
||||
"temperature": "Temperature",
|
||||
"topP": "Top P",
|
||||
"systemPrompt": "System Prompt",
|
||||
"systemPromptPlaceholder": "Optional, set system prompt",
|
||||
"fileLabel": "[File]",
|
||||
"compositeContent": "[Composite]",
|
||||
"storageFull": "Local storage is full, some sessions were not saved",
|
||||
"attachmentNoEdit": "Attachment messages cannot be edited yet",
|
||||
"saveEdit": "Save",
|
||||
"saveEditTitle": "Save edit",
|
||||
"cancelEdit": "Cancel",
|
||||
"cancelEditTitle": "Cancel edit",
|
||||
"contentEmpty": "Content cannot be empty",
|
||||
"editMessage": "Edit",
|
||||
"editMessageTitle": "Edit message content",
|
||||
"regenerate": "Regenerate",
|
||||
"regenerateTitle": "Regenerate response from here",
|
||||
"retryTitle": "Retry last response",
|
||||
"editAnswer": "Edit",
|
||||
"editAnswerTitle": "Edit response content",
|
||||
"copyAnswer": "Copy",
|
||||
"copyAnswerTitle": "Copy response content",
|
||||
"feedback": "Feedback",
|
||||
"feedbackTitle": "Feedback to Grok2API",
|
||||
"noContentToCopy": "No content to copy",
|
||||
"noChatToRetry": "No conversation to retry",
|
||||
"requestFailedCheck": "Request failed, please check service status",
|
||||
"requestFailedStatus": "Request failed: {status}",
|
||||
"clickRetry": "Click to retry",
|
||||
"thinking": "Thinking",
|
||||
"thinkingSec": "Thinking {sec}s",
|
||||
"thought": "Thought",
|
||||
"thinkLabel": "Thinking",
|
||||
"empty": "(empty)",
|
||||
"toolWebSearch": "Web search",
|
||||
"toolImageSearch": "Image search",
|
||||
"toolAgentThink": "Reasoning",
|
||||
"toolDefault": "Tool"
|
||||
},
|
||||
"imagine": {
|
||||
"pageTitle": "Grok2API - Imagine Gallery",
|
||||
"title": "Imagine Gallery",
|
||||
"subtitle": "Continuously generate images via WebSocket, real-time base64 gallery.",
|
||||
"genSettings": "Generation Settings",
|
||||
"prompt": "Prompt",
|
||||
"promptPlaceholder": "Describe the image you want, e.g.: futuristic city neon rain at night, wide angle photography",
|
||||
"autoFollow": "Auto Follow",
|
||||
"autoFollowDesc": "Scroll to latest",
|
||||
"autoSave": "Auto Save",
|
||||
"autoSaveDesc": "Auto-save images",
|
||||
"aspectRatio": "Aspect Ratio",
|
||||
"ratio2_3": "2:3 Portrait",
|
||||
"ratio1_1": "1:1 Square",
|
||||
"ratio3_2": "3:2 Landscape",
|
||||
"ratio16_9": "16:9 Wide",
|
||||
"ratio9_16": "9:16 Tall",
|
||||
"concurrent": "Concurrency",
|
||||
"tasks": "{n} tasks",
|
||||
"concurrentTask1": "1 task",
|
||||
"concurrentTask2": "2 tasks",
|
||||
"concurrentTask3": "3 tasks",
|
||||
"autoFilter": "Auto Filter",
|
||||
"autoFilterDesc": "Filter substandard images",
|
||||
"nsfwLabel": "NSFW",
|
||||
"nsfwOn": "On",
|
||||
"nsfwOff": "Off",
|
||||
"saveLocation": "Save Location",
|
||||
"browserDefault": "Browser default location",
|
||||
"reverseOrder": "Reverse Order",
|
||||
"reverseOrderDesc": "Show newest on top",
|
||||
"connectionStatus": "Connection Status",
|
||||
"connectionMode": "Connection Mode",
|
||||
"connectionModeAria": "Connection mode",
|
||||
"imageCount": "Image Count",
|
||||
"activeTasks": "Active Tasks",
|
||||
"avgTime": "Avg Time",
|
||||
"gallery": "Gallery",
|
||||
"waitingTitle": "Waiting for connection",
|
||||
"waitingSubtitle": "Generated images will appear here after starting a task",
|
||||
"start": "Start",
|
||||
"batch": "Batch",
|
||||
"batchDownloadTitle": "Batch download",
|
||||
"selectAll": "Select all",
|
||||
"deselectAll": "Deselect all",
|
||||
"download": "Download",
|
||||
"startedTasks": "Started {count} concurrent tasks",
|
||||
"startedTasksSSE": "Started {count} concurrent tasks (SSE)",
|
||||
"generatingSSE": "Generating (SSE)",
|
||||
"selectFolder": "Selected folder: {name}",
|
||||
"selectFolderFailed": "Failed to select folder",
|
||||
"noImagesSelected": "Please select images to download first",
|
||||
"jszipFailed": "JSZip library failed to load, please refresh and try again",
|
||||
"packing": "Packing {count} images...",
|
||||
"packingBtn": "Packing...",
|
||||
"packingProgress": "Packing... ({done}/{total})",
|
||||
"noImagesDownloaded": "No images were downloaded successfully",
|
||||
"generatingZip": "Generating ZIP...",
|
||||
"packSuccess": "Successfully packed {count} images",
|
||||
"packFailed": "Packing failed, please try again"
|
||||
},
|
||||
"video": {
|
||||
"pageTitle": "Grok2API - Video Generation",
|
||||
"title": "Video Generation",
|
||||
"subtitle": "Generate short videos with up to 7 reference images, @图N placeholders, and preset styles.",
|
||||
"startGenerate": "Generate",
|
||||
"genSettings": "Generation Settings",
|
||||
"prompt": "Prompt",
|
||||
"promptPlaceholder": "e.g.: @图1 neon rainy street at night, @图2 subject looking back and smiling, slow motion, film grain",
|
||||
"promptTip": "Use @图1 to @图7 in the prompt to reference images by upload order.",
|
||||
"referenceImage": "Reference Image",
|
||||
"referenceImagePlaceholder": "One https://... or data:image/... per line, up to 7 images",
|
||||
"aspectRatio": "Aspect Ratio",
|
||||
"ratio3_2": "3:2 Landscape",
|
||||
"ratio2_3": "2:3 Portrait",
|
||||
"ratio16_9": "16:9 Wide",
|
||||
"ratio9_16": "9:16 Tall",
|
||||
"ratio1_1": "1:1 Square",
|
||||
"duration": "Duration",
|
||||
"seconds": "{n}s",
|
||||
"resolution": "Resolution",
|
||||
"stylePreset": "Style Preset",
|
||||
"upload": "Upload",
|
||||
"clearImage": "Clear",
|
||||
"runStatus": "Run Status",
|
||||
"elapsedTime": "Elapsed {sec}s",
|
||||
"elapsedTimeNone": "Elapsed -",
|
||||
"metaRatio": "Ratio",
|
||||
"metaDuration": "Duration",
|
||||
"metaResolution": "Resolution",
|
||||
"metaPreset": "Preset",
|
||||
"videoPreview": "Video Preview",
|
||||
"clearPreview": "Clear",
|
||||
"waitingGenerate": "Waiting for video generation",
|
||||
"videoTitle": "Video {n}",
|
||||
"open": "Open",
|
||||
"generatingPlaceholder": "Generating...",
|
||||
"superResolution": "Super Resolution",
|
||||
"superResolutionInProgress": "Super resolution in progress",
|
||||
"alreadyGenerating": "Already generating",
|
||||
"referenceConflict": "Reference images: choose either URL/Base64 list or file upload",
|
||||
"referenceLimit": "A maximum of 7 reference images is supported",
|
||||
"noReferenceSelected": "No reference images selected",
|
||||
"downloadFailed": "Download failed, please check if the video link is accessible",
|
||||
"sec6": "6s",
|
||||
"sec10": "10s",
|
||||
"sec15": "15s"
|
||||
},
|
||||
"voice": {
|
||||
"pageTitle": "Grok2API - LiveKit Voice",
|
||||
"title": "LiveKit Voice",
|
||||
"subtitle": "LiveKit voice session, connect to Grok Voice.",
|
||||
"startSession": "Start Session",
|
||||
"stopSession": "Stop Session",
|
||||
"connectionSettings": "Connection Settings",
|
||||
"voiceLabel": "Voice",
|
||||
"personalityLabel": "Personality",
|
||||
"speedLabel": "Speed",
|
||||
"settingsHint": "Tip: Voice / Personality settings are sent to the server before connecting.",
|
||||
"sessionLog": "Session Log",
|
||||
"clearLog": "Clear",
|
||||
"copyLog": "Copy",
|
||||
"sessionStatus": "Session Status",
|
||||
"audioOutput": "Audio Output",
|
||||
"audioHint": "Subscribed audio tracks will be automatically inserted here.",
|
||||
"livekitSDKError": "Error: LiveKit SDK failed to load properly, please refresh the page",
|
||||
"livekitLoadFailed": "LiveKit SDK failed to load",
|
||||
"secureContextBrowser": "Please use a modern browser and allow microphone access",
|
||||
"secureContextHTTPS": "Please use HTTPS or access from localhost",
|
||||
"secureContextError": "Current environment does not support microphone access, {hint}",
|
||||
"connectingStatus": "Connecting",
|
||||
"fetchingToken": "Fetching Token...",
|
||||
"fetchTokenFailed": "Failed to get Token: {status}",
|
||||
"fetchTokenSuccess": "Token obtained successfully",
|
||||
"participantConnected": "Participant connected: {identity}",
|
||||
"participantDisconnected": "Participant disconnected: {identity}",
|
||||
"trackSubscribed": "Track subscribed: {kind}",
|
||||
"disconnected": "Disconnected",
|
||||
"connectedToServer": "Connected to LiveKit server",
|
||||
"inCall": "In call",
|
||||
"openingMic": "Opening microphone...",
|
||||
"voiceEnabled": "Voice enabled",
|
||||
"voiceConnected": "Voice connected successfully",
|
||||
"errorPrefix": "Error: {msg}",
|
||||
"logCopied": "Log copied",
|
||||
"copyLogFailed": "Copy failed, please select manually"
|
||||
}
|
||||
}
|
||||
@@ -1,589 +0,0 @@
|
||||
{
|
||||
"common": {
|
||||
"save": "保存",
|
||||
"cancel": "取消",
|
||||
"confirm": "确认",
|
||||
"delete": "删除",
|
||||
"loading": "加载中...",
|
||||
"invalidKey": "密钥无效",
|
||||
"connectionFailed": "连接失败",
|
||||
"requestFailed": "请求失败",
|
||||
"operationSuccess": "操作成功",
|
||||
"gotIt": "我知道了",
|
||||
"notice": "提示",
|
||||
"rateLimitNotice": "GROK 官方网页更新后未真实暴露 rate-limits 接口,导致无法准确计算 Token 剩余,请耐心等待官方接口上线,目前自动刷新后会更新为 8 次",
|
||||
"pleaseConfirm": "请确认",
|
||||
"ok": "确定",
|
||||
"close": "关闭",
|
||||
"error": "错误",
|
||||
"unknownError": "未知错误",
|
||||
"connectionInterrupted": "连接中断",
|
||||
"taskInProgress": "当前有任务进行中",
|
||||
"taskNoPause": "当前任务不支持暂停",
|
||||
"batchNoPause": "当前批量任务不支持暂停",
|
||||
"waitTaskFinish": "请等待当前任务结束",
|
||||
"pause": "暂停",
|
||||
"stop": "终止",
|
||||
"selectAll": "全选",
|
||||
"selected": "已选择",
|
||||
"items": "项",
|
||||
"export": "导出",
|
||||
"refresh": "刷新",
|
||||
"load": "加载",
|
||||
"files": "个文件",
|
||||
"view": "查看",
|
||||
"retry": "重试",
|
||||
"copy": "复制",
|
||||
"edit": "编辑",
|
||||
"loadFailed": "加载失败",
|
||||
"loadError": "加载失败: {msg}",
|
||||
"saveFailed": "保存失败",
|
||||
"saveError": "保存错误: {msg}",
|
||||
"deleteFailed": "删除失败",
|
||||
"deleteSuccess": "删除成功",
|
||||
"notConnected": "未连接",
|
||||
"connecting": "连接中",
|
||||
"connected": "连接正常",
|
||||
"connectionError": "连接错误",
|
||||
"generating": "生成中",
|
||||
"done": "完成",
|
||||
"failed": "失败",
|
||||
"stopped": "已停止",
|
||||
"terminated": "已终止",
|
||||
"sending": "发送中",
|
||||
"fileReadFailed": "文件读取失败",
|
||||
"noFileSelected": "未选择文件",
|
||||
"configurePublicKey": "请先配置 Public Key",
|
||||
"enterPrompt": "请输入提示词",
|
||||
"enterContent": "请输入内容",
|
||||
"alreadyRunning": "已在运行中",
|
||||
"createTaskFailed": "创建任务失败",
|
||||
"copyFailed": "复制失败",
|
||||
"copied": "已复制",
|
||||
"generationFailed": "生成失败",
|
||||
"partialError": "部分异常",
|
||||
"loadingInProgress": "正在加载中,请稍候",
|
||||
"cleaningInProgress": "正在清理中,请稍候",
|
||||
"noTokenSelected": "未选择 Token",
|
||||
"clearCache": "清空缓存",
|
||||
"failureDetails": "失败详情",
|
||||
"retryFailed": "重试失败项"
|
||||
},
|
||||
"nav": {
|
||||
"tokenManage": "Token管理",
|
||||
"configManage": "配置管理",
|
||||
"cacheManage": "缓存管理",
|
||||
"chat": "Chat 聊天",
|
||||
"imagine": "Imagine 瀑布流",
|
||||
"video": "Video 视频生成",
|
||||
"voice": "LiveKit 陪聊",
|
||||
"feedback": "反馈",
|
||||
"logout": "退出",
|
||||
"adminPanel": "管理后台",
|
||||
"storageMode": "存储模式"
|
||||
},
|
||||
"login": {
|
||||
"adminPageTitle": "Grok2API - 登录",
|
||||
"adminTitle": "管理后台",
|
||||
"adminSubtitle": "请输入后台密码以继续",
|
||||
"adminPlaceholder": "后台密码 (app_key)",
|
||||
"continue": "继续",
|
||||
"publicPageTitle": "Grok2API - Public",
|
||||
"publicTitle": "Public Access",
|
||||
"publicSubtitle": "请输入 Public Key(如未配置可直接进入)",
|
||||
"publicPlaceholder": "Public Key",
|
||||
"enter": "进入",
|
||||
"goToAdmin": "进入管理后台"
|
||||
},
|
||||
"config": {
|
||||
"pageTitle": "Grok2API - 配置管理",
|
||||
"title": "配置管理",
|
||||
"subtitle": "管理 API 密钥及系统参数设置。",
|
||||
"saving": "保存中...",
|
||||
"saved": "成功",
|
||||
"configSaved": "配置已保存",
|
||||
"invalidJson": "无效的 JSON: {field}",
|
||||
"appKeyRequired": "app_key 不能为空(后台密码)",
|
||||
"flaresolverrRequired": "启用自动刷新时必须填写 FlareSolverr 地址",
|
||||
"generate": "生成",
|
||||
"publicAccess": "功能玩法",
|
||||
"noDesc": "暂无说明,请参考配置文档。",
|
||||
"sectionFallback": "{section} 设置",
|
||||
"sections": {
|
||||
"app": "应用设置",
|
||||
"proxy": "代理配置",
|
||||
"retry": "重试策略",
|
||||
"chat": "对话配置",
|
||||
"video": "视频配置",
|
||||
"image": "图像配置",
|
||||
"imagine_fast": "Imagine Fast 配置",
|
||||
"asset": "资产配置",
|
||||
"voice": "语音配置",
|
||||
"token": "Token 池管理",
|
||||
"cache": "缓存管理",
|
||||
"nsfw": "NSFW 配置",
|
||||
"usage": "Usage 配置"
|
||||
},
|
||||
"sectionDescs": {
|
||||
"proxy": "配置不正确将导致 403 错误。服务首次请求 Grok 时的 IP 必须与获取 CF Clearance 时的 IP 一致,后续服务器请求 IP 变化不会导致 403。"
|
||||
},
|
||||
"fields": {
|
||||
"app": {
|
||||
"api_key": {"title": "API 密钥", "desc": "调用 Grok2API 服务的 Token(可选,支持多个,逗号分隔或数组)。"},
|
||||
"app_key": {"title": "后台密码", "desc": "登录 Grok2API 管理后台的密码(必填)。"},
|
||||
"function_enabled": {"title": "启用功能玩法", "desc": "是否启用功能玩法入口(关闭则功能玩法页面不可访问)。"},
|
||||
"function_key": {"title": "Function 密码", "desc": "功能玩法页面的访问密码(可选)。"},
|
||||
"app_url": {"title": "应用地址", "desc": "当前 Grok2API 服务的外部访问 URL,用于文件链接访问。"},
|
||||
"image_format": {"title": "图片格式", "desc": "默认生成的图片格式(url 或 base64)。"},
|
||||
"video_format": {"title": "视频格式", "desc": "默认生成的视频格式(html 或 url,url 为处理后的链接)。"},
|
||||
"temporary": {"title": "临时对话", "desc": "是否默认启用临时对话模式。"},
|
||||
"disable_memory": {"title": "禁用记忆", "desc": "是否默认禁用 Grok 记忆功能。"},
|
||||
"stream": {"title": "流式响应", "desc": "是否默认启用流式输出。"},
|
||||
"thinking": {"title": "思维链", "desc": "是否默认启用思维链输出。"},
|
||||
"dynamic_statsig": {"title": "动态指纹", "desc": "是否默认启用动态生成 Statsig 指纹。"},
|
||||
"custom_instruction": {"title": "自定义指令", "desc": "多行文本,会透传为 Grok 请求参数 customPersonality。"},
|
||||
"filter_tags": {"title": "过滤标签", "desc": "设置自动过滤 Grok 响应中的特殊标签。"}
|
||||
},
|
||||
"proxy": {
|
||||
"base_proxy_url": {"title": "基础代理 URL", "desc": "代理请求到 Grok 官网的基础服务地址。"},
|
||||
"asset_proxy_url": {"title": "资源代理 URL", "desc": "代理请求到 Grok 官网的静态资源(图片/视频)地址。"},
|
||||
"skip_proxy_ssl_verify": {"title": "跳过代理 SSL 校验", "desc": "代理使用自签名证书时启用(仅放行代理证书校验)。"},
|
||||
"enabled": {"title": "启用 CF 自动刷新", "desc": "启用后将通过 FlareSolverr 自动获取 cf_clearance。"},
|
||||
"flaresolverr_url": {"title": "FlareSolverr 地址", "desc": "FlareSolverr 服务的 HTTP 地址(如 http://flaresolverr:8191)。"},
|
||||
"refresh_interval": {"title": "刷新间隔(秒)", "desc": "自动刷新 cf_clearance 的时间间隔,建议不低于 300 秒。"},
|
||||
"timeout": {"title": "挑战超时(秒)", "desc": "等待 FlareSolverr 解决 CF 挑战的最大时间。"},
|
||||
"cf_clearance": {"title": "CF Clearance", "desc": "Cloudflare Clearance Cookie,用于绕过反爬虫验证。启用自动刷新时由系统自动管理。"},
|
||||
"browser": {"title": "浏览器指纹", "desc": "curl_cffi 浏览器指纹标识(如 chrome136)。启用自动刷新时由系统自动管理。"},
|
||||
"user_agent": {"title": "User-Agent", "desc": "HTTP 请求的 User-Agent 字符串。启用自动刷新时由系统自动管理。"}
|
||||
},
|
||||
"retry": {
|
||||
"max_retry": {"title": "最大重试次数", "desc": "请求 Grok 服务失败时的最大重试次数。"},
|
||||
"retry_status_codes": {"title": "重试状态码", "desc": "触发重试的 HTTP 状态码列表。"},
|
||||
"reset_session_status_codes": {"title": "重建状态码", "desc": "触发重建 session 的 HTTP 状态码列表(用于轮换代理)。"},
|
||||
"retry_backoff_base": {"title": "退避基数", "desc": "重试退避的基础延迟(秒)。"},
|
||||
"retry_backoff_factor": {"title": "退避倍率", "desc": "重试退避的指数放大系数。"},
|
||||
"retry_backoff_max": {"title": "退避上限", "desc": "单次重试等待的最大延迟(秒)。"},
|
||||
"retry_budget": {"title": "退避预算", "desc": "单次请求的最大重试总耗时(秒)。"}
|
||||
},
|
||||
"chat": {
|
||||
"concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"},
|
||||
"timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"},
|
||||
"stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"}
|
||||
},
|
||||
"video": {
|
||||
"enable_public_asset": {"title": "公开资产链接", "desc": "是否开启生成结束后创建 Public 资产。"},
|
||||
"concurrent": {"title": "并发上限", "desc": "Reverse 接口并发上限。"},
|
||||
"timeout": {"title": "请求超时", "desc": "Reverse 接口超时时间(秒)。"},
|
||||
"stream_timeout": {"title": "流空闲超时", "desc": "流式空闲超时时间(秒)。"},
|
||||
"upscale_timing": {"title": "超分时机", "desc": "Basic 号池 720p 超分模式:single 为每轮扩展后超分,complete 为全部扩展完成后再超分。"}
|
||||
},
|
||||
"image": {
|
||||
"timeout": {"title": "请求超时", "desc": "WebSocket 请求超时时间(秒)。"},
|
||||
"stream_timeout": {"title": "流空闲超时", "desc": "WebSocket 流式空闲超时时间(秒)。"},
|
||||
"final_timeout": {"title": "最终图超时", "desc": "收到中等图后等待最终图的超时秒数。"},
|
||||
"blocked_grace_seconds": {"title": "审查宽限秒数", "desc": "收到中等图后,判定疑似被审查的宽限秒数(默认 10 秒,可自定义)。"},
|
||||
"nsfw": {"title": "NSFW 模式", "desc": "WebSocket 请求是否启用 NSFW。"},
|
||||
"medium_min_bytes": {"title": "中等图最小字节", "desc": "判定中等质量图的最小字节数。"},
|
||||
"final_min_bytes": {"title": "最终图最小字节", "desc": "判定最终图的最小字节数(通常 JPG > 100KB)。"},
|
||||
"blocked_parallel_enabled": {"title": "启用并行补偿", "desc": "疑似审查/拦截时,是否启用并行补偿生成。"},
|
||||
"blocked_parallel_attempts": {"title": "拦截补偿并发次数", "desc": "疑似审查/拦截导致无最终图时,自动并行补偿生成次数。"}
|
||||
},
|
||||
"imagine_fast": {
|
||||
"n": {"title": "生成数量", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一生成数量(1-10)。"},
|
||||
"size": {"title": "图片尺寸", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一尺寸。"},
|
||||
"response_format": {"title": "响应格式", "desc": "仅用于 grok-imagine-1.0-fast 的服务端统一返回格式。"}
|
||||
},
|
||||
"asset": {
|
||||
"upload_concurrent": {"title": "上传并发", "desc": "上传接口的最大并发数。推荐 30。"},
|
||||
"upload_timeout": {"title": "上传超时", "desc": "上传接口超时时间(秒)。推荐 60。"},
|
||||
"download_concurrent": {"title": "下载并发", "desc": "下载接口的最大并发数。推荐 30。"},
|
||||
"download_timeout": {"title": "下载超时", "desc": "下载接口超时时间(秒)。推荐 60。"},
|
||||
"list_concurrent": {"title": "查询并发", "desc": "资产查询接口的最大并发数。推荐 10。"},
|
||||
"list_timeout": {"title": "查询超时", "desc": "资产查询接口超时时间(秒)。推荐 60。"},
|
||||
"list_batch_size": {"title": "查询批次大小", "desc": "单次查询可处理的 Token 数量。推荐 10。"},
|
||||
"delete_concurrent": {"title": "删除并发", "desc": "资产删除接口的最大并发数。推荐 10。"},
|
||||
"delete_timeout": {"title": "删除超时", "desc": "资产删除接口超时时间(秒)。推荐 60。"},
|
||||
"delete_batch_size": {"title": "删除批次大小", "desc": "单次删除可处理的 Token 数量。推荐 10。"}
|
||||
},
|
||||
"voice": {
|
||||
"timeout": {"title": "请求超时", "desc": "Voice 请求超时时间(秒)。"}
|
||||
},
|
||||
"token": {
|
||||
"auto_refresh": {"title": "自动刷新", "desc": "是否开启 Token 自动刷新机制。"},
|
||||
"refresh_interval_hours": {"title": "刷新间隔", "desc": "普通 Token 刷新的时间间隔(小时)。"},
|
||||
"super_refresh_interval_hours": {"title": "Super 刷新间隔", "desc": "Super Token 刷新的时间间隔(小时)。"},
|
||||
"fail_threshold": {"title": "失败阈值", "desc": "单个 Token 连续失败多少次后被标记为不可用。"},
|
||||
"save_delay_ms": {"title": "保存延迟", "desc": "Token 变更合并写入的延迟(毫秒)。"},
|
||||
"usage_flush_interval_sec": {"title": "用量落库间隔", "desc": "用量类字段写入数据库的最小间隔(秒)。"},
|
||||
"reload_interval_sec": {"title": "同步间隔", "desc": "多 worker 场景下 Token 状态刷新间隔(秒)。"}
|
||||
},
|
||||
"cache": {
|
||||
"enable_auto_clean": {"title": "自动清理", "desc": "是否启用缓存自动清理,开启后按上限自动回收。"},
|
||||
"limit_mb": {"title": "清理阈值", "desc": "缓存大小阈值(MB),超过阈值会触发清理。"}
|
||||
},
|
||||
"nsfw": {
|
||||
"concurrent": {"title": "并发上限", "desc": "批量开启 NSFW 模式时的并发请求上限。推荐 10。"},
|
||||
"batch_size": {"title": "批次大小", "desc": "批量开启 NSFW 模式的单批处理数量。推荐 50。"},
|
||||
"timeout": {"title": "请求超时", "desc": "NSFW 开启相关请求的超时时间(秒)。推荐 60。"}
|
||||
},
|
||||
"usage": {
|
||||
"concurrent": {"title": "并发上限", "desc": "批量刷新用量时的并发请求上限。推荐 10。"},
|
||||
"batch_size": {"title": "批次大小", "desc": "批量刷新用量的单批处理数量。推荐 50。"},
|
||||
"timeout": {"title": "请求超时", "desc": "用量查询接口的超时时间(秒)。推荐 60。"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"token": {
|
||||
"pageTitle": "Grok2API - Token 管理",
|
||||
"title": "Token 列表",
|
||||
"subtitle": "管理 Grok2API 的 Token 服务号池。",
|
||||
"import": "导入",
|
||||
"add": "添加",
|
||||
"statTotal": "Token 总数",
|
||||
"statActive": "Token 正常",
|
||||
"statCooling": "Token 限流",
|
||||
"statInvalid": "Token 失效",
|
||||
"statChatQuota": "Chat 剩余",
|
||||
"statImageQuota": "Image 剩余",
|
||||
"statChatConsumed": "Chat 已消耗",
|
||||
"statImageConsumed": "Image 已消耗",
|
||||
"statVideoQuota": "Video 剩余",
|
||||
"statVideoUnavailable": "无法统计",
|
||||
"statTotalCalls": "总调用次数",
|
||||
"tabAll": "全部",
|
||||
"tabActive": "正常",
|
||||
"tabCooling": "限流",
|
||||
"tabExpired": "失效",
|
||||
"tabNsfw": "已开 NSFW",
|
||||
"tabNoNsfw": "未开 NSFW",
|
||||
"statusFilterAria": "Token 状态筛选",
|
||||
"tableToken": "Token",
|
||||
"tableType": "类型",
|
||||
"tableStatus": "状态",
|
||||
"tableQuota": "额度",
|
||||
"tableQuotaConsumed": "已消耗",
|
||||
"tableNote": "备注",
|
||||
"tableActions": "操作",
|
||||
"refreshStatus": "刷新状态",
|
||||
"emptyState": "暂无 Token,请点击右上角导入或添加。",
|
||||
"emptyFilterState": "当前筛选无结果,请切换筛选条件。",
|
||||
"selectPage": "全选本页",
|
||||
"selectAllFiltered": "全选全部",
|
||||
"clearSelection": "取消全选",
|
||||
"prevPage": "上一页",
|
||||
"nextPage": "下一页",
|
||||
"perPage": "{size} / 页",
|
||||
"pagination": "第 {current} / {total} 页 · 共 {count} 条",
|
||||
"batchExport": "导出",
|
||||
"batchRefresh": "刷新",
|
||||
"batchDisable": "禁用",
|
||||
"batchEnable": "启用",
|
||||
"batchDelete": "删除",
|
||||
"importTitle": "批量导入 Token",
|
||||
"importTargetPool": "目标 Pool",
|
||||
"importTokenList": "Token 列表 (每行一个)",
|
||||
"importPlaceholder": "粘贴 Token,一行一个...",
|
||||
"startImport": "开始导入",
|
||||
"editTitle": "编辑 Token",
|
||||
"addTitle": "添加 Token",
|
||||
"editType": "类型",
|
||||
"editQuota": "额度",
|
||||
"editNote": "备注",
|
||||
"editNotePlaceholder": "可选备注",
|
||||
"tokenEmpty": "Token 不能为空",
|
||||
"tokenExists": "Token 已存在",
|
||||
"confirmDelete": "确定要删除此 Token 吗?",
|
||||
"confirmDisable": "确定要禁用该 Token 吗?\n{token}",
|
||||
"confirmEnable": "确定要启用该 Token 吗?\n{token}",
|
||||
"confirmBatchDelete": "确定要删除选中的 {count} 个 Token 吗?",
|
||||
"confirmBatchDisable": "确定要禁用选中的 {count} 个 Token 吗?",
|
||||
"confirmBatchEnable": "确定要启用选中的 {count} 个 Token 吗?",
|
||||
"disableToken": "禁用",
|
||||
"enableToken": "启用",
|
||||
"disableDone": "Token 已禁用",
|
||||
"enableDone": "Token 已启用",
|
||||
"batchDisableDone": "批量禁用完成",
|
||||
"batchEnableDone": "批量启用完成",
|
||||
"noTokenToDisable": "选中的 Token 已全部是禁用状态",
|
||||
"noTokenToEnable": "选中的 Token 已全部是启用状态",
|
||||
"deleteDone": "删除完成",
|
||||
"refreshDone": "刷新完成",
|
||||
"refreshSuccess": "刷新成功",
|
||||
"refreshFailed": "刷新失败",
|
||||
"refreshError": "刷新失败: {msg}",
|
||||
"requestError": "请求错误",
|
||||
"notValidJson": "响应不是有效 JSON (HTTP {status})",
|
||||
"listEmpty": "列表为空",
|
||||
"stopRefresh": "已终止刷新",
|
||||
"stopDelete": "已终止删除",
|
||||
"stopNsfw": "已终止 NSFW",
|
||||
"nsfwConfirm": "是否为选中的 {count} 个 Token 开启 NSFW 模式?",
|
||||
"nsfwEnable": "开启 NSFW",
|
||||
"nsfwDone": "NSFW 开启完成",
|
||||
"nsfwResult": "NSFW 开启完成:成功 {ok},失败 {fail}",
|
||||
"nsfwFailed": "开启失败: {msg}",
|
||||
"emptyResponse": "空响应 (HTTP {status})"
|
||||
},
|
||||
"cache": {
|
||||
"pageTitle": "Grok2API - 缓存管理",
|
||||
"title": "缓存管理",
|
||||
"subtitle": "管理本地资源与在线资产缓存。",
|
||||
"localImages": "本地图片",
|
||||
"localVideos": "本地视频",
|
||||
"onlineAssets": "在线资产",
|
||||
"tableFile": "文件",
|
||||
"tableSize": "大小",
|
||||
"tableTime": "时间",
|
||||
"tableActions": "操作",
|
||||
"tableToken": "Token",
|
||||
"tableType": "类型",
|
||||
"tableAssetCount": "资产数",
|
||||
"tableLastClear": "上次清空时间",
|
||||
"selectPage": "全选本页",
|
||||
"selectAllFiles": "全选全部",
|
||||
"clearSelection": "取消全选",
|
||||
"prevPage": "上一页",
|
||||
"nextPage": "下一页",
|
||||
"perPageLabel": "每页",
|
||||
"perPage": "{size} / 页",
|
||||
"pagination": "第 {current} / {total} 页 · 共 {count} 条",
|
||||
"notLoaded": "未加载",
|
||||
"noAccounts": "暂无可用账号",
|
||||
"noFiles": "暂无文件",
|
||||
"noTokenAvailable": "无可用 Token",
|
||||
"cannotConnect": "无法连接",
|
||||
"lastClear": "上次清空:{time}",
|
||||
"clear": "清空",
|
||||
"clean": "清理",
|
||||
"confirmClearImage": "确定要清空本地图片缓存吗?",
|
||||
"confirmClearVideo": "确定要清空本地视频缓存吗?",
|
||||
"clearSuccess": "清理成功,释放 {size} MB",
|
||||
"clearFailed": "清理失败",
|
||||
"confirmDeleteFile": "确定要删除该文件吗?",
|
||||
"confirmBatchDeleteFiles": "确定要删除选中的 {count} 个文件吗?",
|
||||
"noFilesSelected": "未选择文件",
|
||||
"deletedFiles": "已删除 {count} 个文件",
|
||||
"deleteResult": "删除完成:成功 {success},失败 {failed}",
|
||||
"loadStatsFailed": "加载统计失败",
|
||||
"selectAccountsToLoad": "请选择要加载的账号",
|
||||
"selectAccountsToClear": "请选择要清空的账号",
|
||||
"confirmClearAccounts": "确定要清空选中的 {count} 个账号在线资产吗?",
|
||||
"confirmClearAccount": "确定要清空账号 {label} 的在线资产吗?",
|
||||
"batchCleanInProgress": "正在批量清理在线资产,请稍候...",
|
||||
"cleanInProgress": "正在清理在线资产,请稍候...",
|
||||
"batchCleanDone": "批量清理完成",
|
||||
"cleanResult": "清理完成 (成功: {success}, 失败: {failed})",
|
||||
"cleanFailedEntry": "清理失败",
|
||||
"requestTimeout": "请求超时或失败",
|
||||
"loadDone": "加载完成",
|
||||
"loadingStatus": "加载中",
|
||||
"loadStopped": "已终止加载",
|
||||
"loadFailedMsg": "加载失败: {msg}",
|
||||
"stoppedLoadRequests": "已终止剩余加载请求",
|
||||
"cleanStopped": "已终止清理",
|
||||
"cleanFailedMsg": "清理失败: {msg}",
|
||||
"stoppedCleanRequests": "已终止剩余清理请求"
|
||||
},
|
||||
"chat": {
|
||||
"pageTitle": "Grok2API - Chat 聊天",
|
||||
"title": "Chat 聊天",
|
||||
"subtitle": "通过 chat 接口与 Grok 进行会话聊天",
|
||||
"sessions": "会话",
|
||||
"newChat": "新增",
|
||||
"collapseSidebar": "折叠",
|
||||
"expandSidebar": "展开",
|
||||
"sessionList": "会话列表",
|
||||
"newSession": "新会话",
|
||||
"ready": "就绪",
|
||||
"emptyState": "输入一条消息开始对话。",
|
||||
"uploadFile": "上传文件",
|
||||
"placeholder": "询问任何内容",
|
||||
"settings": "设置",
|
||||
"send": "发送",
|
||||
"temperature": "温度",
|
||||
"topP": "Top P",
|
||||
"systemPrompt": "System Prompt",
|
||||
"systemPromptPlaceholder": "可选,设置系统提示词",
|
||||
"fileLabel": "[文件]",
|
||||
"compositeContent": "[复合内容]",
|
||||
"storageFull": "本地存储空间不足,部分会话未保存",
|
||||
"attachmentNoEdit": "附件消息暂不支持编辑",
|
||||
"saveEdit": "保存",
|
||||
"saveEditTitle": "保存编辑",
|
||||
"cancelEdit": "取消",
|
||||
"cancelEditTitle": "取消编辑",
|
||||
"contentEmpty": "内容不能为空",
|
||||
"editMessage": "编辑",
|
||||
"editMessageTitle": "编辑消息内容",
|
||||
"regenerate": "重新生成",
|
||||
"regenerateTitle": "从此处重新生成回复",
|
||||
"retryTitle": "重试上一条回答",
|
||||
"editAnswer": "编辑",
|
||||
"editAnswerTitle": "编辑回答内容",
|
||||
"copyAnswer": "复制",
|
||||
"copyAnswerTitle": "复制回答内容",
|
||||
"feedback": "反馈",
|
||||
"feedbackTitle": "反馈到 Grok2API",
|
||||
"noContentToCopy": "暂无内容可复制",
|
||||
"noChatToRetry": "没有可重试的对话",
|
||||
"requestFailedCheck": "请求失败,请检查服务状态",
|
||||
"requestFailedStatus": "请求失败: {status}",
|
||||
"clickRetry": "点击重试",
|
||||
"thinking": "思考中",
|
||||
"thinkingSec": "思考 {sec} 秒",
|
||||
"thought": "已思考",
|
||||
"thinkLabel": "思考",
|
||||
"empty": "(空)",
|
||||
"toolWebSearch": "网页搜索",
|
||||
"toolImageSearch": "图片搜索",
|
||||
"toolAgentThink": "思考推理",
|
||||
"toolDefault": "工具"
|
||||
},
|
||||
"imagine": {
|
||||
"pageTitle": "Grok2API - Imagine 瀑布流",
|
||||
"title": "Imagine 瀑布流",
|
||||
"subtitle": "通过 WebSocket 持续生成图片,实时展示 base64 瀑布流。",
|
||||
"genSettings": "生成设置",
|
||||
"prompt": "提示词",
|
||||
"promptPlaceholder": "描述你想要的画面,例如:未来城市霓虹雨夜,广角摄影",
|
||||
"autoFollow": "自动跟随",
|
||||
"autoFollowDesc": "滚动到最新",
|
||||
"autoSave": "自动保存",
|
||||
"autoSaveDesc": "自动保存图片",
|
||||
"aspectRatio": "宽高比",
|
||||
"ratio2_3": "2:3 竖图",
|
||||
"ratio1_1": "1:1 方图",
|
||||
"ratio3_2": "3:2 横图",
|
||||
"ratio16_9": "16:9 宽屏",
|
||||
"ratio9_16": "9:16 竖屏",
|
||||
"concurrent": "并发数量",
|
||||
"tasks": "{n} 个任务",
|
||||
"concurrentTask1": "1 个任务",
|
||||
"concurrentTask2": "2 个任务",
|
||||
"concurrentTask3": "3 个任务",
|
||||
"autoFilter": "自动过滤",
|
||||
"autoFilterDesc": "过滤不达标图片",
|
||||
"nsfwLabel": "是否 NSFW",
|
||||
"nsfwOn": "开启",
|
||||
"nsfwOff": "关闭",
|
||||
"saveLocation": "保存位置",
|
||||
"browserDefault": "浏览器默认位置",
|
||||
"reverseOrder": "反向新增",
|
||||
"reverseOrderDesc": "最新显示在上方",
|
||||
"connectionStatus": "连接状态",
|
||||
"connectionMode": "连接模式",
|
||||
"connectionModeAria": "连接模式",
|
||||
"imageCount": "图片数量",
|
||||
"activeTasks": "活跃任务",
|
||||
"avgTime": "平均耗时",
|
||||
"gallery": "瀑布流",
|
||||
"waitingTitle": "等待连接中",
|
||||
"waitingSubtitle": "启动任务后,生成的图片会自动汇聚到这里",
|
||||
"start": "开始",
|
||||
"batch": "批量",
|
||||
"batchDownloadTitle": "批量下载",
|
||||
"selectAll": "全选",
|
||||
"deselectAll": "取消全选",
|
||||
"download": "下载",
|
||||
"startedTasks": "已启动 {count} 个并发任务",
|
||||
"startedTasksSSE": "已启动 {count} 个并发任务 (SSE)",
|
||||
"generatingSSE": "生成中 (SSE)",
|
||||
"selectFolder": "已选择文件夹: {name}",
|
||||
"selectFolderFailed": "选择文件夹失败",
|
||||
"noImagesSelected": "请先选择要下载的图片",
|
||||
"jszipFailed": "JSZip 库加载失败,请刷新页面重试",
|
||||
"packing": "正在打包 {count} 张图片...",
|
||||
"packingBtn": "打包中...",
|
||||
"packingProgress": "打包中... ({done}/{total})",
|
||||
"noImagesDownloaded": "没有成功获取任何图片",
|
||||
"generatingZip": "生成压缩包...",
|
||||
"packSuccess": "成功打包 {count} 张图片",
|
||||
"packFailed": "打包失败,请重试"
|
||||
},
|
||||
"video": {
|
||||
"pageTitle": "Grok2API - Video 视频生成",
|
||||
"title": "Video 视频生成",
|
||||
"subtitle": "生成短视频,支持最多 7 张参考图、@图N 引用与多种预设风格。",
|
||||
"startGenerate": "开始生成",
|
||||
"genSettings": "生成设置",
|
||||
"prompt": "提示词",
|
||||
"promptPlaceholder": "例如:@图1街头霓虹雨夜,@图2人物回头微笑,慢镜头,胶片质感",
|
||||
"promptTip": "多图参考可在提示词中使用 @图1 到 @图7,按参考图顺序对应。",
|
||||
"referenceImage": "参考图",
|
||||
"referenceImagePlaceholder": "每行一个 https://... 或 data:image/...,最多 7 张",
|
||||
"aspectRatio": "画面比例",
|
||||
"ratio3_2": "3:2 横构图",
|
||||
"ratio2_3": "2:3 竖构图",
|
||||
"ratio16_9": "16:9 宽屏",
|
||||
"ratio9_16": "9:16 竖屏",
|
||||
"ratio1_1": "1:1 方形",
|
||||
"duration": "视频时长",
|
||||
"seconds": "{n} 秒",
|
||||
"resolution": "分辨率",
|
||||
"stylePreset": "风格预设",
|
||||
"upload": "上传",
|
||||
"clearImage": "清除",
|
||||
"runStatus": "运行状态",
|
||||
"elapsedTime": "耗时 {sec}s",
|
||||
"elapsedTimeNone": "耗时 -",
|
||||
"metaRatio": "比例",
|
||||
"metaDuration": "时长",
|
||||
"metaResolution": "分辨率",
|
||||
"metaPreset": "预设",
|
||||
"videoPreview": "视频预览",
|
||||
"clearPreview": "清空",
|
||||
"waitingGenerate": "等待生成视频",
|
||||
"videoTitle": "视频 {n}",
|
||||
"open": "打开",
|
||||
"generatingPlaceholder": "生成中…",
|
||||
"superResolution": "超分辨率",
|
||||
"superResolutionInProgress": "超分辨率中",
|
||||
"alreadyGenerating": "已在生成中",
|
||||
"referenceConflict": "参考图只能选择其一:URL/Base64 列表 或 本地上传",
|
||||
"referenceLimit": "参考图最多支持 7 张",
|
||||
"noReferenceSelected": "未选择参考图",
|
||||
"downloadFailed": "下载失败,请检查视频链接是否可访问",
|
||||
"sec6": "6 秒",
|
||||
"sec10": "10 秒",
|
||||
"sec15": "15 秒"
|
||||
},
|
||||
"voice": {
|
||||
"pageTitle": "Grok2API - LiveKit 陪聊",
|
||||
"title": "LiveKit 陪聊",
|
||||
"subtitle": "LiveKit 语音会话,连接 Grok Voice。",
|
||||
"startSession": "开始会话",
|
||||
"stopSession": "停止会话",
|
||||
"connectionSettings": "连接设置",
|
||||
"voiceLabel": "声音 (Voice)",
|
||||
"personalityLabel": "个性 (Personality)",
|
||||
"speedLabel": "语速",
|
||||
"settingsHint": "提示:Voice / Personality 会在建立连接前发送到服务端。",
|
||||
"sessionLog": "会话日志",
|
||||
"clearLog": "清空",
|
||||
"copyLog": "复制",
|
||||
"sessionStatus": "会话状态",
|
||||
"audioOutput": "音频输出",
|
||||
"audioHint": "订阅到的音轨会自动插入此区域。",
|
||||
"livekitSDKError": "错误: LiveKit SDK 未能正确加载,请刷新页面重试",
|
||||
"livekitLoadFailed": "LiveKit SDK 加载失败",
|
||||
"secureContextBrowser": "请使用最新版浏览器并允许麦克风权限",
|
||||
"secureContextHTTPS": "请使用 HTTPS 或在本机 localhost 访问",
|
||||
"secureContextError": "当前环境不支持麦克风权限,{hint}",
|
||||
"connectingStatus": "正在连接",
|
||||
"fetchingToken": "正在获取 Token...",
|
||||
"fetchTokenFailed": "获取 Token 失败: {status}",
|
||||
"fetchTokenSuccess": "获取 Token 成功",
|
||||
"participantConnected": "参与者已连接: {identity}",
|
||||
"participantDisconnected": "参与者已断开: {identity}",
|
||||
"trackSubscribed": "订阅音轨: {kind}",
|
||||
"disconnected": "已断开连接",
|
||||
"connectedToServer": "已连接到 LiveKit 服务器",
|
||||
"inCall": "通话中",
|
||||
"openingMic": "正在开启麦克风...",
|
||||
"voiceEnabled": "语音已开启",
|
||||
"voiceConnected": "语音连接成功",
|
||||
"errorPrefix": "错误: {msg}",
|
||||
"logCopied": "日志已复制",
|
||||
"copyLogFailed": "复制失败,请手动选择"
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/* Cache management — simplified, updated API paths */
|
||||
let apiKey = '';
|
||||
let currentTab = 'image';
|
||||
let listPage = 1;
|
||||
const PAGE_SIZE = 100;
|
||||
let listData = { image: { items: [], total: 0 }, video: { items: [], total: 0 } };
|
||||
|
||||
const byId = id => document.getElementById(id);
|
||||
|
||||
async function init() {
|
||||
apiKey = await ensureAdminKey();
|
||||
if (!apiKey) return;
|
||||
setupConfirmDialog();
|
||||
loadStats();
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/cache`, { headers: buildAuthHeaders(apiKey) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
byId('img-count').textContent = data.local_image?.count ?? '-';
|
||||
byId('img-size').textContent = data.local_image?.size_mb != null ? data.local_image.size_mb + ' MB' : '-';
|
||||
byId('video-count').textContent = data.local_video?.count ?? '-';
|
||||
byId('video-size').textContent = data.local_video?.size_mb != null ? data.local_video.size_mb + ' MB' : '-';
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
loadList();
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/cache/list?type=${currentTab}&page=${listPage}&page_size=${PAGE_SIZE}`, { headers: buildAuthHeaders(apiKey) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
listData[currentTab] = { items: data.items || [], total: data.total || 0 };
|
||||
renderList();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
const { items, total } = listData[currentTab];
|
||||
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const tbody = byId('file-list-body');
|
||||
const empty = byId('file-empty');
|
||||
const info = byId('list-info');
|
||||
const prev = byId('list-prev');
|
||||
const next = byId('list-next');
|
||||
|
||||
if (info) info.textContent = `${total === 0 ? 0 : listPage} / ${pages} · ${total}`;
|
||||
if (prev) prev.disabled = listPage <= 1;
|
||||
if (next) next.disabled = listPage >= pages;
|
||||
|
||||
if (!items.length) {
|
||||
tbody.replaceChildren();
|
||||
empty?.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
empty?.classList.add('hidden');
|
||||
|
||||
const frag = document.createDocumentFragment();
|
||||
items.forEach(f => {
|
||||
const tr = document.createElement('tr');
|
||||
const sizeKB = f.size_bytes ? (f.size_bytes / 1024).toFixed(1) + ' KB' : '-';
|
||||
tr.innerHTML = `
|
||||
<td class="font-mono text-xs truncate" style="max-width:400px" title="${escapeHtml(f.name)}">${escapeHtml(f.name)}</td>
|
||||
<td class="text-right text-xs text-muted">${sizeKB}</td>
|
||||
<td class="text-center">
|
||||
<button onclick="deleteFile('${escapeHtml(f.name)}')" class="btn-ghost" style="padding:2px;color:var(--error)" title="删除">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
</button>
|
||||
</td>`;
|
||||
frag.appendChild(tr);
|
||||
});
|
||||
tbody.replaceChildren(frag);
|
||||
}
|
||||
|
||||
function switchTab(tab) {
|
||||
currentTab = tab; listPage = 1;
|
||||
document.querySelectorAll('.tab-item').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
|
||||
loadList();
|
||||
}
|
||||
function listPrev() { if (listPage > 1) { listPage--; loadList(); } }
|
||||
function listNext() { const pages = Math.max(1, Math.ceil((listData[currentTab]?.total||0) / PAGE_SIZE)); if (listPage < pages) { listPage++; loadList(); } }
|
||||
|
||||
async function deleteFile(name) {
|
||||
if (!await confirmAction(`删除文件 ${name}?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/cache/item/delete`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) },
|
||||
body: JSON.stringify({ type: currentTab, name })
|
||||
});
|
||||
if (res.ok) { showToast('已删除', 'success'); loadStats(); }
|
||||
else showToast('删除失败', 'error');
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
async function clearLocalCache() {
|
||||
if (!await confirmAction(`清理全部${currentTab === 'image' ? '图片' : '视频'}缓存?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/cache/clear`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) },
|
||||
body: JSON.stringify({ type: currentTab })
|
||||
});
|
||||
if (res.ok) { showToast('已清理', 'success'); loadStats(); }
|
||||
else showToast('清理失败', 'error');
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
window.onload = init;
|
||||
@@ -1,257 +0,0 @@
|
||||
let apiKey = '';
|
||||
let currentConfig = {};
|
||||
const byId = id => document.getElementById(id);
|
||||
|
||||
const NUMERIC_FIELDS = new Set([
|
||||
'timeout','max_retry','retry_backoff_base','retry_backoff_factor','retry_backoff_max',
|
||||
'retry_budget','refresh.interval_hours','refresh.super_interval_hours','runtime.fail_threshold',
|
||||
'limit_mb','refresh.on_demand_min_interval_sec','refresh.on_demand_max_tokens',
|
||||
'upload_concurrent','upload_timeout','download_concurrent','download_timeout',
|
||||
'list_concurrent','list_timeout','list_batch_size','delete_concurrent','delete_timeout',
|
||||
'delete_batch_size','reload_interval_sec','stream_timeout','final_timeout',
|
||||
'blocked_grace_seconds','final_min_bytes','medium_min_bytes','blocked_parallel_attempts',
|
||||
'concurrent','batch_size','max_file_size_mb','max_files','request_slow_ms'
|
||||
]);
|
||||
|
||||
const LOCALE_MAP = {
|
||||
app:{label:"应用设置",api_key:{title:"API 密钥",desc:"调用 Grok2API 服务的 Token。"},app_key:{title:"后台密码",desc:"登录管理后台的密码(必填)。"},function_enabled:{title:"启用功能玩法",desc:"是否启用功能玩法入口。"},function_key:{title:"Function 密码",desc:"功能玩法页面的访问密码。"},app_url:{title:"应用地址",desc:"服务外部访问 URL。"},image_format:{title:"图片格式",desc:"默认图片格式。"},video_format:{title:"视频格式",desc:"默认视频格式。"},temporary:{title:"临时对话",desc:"默认启用临时对话。"},disable_memory:{title:"禁用记忆",desc:"默认禁用 Grok 记忆。"},stream:{title:"流式响应",desc:"默认启用流式输出。"},thinking:{title:"思维链",desc:"默认启用思维链。"},dynamic_statsig:{title:"动态指纹",desc:"动态生成 Statsig 指纹。"},custom_instruction:{title:"自定义指令",desc:"透传为 customPersonality。"},filter_tags:{title:"过滤标签",desc:"自动过滤响应中的特殊标签。"}},
|
||||
proxy:{label:"代理配置",base_proxy_url:{title:"基础代理 URL",desc:"代理到 Grok 的基础地址。"},asset_proxy_url:{title:"资源代理 URL",desc:"代理到 Grok 的资源地址。"},skip_proxy_ssl_verify:{title:"跳过 SSL 校验",desc:"代理自签名证书时启用。"},enabled:{title:"Managed Clearance",desc:"通过 FlareSolverr 维护 CF clearance。"},flaresolverr_url:{title:"FlareSolverr 地址",desc:"Managed clearance provider 地址。"},refresh_interval:{title:"预热间隔(秒)",desc:"预热间隔,建议≥300。"},timeout:{title:"挑战超时(秒)",desc:"等待解决挑战的最大时间。"},cf_clearance:{title:"CF Clearance",desc:"手动配置的 clearance cookie。"},browser:{title:"浏览器指纹",desc:"curl_cffi 浏览器指纹。"},user_agent:{title:"User-Agent",desc:"HTTP User-Agent。"}},
|
||||
retry:{label:"重试策略",max_retry:{title:"最大重试",desc:"最大重试次数。"},retry_status_codes:{title:"重试状态码",desc:"触发重试的 HTTP 状态码。"},reset_session_status_codes:{title:"重建状态码",desc:"触发重建 session 的状态码。"},retry_backoff_base:{title:"退避基数",desc:"基础延迟(秒)。"},retry_backoff_factor:{title:"退避倍率",desc:"指数放大系数。"},retry_backoff_max:{title:"退避上限",desc:"单次最大延迟(秒)。"},retry_budget:{title:"退避预算",desc:"最大重试总耗时(秒)。"}},
|
||||
chat:{label:"对话配置",concurrent:{title:"并发上限",desc:"Reverse 并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"}},
|
||||
video:{label:"视频配置",enable_public_asset:{title:"公开资产链接",desc:"生成后创建 Public 资产。"},concurrent:{title:"并发上限",desc:"并发上限。"},timeout:{title:"请求超时",desc:"超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},upscale_timing:{title:"超分时机",desc:"720p 超分模式。"}},
|
||||
image:{label:"图像配置",timeout:{title:"请求超时",desc:"WebSocket 超时(秒)。"},stream_timeout:{title:"流空闲超时",desc:"流空闲超时(秒)。"},final_timeout:{title:"最终图超时",desc:"等待最终图的超时。"},blocked_grace_seconds:{title:"审查宽限",desc:"判定审查的宽限秒数。"},nsfw:{title:"NSFW 模式",desc:"启用 NSFW。"},medium_min_bytes:{title:"中等图最小字节",desc:"中等图最小字节数。"},final_min_bytes:{title:"最终图最小字节",desc:"最终图最小字节数。"},blocked_parallel_enabled:{title:"并行补偿",desc:"审查时并行补偿。"},blocked_parallel_attempts:{title:"补偿次数",desc:"补偿并发次数。"}},
|
||||
imagine_fast:{label:"Imagine Fast",n:{title:"生成数量",desc:"生成数量。"},size:{title:"图片尺寸",desc:"尺寸。"},response_format:{title:"响应格式",desc:"返回格式。"}},
|
||||
asset:{label:"资产配置",upload_concurrent:{title:"上传并发",desc:"上传最大并发。"},upload_timeout:{title:"上传超时",desc:"超时(秒)。"},download_concurrent:{title:"下载并发",desc:"下载最大并发。"},download_timeout:{title:"下载超时",desc:"超时(秒)。"},list_concurrent:{title:"查询并发",desc:"查询最大并发。"},list_timeout:{title:"查询超时",desc:"超时(秒)。"},list_batch_size:{title:"查询批次",desc:"单次批次大小。"},delete_concurrent:{title:"删除并发",desc:"删除最大并发。"},delete_timeout:{title:"删除超时",desc:"超时(秒)。"},delete_batch_size:{title:"删除批次",desc:"单次批次大小。"}},
|
||||
voice:{label:"语音配置",timeout:{title:"请求超时",desc:"超时(秒)。"}},
|
||||
account:{label:"Account 配置","runtime.consumed_mode_enabled":{title:"消耗模式",desc:"按 consumed 选号。"},"runtime.fail_threshold":{title:"失败阈值",desc:"连续失败阈值。"},"refresh.enabled":{title:"刷新调度",desc:"启用周期 refresh。"},"refresh.interval_hours":{title:"普通池间隔",desc:"普通池刷新间隔(小时)。"},"refresh.super_interval_hours":{title:"Super 池间隔",desc:"Super 池间隔(小时)。"},"refresh.on_demand_enabled":{title:"按需刷新",desc:"允许按需 refresh。"},"refresh.on_demand_min_interval_sec":{title:"按需最小间隔",desc:"最小间隔(秒)。"},"refresh.on_demand_max_tokens":{title:"按需最大数量",desc:"最多检查账号数。"}},
|
||||
log:{label:"日志配置",max_file_size_mb:{title:"单文件上限",desc:"上限(MB)。"},max_files:{title:"保留数",desc:"最多保留日志文件数。"},log_health_requests:{title:"记录健康检查",desc:"记录 /health。"},log_all_requests:{title:"记录全部请求",desc:"全部请求日志。"},request_slow_ms:{title:"慢请求阈值",desc:"阈值(毫秒)。"}},
|
||||
cache:{label:"缓存管理",enable_auto_clean:{title:"自动清理",desc:"自动清理缓存。"},limit_mb:{title:"清理阈值",desc:"阈值(MB)。"}},
|
||||
nsfw:{label:"NSFW 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}},
|
||||
usage:{label:"Usage 配置",concurrent:{title:"并发上限",desc:"并发上限。"},batch_size:{title:"批次大小",desc:"批次大小。"},timeout:{title:"请求超时",desc:"超时(秒)。"}}
|
||||
};
|
||||
|
||||
const SECTION_ORDER = new Map(Object.keys(LOCALE_MAP).map((k,i) => [k,i]));
|
||||
const MANAGED_LOCKED = ['cf_clearance','browser','user_agent'];
|
||||
const MANAGED_PROVIDER = ['flaresolverr_url','refresh_interval','timeout'];
|
||||
|
||||
function getText(s, k) {
|
||||
let ti = t('config.fields.'+s+'.'+k+'.title');
|
||||
let de = t('config.fields.'+s+'.'+k+'.desc');
|
||||
if (!ti.startsWith('config.fields.')) return {title:ti, desc: de.startsWith('config.fields.') ? '' : de};
|
||||
const m = LOCALE_MAP[s]; return m?.[k] || {title: k.replace(/_/g,' '), desc:''};
|
||||
}
|
||||
function getSectionLabel(s) {
|
||||
let l = t('config.sections.'+s);
|
||||
return l.startsWith('config.sections.') ? (LOCALE_MAP[s]?.label || s) : l;
|
||||
}
|
||||
function sortByOrder(keys, order) {
|
||||
if (!order) return keys;
|
||||
return keys.sort((a,b) => {
|
||||
const ia = order.get(a), ib = order.get(b);
|
||||
if (ia !== undefined && ib !== undefined) return ia - ib;
|
||||
if (ia !== undefined) return -1;
|
||||
if (ib !== undefined) return 1;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function setMeta(input, section, key) { input.dataset.section = section; input.dataset.key = key; }
|
||||
|
||||
function buildBool(s, k, val) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'toggle';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'checkbox'; input.checked = val; input.className = 'sr-only';
|
||||
setMeta(input, s, k);
|
||||
const track = document.createElement('div');
|
||||
track.className = 'toggle-track';
|
||||
label.append(input, track);
|
||||
return {input, node: label};
|
||||
}
|
||||
|
||||
function buildSelect(s, k, val, opts) {
|
||||
const input = document.createElement('select');
|
||||
input.className = 'input'; setMeta(input, s, k);
|
||||
opts.forEach(o => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = o.val; opt.text = o.text;
|
||||
if (val === o.val) opt.selected = true;
|
||||
input.appendChild(opt);
|
||||
});
|
||||
return {input, node: input};
|
||||
}
|
||||
|
||||
function buildJson(s, k, val) {
|
||||
const input = document.createElement('textarea');
|
||||
input.className = 'input font-mono'; input.rows = 4;
|
||||
input.value = JSON.stringify(val, null, 2);
|
||||
setMeta(input, s, k); input.dataset.type = 'json';
|
||||
return {input, node: input};
|
||||
}
|
||||
|
||||
function buildText(s, k, val) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text'; input.className = 'input'; input.value = val;
|
||||
setMeta(input, s, k);
|
||||
return {input, node: input};
|
||||
}
|
||||
|
||||
function buildTextarea(s, k, val, rows=5) {
|
||||
const input = document.createElement('textarea');
|
||||
input.className = 'input'; input.rows = rows; input.value = val||'';
|
||||
setMeta(input, s, k);
|
||||
return {input, node: input};
|
||||
}
|
||||
|
||||
function randomKey(len) {
|
||||
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
const buf = new Uint8Array(len);
|
||||
crypto.getRandomValues(buf);
|
||||
return Array.from(buf, b => chars[b % chars.length]).join('');
|
||||
}
|
||||
|
||||
function buildSecret(s, k, val) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text'; input.className = 'input'; input.value = val; input.style.flex = '1';
|
||||
setMeta(input, s, k);
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'flex gap-2';
|
||||
const genBtn = document.createElement('button');
|
||||
genBtn.className = 'btn btn-primary btn-icon'; genBtn.type = 'button'; genBtn.title = '生成';
|
||||
genBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7"/><polyline points="21 3 21 9 15 9"/></svg>';
|
||||
genBtn.onclick = () => { input.value = randomKey(16); };
|
||||
const copyBtn = document.createElement('button');
|
||||
copyBtn.className = 'btn btn-primary btn-icon'; copyBtn.type = 'button';
|
||||
copyBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
|
||||
copyBtn.onclick = () => copyToClipboard(input.value, copyBtn);
|
||||
wrap.append(input, genBtn, copyBtn);
|
||||
return {input, node: wrap};
|
||||
}
|
||||
|
||||
function buildFieldCard(section, key, val) {
|
||||
const text = getText(section, key);
|
||||
const card = document.createElement('div');
|
||||
card.className = 'config-field';
|
||||
const title = document.createElement('div');
|
||||
title.className = 'config-field-title'; title.textContent = text.title;
|
||||
card.appendChild(title);
|
||||
if (text.desc) {
|
||||
const desc = document.createElement('p');
|
||||
desc.className = 'config-field-desc'; desc.textContent = text.desc;
|
||||
card.appendChild(desc);
|
||||
}
|
||||
const inputWrap = document.createElement('div');
|
||||
inputWrap.className = 'config-field-input';
|
||||
|
||||
let built;
|
||||
if (section === 'app' && key === 'custom_instruction') built = buildTextarea(section, key, val, 6);
|
||||
else if (typeof val === 'boolean') built = buildBool(section, key, val);
|
||||
else if (key === 'image_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'base64',text:'Base64'}]);
|
||||
else if (key === 'video_format') built = buildSelect(section, key, val, [{val:'html',text:'HTML'},{val:'url',text:'URL'}]);
|
||||
else if (section==='video' && key==='upscale_timing') built = buildSelect(section, key, val, [{val:'single',text:'single'},{val:'complete',text:'complete'}]);
|
||||
else if (section==='imagine_fast' && key==='size') built = buildSelect(section, key, val, [{val:'1024x1024',text:'1024x1024'},{val:'1280x720',text:'1280x720'},{val:'720x1280',text:'720x1280'},{val:'1792x1024',text:'1792x1024'},{val:'1024x1792',text:'1024x1792'}]);
|
||||
else if (section==='imagine_fast' && key==='response_format') built = buildSelect(section, key, val, [{val:'url',text:'URL'},{val:'b64_json',text:'B64 JSON'},{val:'base64',text:'Base64'}]);
|
||||
else if (Array.isArray(val) || typeof val === 'object') built = buildJson(section, key, val);
|
||||
else if (['api_key','app_key','function_key'].includes(key)) built = buildSecret(section, key, val);
|
||||
else built = buildText(section, key, val);
|
||||
|
||||
if (built) inputWrap.appendChild(built.node);
|
||||
card.appendChild(inputWrap);
|
||||
|
||||
if (section==='proxy' && key==='enabled' && built) {
|
||||
built.input.addEventListener('change', () => applyManagedState(built.input.checked));
|
||||
}
|
||||
if (section==='app' && key==='function_enabled') {
|
||||
card.classList.add('has-action');
|
||||
const link = document.createElement('a');
|
||||
link.href = '/login'; link.className = 'btn btn-primary btn-icon'; link.title = '访问';
|
||||
link.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7"/><path d="M7 7h10v10"/></svg>';
|
||||
link.style.display = val ? 'inline-flex' : 'none';
|
||||
card.appendChild(link);
|
||||
if (built) built.input.addEventListener('change', () => { link.style.display = built.input.checked ? 'inline-flex' : 'none'; });
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
function applyManagedState(enabled) {
|
||||
function setDisabled(k, disabled) {
|
||||
const el = document.querySelector(`[data-section="proxy"][data-key="${k}"]`);
|
||||
if (!el) return;
|
||||
el.disabled = disabled;
|
||||
const field = el.closest('.config-field');
|
||||
if (field) { field.style.opacity = disabled ? '.45' : ''; field.style.pointerEvents = disabled ? 'none' : ''; }
|
||||
}
|
||||
MANAGED_LOCKED.forEach(k => setDisabled(k, !!enabled));
|
||||
MANAGED_PROVIDER.forEach(k => setDisabled(k, !enabled));
|
||||
}
|
||||
|
||||
function renderConfig(data) {
|
||||
const container = byId('config-container');
|
||||
if (!container) return;
|
||||
container.replaceChildren();
|
||||
const frag = document.createDocumentFragment();
|
||||
sortByOrder(Object.keys(data), SECTION_ORDER).forEach(section => {
|
||||
const items = data[section];
|
||||
const localeSection = LOCALE_MAP[section];
|
||||
const keyOrder = localeSection ? new Map(Object.keys(localeSection).map((k,i) => [k,i])) : null;
|
||||
const keys = sortByOrder(Object.keys(items), keyOrder).filter(k => !(section==='proxy' && k==='cf_cookies'));
|
||||
if (!keys.length) return;
|
||||
const card = document.createElement('div');
|
||||
card.className = 'config-section';
|
||||
card.innerHTML = `<div class="config-section-title">${getSectionLabel(section)}</div>`;
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'config-grid';
|
||||
keys.forEach(k => grid.appendChild(buildFieldCard(section, k, items[k])));
|
||||
card.appendChild(grid);
|
||||
frag.appendChild(card);
|
||||
});
|
||||
container.appendChild(frag);
|
||||
applyManagedState(data.proxy?.enabled);
|
||||
}
|
||||
|
||||
async function init() {
|
||||
apiKey = await ensureAdminKey();
|
||||
if (!apiKey) return;
|
||||
loadData();
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/config`, { headers: buildAuthHeaders(apiKey) });
|
||||
if (res.ok) { currentConfig = await res.json(); renderConfig(currentConfig); }
|
||||
else if (res.status === 401) logout();
|
||||
} catch { showToast(t('common.connectionFailed'), 'error'); }
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
const btn = byId('save-btn');
|
||||
const orig = btn.innerText;
|
||||
btn.disabled = true; btn.innerText = t('config.saving') || '保存中...';
|
||||
try {
|
||||
const cfg = structuredClone ? structuredClone(currentConfig) : JSON.parse(JSON.stringify(currentConfig));
|
||||
document.querySelectorAll('[data-section][data-key]').forEach(input => {
|
||||
const s = input.dataset.section, k = input.dataset.key;
|
||||
let val = input.value;
|
||||
if (input.type === 'checkbox') val = input.checked;
|
||||
else if (input.dataset.type === 'json') { try { val = JSON.parse(val); } catch { throw new Error(`Invalid JSON: ${getText(s,k).title}`); } }
|
||||
else if (k === 'app_key' && !val.trim()) throw new Error('app_key 不能为空');
|
||||
else if (NUMERIC_FIELDS.has(k) && val.trim() !== '' && !isNaN(Number(val))) val = Number(val);
|
||||
if (!cfg[s]) cfg[s] = {};
|
||||
cfg[s][k] = val;
|
||||
});
|
||||
if (cfg.proxy?.enabled && !String(cfg.proxy.flaresolverr_url||'').trim()) {
|
||||
showToast('启用 Managed Clearance 时需配置 FlareSolverr 地址', 'error');
|
||||
btn.disabled = false; btn.innerText = orig; return;
|
||||
}
|
||||
const res = await fetch(`${API_BASE}/config`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) },
|
||||
body: JSON.stringify(cfg)
|
||||
});
|
||||
if (res.ok) { showToast(t('config.configSaved') || '配置已保存', 'success'); }
|
||||
else { showToast(t('common.saveFailed') || '保存失败', 'error'); }
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
finally { btn.disabled = false; btn.innerText = orig; }
|
||||
}
|
||||
|
||||
window.onload = init;
|
||||
@@ -1,21 +0,0 @@
|
||||
const input = document.getElementById('api-key-input');
|
||||
if (input) input.addEventListener('keypress', e => { if (e.key === 'Enter') login(); });
|
||||
|
||||
async function login() {
|
||||
const key = (input ? input.value : '').trim();
|
||||
if (!key) return;
|
||||
try {
|
||||
if (await verifyKey(`${API_BASE}/verify`, key)) {
|
||||
await storeAppKey(key);
|
||||
window.location.href = '/admin/token';
|
||||
} else {
|
||||
showToast(t('common.invalidKey'), 'error');
|
||||
}
|
||||
} catch { showToast(t('common.connectionFailed'), 'error'); }
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const key = await getStoredAppKey();
|
||||
if (!key) return;
|
||||
try { if (await verifyKey(`${API_BASE}/verify`, key)) window.location.href = '/admin/token'; } catch {}
|
||||
})();
|
||||
@@ -1,380 +0,0 @@
|
||||
/* Token management — full rewrite with updated API paths */
|
||||
let apiKey = '';
|
||||
let consumedModeEnabled = false;
|
||||
let allTokens = {};
|
||||
let flatTokens = [];
|
||||
let isBatchProcessing = false;
|
||||
let currentBatchAction = null;
|
||||
let currentBatchTaskId = null;
|
||||
let batchEventSource = null;
|
||||
let batchTotal = 0;
|
||||
let batchProcessed = 0;
|
||||
let currentFilter = 'all';
|
||||
let currentPage = 1;
|
||||
let pageSize = 50;
|
||||
|
||||
const byId = id => document.getElementById(id);
|
||||
const DEFAULT_QUOTA = { ssoBasic: 80, ssoSuper: 140 };
|
||||
|
||||
function setText(id, text) { const el = byId(id); if (el) el.innerText = text; }
|
||||
|
||||
function getSelectedTokens() { return flatTokens.filter(t => t._selected); }
|
||||
function countSelected(tokens) { return tokens.filter(t => t._selected).length; }
|
||||
function setSelectedForTokens(tokens, sel) { tokens.forEach(t => t._selected = sel); }
|
||||
|
||||
function syncVisibleSelectionUI(sel) {
|
||||
document.querySelectorAll('#token-table-body input[type="checkbox"]').forEach(i => i.checked = sel);
|
||||
document.querySelectorAll('#token-table-body tr').forEach(r => r.classList.toggle('row-selected', sel));
|
||||
}
|
||||
|
||||
function getFilteredTokens() {
|
||||
if (currentFilter === 'all') return flatTokens;
|
||||
return flatTokens.filter(t => {
|
||||
if (currentFilter === 'active') return t.status === 'active';
|
||||
if (currentFilter === 'cooling') return t.status === 'cooling';
|
||||
if (currentFilter === 'expired') return t.status !== 'active' && t.status !== 'cooling';
|
||||
if (currentFilter === 'nsfw') return t.tags?.includes('nsfw');
|
||||
if (currentFilter === 'no-nsfw') return !t.tags?.includes('nsfw');
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function getPaginationData() {
|
||||
const filtered = getFilteredTokens();
|
||||
const total = filtered.length;
|
||||
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (currentPage > pages) currentPage = pages;
|
||||
const start = (currentPage - 1) * pageSize;
|
||||
return { filtered, total, pages, visible: filtered.slice(start, start + pageSize) };
|
||||
}
|
||||
|
||||
function getVisibleTokens() { return getPaginationData().visible; }
|
||||
|
||||
async function init() {
|
||||
apiKey = await ensureAdminKey();
|
||||
if (!apiKey) return;
|
||||
setupConfirmDialog();
|
||||
setupSelectAllMenu();
|
||||
makeDraggable(byId('batch-actions'));
|
||||
const poolSel = byId('edit-pool');
|
||||
const quotaIn = byId('edit-quota');
|
||||
if (poolSel && quotaIn) poolSel.addEventListener('change', () => { if (currentEditIndex < 0) quotaIn.value = DEFAULT_QUOTA[poolSel.value] || 80; });
|
||||
loadData();
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/tokens`, { headers: buildAuthHeaders(apiKey) });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
allTokens = data.tokens;
|
||||
consumedModeEnabled = data.consumed_mode_enabled || false;
|
||||
processTokens(data.tokens);
|
||||
updateStats();
|
||||
renderTable();
|
||||
} else if (res.status === 401) logout();
|
||||
else throw new Error(`HTTP ${res.status}`);
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
function processTokens(data) {
|
||||
flatTokens = [];
|
||||
Object.entries(data).forEach(([pool, tokens]) => {
|
||||
if (!Array.isArray(tokens)) return;
|
||||
tokens.forEach(t => {
|
||||
const o = typeof t === 'string' ? { token: t, status: 'active', quota: 0, tags: [] } : { ...t };
|
||||
flatTokens.push({ ...o, pool, _selected: false });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function updateStats() {
|
||||
let total = flatTokens.length, active = 0, cooling = 0, invalid = 0, nsfw = 0, noNsfw = 0, quota = 0, calls = 0;
|
||||
flatTokens.forEach(t => {
|
||||
if (t.status === 'active') { active++; quota += (t.quota || 0); }
|
||||
else if (t.status === 'cooling') cooling++;
|
||||
else invalid++;
|
||||
t.tags?.includes('nsfw') ? nsfw++ : noNsfw++;
|
||||
calls += (t.use_count || 0);
|
||||
});
|
||||
setText('stat-total', total.toLocaleString());
|
||||
setText('stat-active', active.toLocaleString());
|
||||
setText('stat-cooling', cooling.toLocaleString());
|
||||
setText('stat-invalid', invalid.toLocaleString());
|
||||
setText('stat-chat-quota', (consumedModeEnabled ? flatTokens.reduce((s,t) => s+(t.consumed||0), 0) : quota).toLocaleString());
|
||||
setText('stat-image-quota', Math.floor((consumedModeEnabled ? flatTokens.reduce((s,t) => s+(t.consumed||0), 0) : quota) / 2).toLocaleString());
|
||||
setText('stat-total-calls', calls.toLocaleString());
|
||||
const counts = { all: total, active, cooling, expired: invalid, nsfw, 'no-nsfw': noNsfw };
|
||||
Object.entries(counts).forEach(([k, v]) => { const el = byId(`tab-count-${k}`); if (el) el.textContent = v; });
|
||||
}
|
||||
|
||||
function renderTable() {
|
||||
const tbody = byId('token-table-body');
|
||||
const loading = byId('loading');
|
||||
const empty = byId('empty-state');
|
||||
if (loading) loading.classList.add('hidden');
|
||||
const { total, pages, visible } = getPaginationData();
|
||||
updatePagination(total, pages);
|
||||
if (!visible.length) {
|
||||
tbody.replaceChildren();
|
||||
if (empty) { empty.textContent = currentFilter === 'all' ? t('token.emptyState') : t('token.emptyFilterState'); empty.classList.remove('hidden'); }
|
||||
updateSelectionState(); return;
|
||||
}
|
||||
if (empty) empty.classList.add('hidden');
|
||||
const idxMap = new Map(flatTokens.map((t, i) => [t, i]));
|
||||
const frag = document.createDocumentFragment();
|
||||
visible.forEach(item => {
|
||||
const idx = idxMap.get(item);
|
||||
const tr = document.createElement('tr');
|
||||
tr.dataset.index = idx;
|
||||
if (item._selected) tr.classList.add('row-selected');
|
||||
const short = item.token.length > 24 ? item.token.slice(0,8) + '...' + item.token.slice(-16) : item.token;
|
||||
const statusClass = item.status === 'active' ? 'badge-green' : item.status === 'cooling' ? 'badge-orange' : item.status === 'expired' ? 'badge-red' : '';
|
||||
const nsfwBadge = item.tags?.includes('nsfw') ? ' <span class="badge badge-purple">nsfw</span>' : '';
|
||||
tr.innerHTML = `
|
||||
<td class="text-center"><input type="checkbox" class="checkbox" ${item._selected?'checked':''} onchange="toggleSelect(${idx})"></td>
|
||||
<td><div class="flex items-center gap-2"><span class="font-mono text-xs text-muted" title="${escapeHtml(item.token)}">${escapeHtml(short)}</span><button class="btn-ghost" style="padding:2px" onclick="copyToClipboard('${escapeHtml(item.token)}',this)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button></div></td>
|
||||
<td class="text-center"><span class="badge">${escapeHtml(item.pool)}</span></td>
|
||||
<td class="text-center"><span class="badge ${statusClass}">${item.status}</span>${nsfwBadge}</td>
|
||||
<td class="text-center font-mono text-xs">${consumedModeEnabled ? (item.consumed||0) : (item.quota||0)}</td>
|
||||
<td class="text-xs text-muted truncate" style="max-width:150px">${escapeHtml(item.note||'-')}</td>
|
||||
<td class="text-center"><div class="flex items-center justify-center gap-2">
|
||||
<button onclick="refreshStatus('${escapeHtml(item.token)}')" class="btn-ghost" style="padding:2px" title="${t('token.refreshStatus')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button>
|
||||
<button onclick="openEditModal(${idx})" class="btn-ghost" style="padding:2px" title="${t('common.edit')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>
|
||||
<button onclick="deleteToken(${idx})" class="btn-ghost" style="padding:2px;color:var(--error)" title="${t('common.delete')}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
|
||||
</div></td>`;
|
||||
frag.appendChild(tr);
|
||||
});
|
||||
tbody.replaceChildren(frag);
|
||||
updateSelectionState();
|
||||
}
|
||||
|
||||
/* Selection */
|
||||
function toggleSelectAll() { const cb = byId('select-all'); setSelectedForTokens(getVisibleTokens(), cb?.checked); syncVisibleSelectionUI(cb?.checked); updateSelectionState(); }
|
||||
function toggleSelect(idx) { flatTokens[idx]._selected = !flatTokens[idx]._selected; const r = document.querySelector(`#token-table-body tr[data-index="${idx}"]`); if (r) r.classList.toggle('row-selected', flatTokens[idx]._selected); updateSelectionState(); }
|
||||
|
||||
function setupSelectAllMenu() {
|
||||
document.addEventListener('click', e => { if (!byId('select-all-wrap')?.contains(e.target)) byId('select-all-popover')?.classList.add('hidden'); });
|
||||
document.addEventListener('keydown', e => { if (e.key === 'Escape') byId('select-all-popover')?.classList.add('hidden'); });
|
||||
}
|
||||
|
||||
function handleSelectAllPrimary(e) {
|
||||
e?.stopPropagation();
|
||||
if (countSelected(flatTokens) > 0) { clearAllSelection(); return; }
|
||||
const p = byId('select-all-popover');
|
||||
p?.classList.toggle('hidden');
|
||||
}
|
||||
function selectVisibleAllFromMenu() { setSelectedForTokens(getVisibleTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
|
||||
function selectAllFilteredFromMenu() { setSelectedForTokens(getFilteredTokens(), true); syncVisibleSelectionUI(true); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
|
||||
function clearAllSelection() { setSelectedForTokens(flatTokens, false); syncVisibleSelectionUI(false); updateSelectionState(); byId('select-all-popover')?.classList.add('hidden'); }
|
||||
|
||||
function updateSelectionState() {
|
||||
const sel = countSelected(flatTokens);
|
||||
const vis = getVisibleTokens();
|
||||
const visSel = countSelected(vis);
|
||||
const cb = byId('select-all');
|
||||
if (cb) { cb.checked = vis.length > 0 && visSel === vis.length; cb.indeterminate = visSel > 0 && visSel < vis.length; }
|
||||
const label = byId('select-all-label');
|
||||
if (label) label.textContent = sel > 0 ? t('token.clearSelection') : t('common.selectAll');
|
||||
const trigger = byId('select-all-trigger');
|
||||
if (trigger) trigger.classList.toggle('is-active', sel > 0);
|
||||
const caret = byId('select-all-caret');
|
||||
if (caret) caret.style.display = sel > 0 ? 'none' : 'inline';
|
||||
const countEl = byId('selected-count');
|
||||
if (countEl) countEl.textContent = sel;
|
||||
if (sel > 0) byId('select-all-popover')?.classList.add('hidden');
|
||||
setActionButtons(sel);
|
||||
}
|
||||
|
||||
function setActionButtons(count = null) {
|
||||
const c = count ?? countSelected(flatTokens);
|
||||
const dis = isBatchProcessing;
|
||||
['btn-batch-export','btn-batch-update','btn-batch-disable','btn-batch-enable','btn-batch-nsfw','btn-batch-delete'].forEach(id => {
|
||||
const b = byId(id); if (b) b.disabled = dis || c === 0;
|
||||
});
|
||||
}
|
||||
|
||||
/* Filtering & Pagination */
|
||||
function filterByStatus(status) {
|
||||
currentFilter = status; currentPage = 1;
|
||||
document.querySelectorAll('.tab-item').forEach(t => { t.classList.toggle('active', t.dataset.filter === status); });
|
||||
renderTable();
|
||||
}
|
||||
|
||||
function updatePagination(total, pages) {
|
||||
const info = byId('pagination-info');
|
||||
if (info) info.textContent = `${total === 0 ? 0 : currentPage} / ${pages} · ${total}`;
|
||||
const prev = byId('page-prev'); if (prev) prev.disabled = currentPage <= 1;
|
||||
const next = byId('page-next'); if (next) next.disabled = currentPage >= pages;
|
||||
}
|
||||
function goPrevPage() { if (currentPage > 1) { currentPage--; renderTable(); } }
|
||||
function goNextPage() { const p = getPaginationData().pages; if (currentPage < p) { currentPage++; renderTable(); } }
|
||||
function changePageSize() { const v = parseInt(byId('page-size')?.value); if (v) { pageSize = v; currentPage = 1; renderTable(); } }
|
||||
|
||||
/* CRUD */
|
||||
let currentEditIndex = -1;
|
||||
function addToken() { openEditModal(-1); }
|
||||
|
||||
function openEditModal(idx) {
|
||||
currentEditIndex = idx;
|
||||
const isNew = idx < 0;
|
||||
if (isNew) {
|
||||
byId('edit-token-display').value = ''; byId('edit-token-display').disabled = false;
|
||||
byId('edit-pool').value = 'ssoBasic'; byId('edit-quota').value = 80; byId('edit-note').value = '';
|
||||
document.querySelector('#edit-modal .modal-title').textContent = t('token.addTitle');
|
||||
} else {
|
||||
const item = flatTokens[idx];
|
||||
byId('edit-token-display').value = item.token; byId('edit-token-display').disabled = true;
|
||||
byId('edit-pool').value = item.pool;
|
||||
byId('edit-quota').value = consumedModeEnabled ? (item.consumed||0) : item.quota;
|
||||
byId('edit-note').value = item.note || '';
|
||||
document.querySelector('#edit-modal .modal-title').textContent = t('token.editTitle');
|
||||
}
|
||||
openModal('edit-modal');
|
||||
}
|
||||
function closeEditModal() { closeModal('edit-modal'); }
|
||||
|
||||
async function saveEdit() {
|
||||
const pool = byId('edit-pool').value.trim() || 'ssoBasic';
|
||||
const quota = parseInt(byId('edit-quota').value) || 0;
|
||||
const note = byId('edit-note').value.trim().slice(0, 50);
|
||||
if (currentEditIndex >= 0) {
|
||||
const item = flatTokens[currentEditIndex];
|
||||
item.pool = pool; if (!consumedModeEnabled) item.quota = quota; item.note = note;
|
||||
} else {
|
||||
const token = byId('edit-token-display').value.trim();
|
||||
if (!token) return showToast(t('token.tokenEmpty'), 'error');
|
||||
if (flatTokens.some(t => t.token === token)) return showToast(t('token.tokenExists'), 'error');
|
||||
flatTokens.push({ token, pool, quota, consumed: 0, note, status: 'active', use_count: 0, tags: [], _selected: false });
|
||||
}
|
||||
await syncToServer(); closeEditModal(); loadData();
|
||||
}
|
||||
|
||||
async function deleteToken(idx) {
|
||||
if (!await confirmAction(t('token.confirmDelete'), { okText: t('common.delete') })) return;
|
||||
flatTokens.splice(idx, 1);
|
||||
syncToServer().then(loadData);
|
||||
}
|
||||
|
||||
async function syncToServer() {
|
||||
const data = {};
|
||||
flatTokens.forEach(t => {
|
||||
if (!data[t.pool]) data[t.pool] = [];
|
||||
const p = { token: t.token, status: t.status, quota: t.quota, consumed: t.consumed||0, note: t.note||'', fail_count: t.fail_count||0, use_count: t.use_count||0, tags: t.tags||[] };
|
||||
if (t.created_at) p.created_at = t.created_at;
|
||||
if (t.last_used_at) p.last_used_at = t.last_used_at;
|
||||
if (t.last_fail_at) p.last_fail_at = t.last_fail_at;
|
||||
if (t.last_sync_at) p.last_sync_at = t.last_sync_at;
|
||||
if (t.last_asset_clear_at) p.last_asset_clear_at = t.last_asset_clear_at;
|
||||
if (t.last_fail_reason) p.last_fail_reason = t.last_fail_reason;
|
||||
data[t.pool].push(p);
|
||||
});
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/tokens`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify(data) });
|
||||
if (!res.ok) showToast(t('common.saveFailed'), 'error');
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* Import/Export */
|
||||
function openImportModal() { openModal('import-modal'); }
|
||||
function closeImportModal() { closeModal('import-modal', () => { const i = byId('import-text'); if (i) i.value = ''; }); }
|
||||
async function submitImport() {
|
||||
const pool = byId('import-pool').value.trim() || 'ssoBasic';
|
||||
const lines = byId('import-text').value.split('\n');
|
||||
lines.forEach(l => { const t = l.trim(); if (t && !flatTokens.some(ft => ft.token === t)) flatTokens.push({ token: t, pool, status: 'active', quota: DEFAULT_QUOTA[pool]||80, consumed: 0, note: '', tags: [], fail_count: 0, use_count: 0, _selected: false }); });
|
||||
await syncToServer(); closeImportModal(); loadData();
|
||||
}
|
||||
function batchExport() {
|
||||
const sel = getSelectedTokens();
|
||||
if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
|
||||
downloadTextFile(sel.map(t => t.token).join('\n')+'\n', `tokens_${new Date().toISOString().slice(0,10)}.txt`);
|
||||
}
|
||||
|
||||
/* Batch ops */
|
||||
async function refreshStatus(token) {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/tokens/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: [token] }) });
|
||||
if (res.ok) { showToast(t('token.refreshSuccess'), 'success'); loadData(); }
|
||||
else showToast(t('token.refreshFailed'), 'error');
|
||||
} catch { showToast(t('token.requestError'), 'error'); }
|
||||
}
|
||||
|
||||
async function batchUpdate() { await startBatchAsync('refresh', `${API_BASE}/tokens/refresh/async`); }
|
||||
async function batchEnableNSFW() {
|
||||
const sel = getSelectedTokens();
|
||||
if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
|
||||
if (!await confirmAction(t('token.nsfwConfirm', { count: sel.length }), { okText: t('token.nsfwEnable') })) return;
|
||||
await startBatchAsync('nsfw', `${API_BASE}/tokens/nsfw/enable/async`);
|
||||
}
|
||||
|
||||
async function startBatchAsync(action, url) {
|
||||
if (isBatchProcessing) return showToast(t('common.taskInProgress'), 'info');
|
||||
const sel = getSelectedTokens();
|
||||
if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
|
||||
isBatchProcessing = true; currentBatchAction = action;
|
||||
batchTotal = sel.length; batchProcessed = 0;
|
||||
updateBatchProgress(); setActionButtons();
|
||||
try {
|
||||
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...buildAuthHeaders(apiKey) }, body: JSON.stringify({ tokens: sel.map(t => t.token) }) });
|
||||
const data = await res.json();
|
||||
if (!res.ok || data.status !== 'success') throw new Error(data.detail || 'Failed');
|
||||
currentBatchTaskId = data.task_id;
|
||||
BatchSSE.close(batchEventSource);
|
||||
batchEventSource = BatchSSE.open(currentBatchTaskId, apiKey, {
|
||||
onMessage: msg => {
|
||||
if (msg.type === 'progress' || msg.type === 'snapshot') {
|
||||
if (msg.total) batchTotal = msg.total;
|
||||
if (msg.processed != null) batchProcessed = msg.processed;
|
||||
updateBatchProgress();
|
||||
} else if (msg.type === 'done') {
|
||||
batchProcessed = batchTotal; updateBatchProgress();
|
||||
finishBatch(false); showToast(action === 'nsfw' ? t('token.nsfwDone') : t('token.refreshDone'), 'success');
|
||||
closeBatchSSE();
|
||||
} else if (msg.type === 'cancelled') {
|
||||
finishBatch(true); showToast(t('common.cancelled'), 'info'); closeBatchSSE();
|
||||
} else if (msg.type === 'error') {
|
||||
finishBatch(true); showToast(msg.error || t('common.unknownError'), 'error'); closeBatchSSE();
|
||||
}
|
||||
},
|
||||
onError: () => { finishBatch(true); showToast(t('common.connectionInterrupted'), 'error'); closeBatchSSE(); }
|
||||
});
|
||||
} catch (e) { finishBatch(true); showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
function closeBatchSSE() { currentBatchTaskId = null; BatchSSE.close(batchEventSource); batchEventSource = null; }
|
||||
function stopBatchRefresh() { if (currentBatchTaskId) { BatchSSE.cancel(currentBatchTaskId, apiKey); closeBatchSSE(); } finishBatch(true); }
|
||||
function finishBatch(aborted) { isBatchProcessing = false; currentBatchAction = null; updateBatchProgress(); setActionButtons(); updateSelectionState(); loadData(); }
|
||||
|
||||
function updateBatchProgress() {
|
||||
const c = byId('batch-progress'), txt = byId('batch-progress-text'), stop = byId('btn-stop-action');
|
||||
if (!c) return;
|
||||
if (!isBatchProcessing) { c.classList.add('hidden'); stop?.classList.add('hidden'); return; }
|
||||
c.classList.remove('hidden'); stop?.classList.remove('hidden');
|
||||
if (txt) txt.textContent = batchTotal ? `${Math.floor(batchProcessed/batchTotal*100)}%` : '...';
|
||||
}
|
||||
|
||||
async function batchDelete() {
|
||||
if (isBatchProcessing) return;
|
||||
const sel = getSelectedTokens();
|
||||
if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
|
||||
if (!await confirmAction(t('token.confirmBatchDelete', { count: sel.length }), { okText: t('common.delete') })) return;
|
||||
const remove = new Set(sel.map(t => t.token));
|
||||
flatTokens = flatTokens.filter(t => !remove.has(t.token));
|
||||
await syncToServer(); showToast(t('token.deleteDone'), 'success'); loadData();
|
||||
}
|
||||
|
||||
async function batchSetStatus(target) {
|
||||
if (isBatchProcessing) return;
|
||||
const sel = getSelectedTokens();
|
||||
if (!sel.length) return showToast(t('common.noTokenSelected'), 'error');
|
||||
const targets = sel.filter(t => t.status !== target);
|
||||
if (!targets.length) return;
|
||||
const toDisabled = target === 'disabled';
|
||||
if (!await confirmAction(t(toDisabled ? 'token.confirmBatchDisable' : 'token.confirmBatchEnable', { count: targets.length }))) return;
|
||||
targets.forEach(t => t.status = target);
|
||||
await syncToServer(); loadData(); showToast(toDisabled ? t('token.batchDisableDone') : t('token.batchEnableDone'), 'success');
|
||||
}
|
||||
function batchDisableTokens() { batchSetStatus('disabled'); }
|
||||
function batchEnableTokens() { batchSetStatus('active'); }
|
||||
|
||||
window.onload = init;
|
||||
@@ -1,129 +0,0 @@
|
||||
/* Core auth module — key storage, verification, session management */
|
||||
const API_BASE = '/admin/api'; // admin API prefix
|
||||
const FN_BASE = '/function'; // function API prefix
|
||||
const APP_KEY_STORAGE = 'grok2api_app_key';
|
||||
const FUNCTION_KEY_STORAGE = 'grok2api_function_key';
|
||||
const APP_KEY_XOR_PREFIX = 'enc:xor:';
|
||||
const APP_KEY_ENC_PREFIX = 'enc:v1:';
|
||||
const APP_KEY_SECRET = 'grok2api-admin-key';
|
||||
|
||||
let cachedAdminKey = null;
|
||||
let cachedFunctionKey = null;
|
||||
|
||||
const _enc = new TextEncoder();
|
||||
const _dec = new TextDecoder();
|
||||
|
||||
function _toB64(bytes) { let s = ''; bytes.forEach(b => s += String.fromCharCode(b)); return btoa(s); }
|
||||
function _fromB64(b64) { const s = atob(b64); const a = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) a[i] = s.charCodeAt(i); return a; }
|
||||
function _xor(data, key) { const o = new Uint8Array(data.length); for (let i = 0; i < data.length; i++) o[i] = data[i] ^ key[i % key.length]; return o; }
|
||||
|
||||
function xorEncrypt(plain) {
|
||||
return APP_KEY_XOR_PREFIX + _toB64(_xor(_enc.encode(plain), _enc.encode(APP_KEY_SECRET)));
|
||||
}
|
||||
function xorDecrypt(stored) {
|
||||
if (!stored.startsWith(APP_KEY_XOR_PREFIX)) return stored;
|
||||
return _dec.decode(_xor(_fromB64(stored.slice(APP_KEY_XOR_PREFIX.length)), _enc.encode(APP_KEY_SECRET)));
|
||||
}
|
||||
|
||||
async function _deriveKey(salt) {
|
||||
const km = await crypto.subtle.importKey('raw', _enc.encode(APP_KEY_SECRET), 'PBKDF2', false, ['deriveKey']);
|
||||
return crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' }, km, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
|
||||
async function encryptAppKey(plain) {
|
||||
if (!plain) return '';
|
||||
if (!crypto?.subtle) return xorEncrypt(plain);
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const key = await _deriveKey(salt);
|
||||
const cipher = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, _enc.encode(plain));
|
||||
return `${APP_KEY_ENC_PREFIX}${_toB64(salt)}:${_toB64(iv)}:${_toB64(new Uint8Array(cipher))}`;
|
||||
}
|
||||
|
||||
async function decryptAppKey(stored) {
|
||||
if (!stored) return '';
|
||||
if (stored.startsWith(APP_KEY_XOR_PREFIX)) return xorDecrypt(stored);
|
||||
if (!stored.startsWith(APP_KEY_ENC_PREFIX)) return stored;
|
||||
if (!crypto?.subtle) return '';
|
||||
const parts = stored.split(':');
|
||||
if (parts.length !== 5) return '';
|
||||
const [, , saltB64, ivB64, cipherB64] = parts;
|
||||
const key = await _deriveKey(_fromB64(saltB64));
|
||||
return _dec.decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: _fromB64(ivB64) }, key, _fromB64(cipherB64)));
|
||||
}
|
||||
|
||||
async function getStoredAppKey() {
|
||||
const s = localStorage.getItem(APP_KEY_STORAGE) || '';
|
||||
if (!s) return '';
|
||||
try { return await decryptAppKey(s); } catch { clearStoredAppKey(); return ''; }
|
||||
}
|
||||
|
||||
async function getStoredFunctionKey() {
|
||||
const s = localStorage.getItem(FUNCTION_KEY_STORAGE) || '';
|
||||
if (!s) return '';
|
||||
try { return await decryptAppKey(s); } catch { clearStoredFunctionKey(); return ''; }
|
||||
}
|
||||
|
||||
async function storeAppKey(key) {
|
||||
if (!key) { clearStoredAppKey(); return; }
|
||||
localStorage.setItem(APP_KEY_STORAGE, await encryptAppKey(key) || '');
|
||||
}
|
||||
|
||||
async function storeFunctionKey(key) {
|
||||
if (!key) { clearStoredFunctionKey(); return; }
|
||||
localStorage.setItem(FUNCTION_KEY_STORAGE, await encryptAppKey(key) || '');
|
||||
}
|
||||
|
||||
function clearStoredAppKey() { localStorage.removeItem(APP_KEY_STORAGE); cachedAdminKey = null; }
|
||||
function clearStoredFunctionKey() { localStorage.removeItem(FUNCTION_KEY_STORAGE); cachedFunctionKey = null; }
|
||||
|
||||
async function verifyKey(url, key) {
|
||||
const h = key ? { Authorization: `Bearer ${key}` } : {};
|
||||
return (await fetch(url, { headers: h })).ok;
|
||||
}
|
||||
|
||||
async function ensureAdminKey() {
|
||||
if (cachedAdminKey) return cachedAdminKey;
|
||||
const key = await getStoredAppKey();
|
||||
if (!key) { window.location.href = '/admin/login'; return null; }
|
||||
try {
|
||||
if (!await verifyKey(`${API_BASE}/verify`, key)) throw 0;
|
||||
cachedAdminKey = `Bearer ${key}`;
|
||||
return cachedAdminKey;
|
||||
} catch { clearStoredAppKey(); window.location.href = '/admin/login'; return null; }
|
||||
}
|
||||
|
||||
async function ensureFunctionKey() {
|
||||
if (cachedFunctionKey !== null) return cachedFunctionKey;
|
||||
const key = await getStoredFunctionKey();
|
||||
if (!key) {
|
||||
try { if (await verifyKey(`${FN_BASE}/voice/token`, '')) { cachedFunctionKey = ''; return ''; } } catch {}
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (!await verifyKey(`${FN_BASE}/voice/token`, key)) throw 0;
|
||||
cachedFunctionKey = `Bearer ${key}`;
|
||||
return cachedFunctionKey;
|
||||
} catch { clearStoredFunctionKey(); return null; }
|
||||
}
|
||||
|
||||
function buildAuthHeaders(apiKey) { return apiKey ? { Authorization: apiKey } : {}; }
|
||||
function logout() { clearStoredAppKey(); clearStoredFunctionKey(); window.location.href = '/admin/login'; }
|
||||
function functionLogout() { clearStoredFunctionKey(); window.location.href = '/login'; }
|
||||
|
||||
async function fetchStorageType() {
|
||||
const apiKey = await ensureAdminKey();
|
||||
if (!apiKey) return null;
|
||||
try {
|
||||
const r = await fetch(`${API_BASE}/storage`, { headers: buildAuthHeaders(apiKey) });
|
||||
if (!r.ok) return null;
|
||||
const d = await r.json();
|
||||
return d?.type || null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function formatStorageLabel(type) {
|
||||
if (!type) return '-';
|
||||
const map = { local: 'local', mysql: 'mysql', pgsql: 'pgsql', postgres: 'pgsql', postgresql: 'pgsql', redis: 'redis' };
|
||||
return map[type.toLowerCase()] || '-';
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/* Unified header injection — handles both admin and function pages */
|
||||
(function() {
|
||||
const GITHUB_ICON = '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.58 2 12.26c0 4.5 2.87 8.32 6.84 9.67.5.1.68-.22.68-.48 0-.24-.01-.86-.01-1.69-2.78.62-3.37-1.37-3.37-1.37-.45-1.17-1.11-1.48-1.11-1.48-.91-.64.07-.63.07-.63 1.01.07 1.54 1.06 1.54 1.06.9 1.58 2.36 1.12 2.94.86.09-.67.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.04 1.03-2.76-.1-.26-.45-1.3.1-2.71 0 0 .84-.27 2.75 1.05A9.3 9.3 0 0 1 12 6.79c.85 0 1.7.12 2.5.36 1.9-1.32 2.74-1.05 2.74-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.64 1.03 2.76 0 3.94-2.34 4.81-4.58 5.06.36.32.68.95.68 1.92 0 1.38-.01 2.49-.01 2.83 0 .26.18.58.69.48A10.05 10.05 0 0 0 22 12.26C22 6.58 17.52 2 12 2Z"/></svg>';
|
||||
|
||||
var ADMIN_NAV = `
|
||||
<a href="/admin/token" class="nav-link" data-nav="/admin/token" data-i18n="nav.tokenManage">Token管理</a>
|
||||
<a href="/admin/config" class="nav-link" data-nav="/admin/config" data-i18n="nav.configManage">配置管理</a>
|
||||
<a href="/admin/cache" class="nav-link" data-nav="/admin/cache" data-i18n="nav.cacheManage">缓存管理</a>`;
|
||||
|
||||
var ADMIN_RIGHT = `
|
||||
<button id="lang-toggle" type="button" class="header-btn">EN</button>
|
||||
<button id="storage-mode-btn" type="button" class="header-btn">-</button>
|
||||
<a href="https://github.com/chenyme/grok2api/issues" target="_blank" class="header-btn" data-i18n="nav.feedback">反馈</a>
|
||||
<button onclick="logout()" type="button" class="header-btn" data-i18n="nav.logout">退出</button>`;
|
||||
|
||||
var FUNCTION_NAV = `
|
||||
<a href="/chat" class="nav-link" data-nav="/chat">Chat</a>
|
||||
<a href="/imagine" class="nav-link" data-nav="/imagine">Imagine</a>
|
||||
<a href="/voice" class="nav-link" data-nav="/voice">Voice</a>
|
||||
<a href="/video" class="nav-link" data-nav="/video">Video</a>`;
|
||||
|
||||
var FUNCTION_RIGHT = `
|
||||
<button id="lang-toggle" class="header-btn">EN</button>
|
||||
<button onclick="functionLogout()" class="header-btn" data-i18n="nav.logout">退出</button>`;
|
||||
|
||||
var FOOTER_HTML = '<footer class="app-footer"><a href="https://github.com/chenyme/grok2api" target="_blank">Grok2API</a> Created By <a href="https://github.com/chenyme" target="_blank">@Chenyme</a></footer>';
|
||||
|
||||
var container = document.getElementById('app-header');
|
||||
if (container && !container.children.length) {
|
||||
var type = container.dataset.type || 'admin';
|
||||
var isAdmin = type === 'admin';
|
||||
container.innerHTML = '<header class="app-header"><div class="app-header-inner">' +
|
||||
'<div class="header-left">' +
|
||||
'<a href="' + (isAdmin ? 'https://github.com/chenyme/grok2api' : '/') + '" ' + (isAdmin ? 'target="_blank" ' : '') + 'class="brand">' + GITHUB_ICON + '<span>Grok2API</span></a>' +
|
||||
'<div class="header-sep"></div>' +
|
||||
(isAdmin ? ADMIN_NAV : FUNCTION_NAV) +
|
||||
'</div>' +
|
||||
'<div class="header-right">' +
|
||||
(isAdmin ? ADMIN_RIGHT : FUNCTION_RIGHT) +
|
||||
'</div>' +
|
||||
'</div></header>';
|
||||
}
|
||||
|
||||
// Inject footer if placeholder exists
|
||||
var footer = document.getElementById('app-footer');
|
||||
if (footer && !footer.children.length) {
|
||||
footer.innerHTML = FOOTER_HTML;
|
||||
}
|
||||
|
||||
// Highlight active nav link
|
||||
var path = location.pathname;
|
||||
document.querySelectorAll('a[data-nav]').forEach(function(a) {
|
||||
if (path === a.dataset.nav || (a.dataset.nav !== '/' && path.startsWith(a.dataset.nav))) {
|
||||
a.classList.add('active');
|
||||
}
|
||||
});
|
||||
|
||||
// Storage mode badge (admin only)
|
||||
var btn = document.getElementById('storage-mode-btn');
|
||||
if (btn && typeof fetchStorageType === 'function') {
|
||||
(async function() {
|
||||
btn.textContent = '...';
|
||||
var type = await fetchStorageType();
|
||||
var label = formatStorageLabel(type);
|
||||
btn.textContent = label === '-' ? '-' : label.toUpperCase();
|
||||
if (label !== '-') btn.classList.add('ready');
|
||||
})();
|
||||
}
|
||||
|
||||
// Lang toggle
|
||||
var langBtn = document.getElementById('lang-toggle');
|
||||
if (langBtn) {
|
||||
langBtn.textContent = (window.I18n && I18n.getLang() === 'zh') ? 'EN' : '中';
|
||||
langBtn.addEventListener('click', function() { if (window.I18n) I18n.toggleLang(); });
|
||||
}
|
||||
})();
|
||||
@@ -1,27 +0,0 @@
|
||||
/* Batch SSE helper */
|
||||
(function(g) {
|
||||
function normalize(key) {
|
||||
if (!key) return '';
|
||||
const s = String(key).trim();
|
||||
return s.startsWith('Bearer ') ? s.slice(7).trim() : s;
|
||||
}
|
||||
function open(taskId, apiKey, handlers = {}) {
|
||||
if (!taskId) return null;
|
||||
const raw = normalize(apiKey);
|
||||
const url = `${API_BASE}/batch/${taskId}/stream?app_key=${encodeURIComponent(raw)}`;
|
||||
const es = new EventSource(url);
|
||||
es.onmessage = e => {
|
||||
if (!e.data) return;
|
||||
try { const msg = JSON.parse(e.data); if (handlers.onMessage) handlers.onMessage(msg); } catch {}
|
||||
};
|
||||
es.onerror = () => { if (handlers.onError) handlers.onError(); };
|
||||
return es;
|
||||
}
|
||||
function close(es) { if (es) es.close(); }
|
||||
async function cancel(taskId, apiKey) {
|
||||
if (!taskId) return;
|
||||
const raw = normalize(apiKey);
|
||||
try { await fetch(`${API_BASE}/batch/${taskId}/cancel`, { method: 'POST', headers: raw ? { Authorization: `Bearer ${raw}` } : undefined }); } catch {}
|
||||
}
|
||||
g.BatchSSE = { open, close, cancel };
|
||||
})(window);
|
||||
@@ -1,23 +0,0 @@
|
||||
/* Toast notification system */
|
||||
function showToast(message, type = 'success') {
|
||||
let c = document.getElementById('toast-container');
|
||||
if (!c) {
|
||||
c = document.createElement('div');
|
||||
c.id = 'toast-container';
|
||||
c.className = 'toast-container';
|
||||
document.body.appendChild(c);
|
||||
}
|
||||
const el = document.createElement('div');
|
||||
const ok = type === 'success';
|
||||
const icon = ok
|
||||
? '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>'
|
||||
: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
|
||||
el.className = `toast ${ok ? 'toast-success' : 'toast-error'}`;
|
||||
const safe = String(message).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
el.innerHTML = `<div class="toast-icon">${icon}</div><div class="toast-content">${safe}</div>`;
|
||||
c.appendChild(el);
|
||||
setTimeout(() => {
|
||||
el.classList.add('out');
|
||||
el.addEventListener('animationend', () => el.remove());
|
||||
}, 3000);
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
/* Shared UI helpers: modal, draggable, confirm dialog */
|
||||
|
||||
function openModal(id) {
|
||||
const m = document.getElementById(id);
|
||||
if (!m) return null;
|
||||
m.classList.remove('hidden');
|
||||
requestAnimationFrame(() => m.classList.add('is-open'));
|
||||
return m;
|
||||
}
|
||||
|
||||
function closeModal(id, cb) {
|
||||
const m = document.getElementById(id);
|
||||
if (!m) return;
|
||||
m.classList.remove('is-open');
|
||||
setTimeout(() => { m.classList.add('hidden'); if (cb) cb(); }, 200);
|
||||
}
|
||||
|
||||
/* Confirm dialog — requires #confirm-dialog, #confirm-message, #confirm-ok, #confirm-cancel in DOM */
|
||||
let _confirmResolve = null;
|
||||
|
||||
function setupConfirmDialog() {
|
||||
const d = document.getElementById('confirm-dialog');
|
||||
if (!d) return;
|
||||
const ok = document.getElementById('confirm-ok');
|
||||
const cancel = document.getElementById('confirm-cancel');
|
||||
d.addEventListener('click', e => { if (e.target === d) _closeConfirm(false); });
|
||||
if (ok) ok.addEventListener('click', () => _closeConfirm(true));
|
||||
if (cancel) cancel.addEventListener('click', () => _closeConfirm(false));
|
||||
}
|
||||
|
||||
function confirmAction(message, opts = {}) {
|
||||
const d = document.getElementById('confirm-dialog');
|
||||
if (!d) return Promise.resolve(false);
|
||||
const msg = document.getElementById('confirm-message');
|
||||
const ok = document.getElementById('confirm-ok');
|
||||
const cancel = document.getElementById('confirm-cancel');
|
||||
if (msg) msg.textContent = message;
|
||||
if (ok) ok.textContent = opts.okText || t('common.ok');
|
||||
if (cancel) cancel.textContent = opts.cancelText || t('common.cancel');
|
||||
return new Promise(resolve => {
|
||||
_confirmResolve = resolve;
|
||||
d.classList.remove('hidden');
|
||||
requestAnimationFrame(() => d.classList.add('is-open'));
|
||||
});
|
||||
}
|
||||
|
||||
function _closeConfirm(ok) {
|
||||
const d = document.getElementById('confirm-dialog');
|
||||
if (!d) return;
|
||||
d.classList.remove('is-open');
|
||||
setTimeout(() => { d.classList.add('hidden'); if (_confirmResolve) { _confirmResolve(ok); _confirmResolve = null; } }, 200);
|
||||
}
|
||||
|
||||
/* Draggable element */
|
||||
function makeDraggable(el) {
|
||||
if (!el) return;
|
||||
let dragging = false, sx, sy, il, it;
|
||||
el.style.touchAction = 'none';
|
||||
el.addEventListener('pointerdown', e => {
|
||||
if (e.target.closest('button, a, input, select')) return;
|
||||
e.preventDefault();
|
||||
dragging = true;
|
||||
el.setPointerCapture(e.pointerId);
|
||||
sx = e.clientX; sy = e.clientY;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!el.style.left) {
|
||||
el.style.left = r.left + 'px';
|
||||
el.style.top = r.top + 'px';
|
||||
el.style.transform = 'none';
|
||||
el.style.bottom = 'auto';
|
||||
}
|
||||
il = parseFloat(el.style.left);
|
||||
it = parseFloat(el.style.top);
|
||||
});
|
||||
document.addEventListener('pointermove', e => {
|
||||
if (!dragging) return;
|
||||
el.style.left = (il + e.clientX - sx) + 'px';
|
||||
el.style.top = (it + e.clientY - sy) + 'px';
|
||||
});
|
||||
document.addEventListener('pointerup', e => {
|
||||
if (dragging) { dragging = false; el.releasePointerCapture(e.pointerId); }
|
||||
});
|
||||
}
|
||||
|
||||
/* Escape HTML */
|
||||
function escapeHtml(s) {
|
||||
if (!s) return '';
|
||||
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||
}
|
||||
|
||||
/* Copy to clipboard with button feedback */
|
||||
async function copyToClipboard(text, btn) {
|
||||
if (!text) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
if (!btn) return;
|
||||
const orig = btn.innerHTML;
|
||||
btn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>';
|
||||
btn.style.color = 'var(--success)';
|
||||
setTimeout(() => { btn.innerHTML = orig; btn.style.color = ''; }, 1500);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/* Download text file */
|
||||
function downloadTextFile(content, filename) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type: 'text/plain' }));
|
||||
const a = document.createElement('a');
|
||||
a.href = url; a.download = filename;
|
||||
document.body.appendChild(a); a.click(); a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,25 +0,0 @@
|
||||
const input = document.getElementById('function-key-input');
|
||||
if (input) input.addEventListener('keypress', e => { if (e.key === 'Enter') login(); });
|
||||
|
||||
async function requestFunctionLogin(key) {
|
||||
const h = key ? { Authorization: `Bearer ${key}` } : {};
|
||||
return (await fetch(`${FN_BASE}/voice/token?voice=ara`, { headers: h })).ok;
|
||||
}
|
||||
|
||||
async function login() {
|
||||
const key = (input ? input.value : '').trim();
|
||||
try {
|
||||
const ok = await requestFunctionLogin(key);
|
||||
if (ok) { await storeFunctionKey(key); window.location.href = '/chat'; }
|
||||
else showToast(t('common.invalidKey'), 'error');
|
||||
} catch { showToast(t('common.connectionFailed'), 'error'); }
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const stored = await getStoredFunctionKey();
|
||||
if (stored && await requestFunctionLogin(stored)) { window.location.href = '/chat'; return; }
|
||||
if (stored) clearStoredFunctionKey();
|
||||
if (await requestFunctionLogin('')) window.location.href = '/chat';
|
||||
} catch {}
|
||||
})();
|
||||
@@ -1,707 +0,0 @@
|
||||
(() => {
|
||||
const startBtn = document.getElementById('startBtn');
|
||||
const stopBtn = document.getElementById('stopBtn');
|
||||
const clearBtn = document.getElementById('clearBtn');
|
||||
const promptInput = document.getElementById('promptInput');
|
||||
const imageUrlInput = document.getElementById('imageUrlInput');
|
||||
const imageFileInput = document.getElementById('imageFileInput');
|
||||
const imageFileName = document.getElementById('imageFileName');
|
||||
const clearImageFileBtn = document.getElementById('clearImageFileBtn');
|
||||
const selectImageFileBtn = document.getElementById('selectImageFileBtn');
|
||||
const ratioSelect = document.getElementById('ratioSelect');
|
||||
const lengthSelect = document.getElementById('lengthSelect');
|
||||
const resolutionSelect = document.getElementById('resolutionSelect');
|
||||
const presetSelect = document.getElementById('presetSelect');
|
||||
const statusText = document.getElementById('statusText');
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const progressFill = document.getElementById('progressFill');
|
||||
const progressText = document.getElementById('progressText');
|
||||
const durationValue = document.getElementById('durationValue');
|
||||
const aspectValue = document.getElementById('aspectValue');
|
||||
const lengthValue = document.getElementById('lengthValue');
|
||||
const resolutionValue = document.getElementById('resolutionValue');
|
||||
const presetValue = document.getElementById('presetValue');
|
||||
const videoEmpty = document.getElementById('videoEmpty');
|
||||
const videoStage = document.getElementById('videoStage');
|
||||
|
||||
let currentSource = null;
|
||||
let currentTaskId = '';
|
||||
let isRunning = false;
|
||||
let progressBuffer = '';
|
||||
let contentBuffer = '';
|
||||
let collectingContent = false;
|
||||
let startAt = 0;
|
||||
let fileDataUrls = [];
|
||||
let elapsedTimer = null;
|
||||
let lastProgress = 0;
|
||||
let currentPreviewItem = null;
|
||||
let previewCount = 0;
|
||||
const DEFAULT_REASONING_EFFORT = 'low';
|
||||
const MAX_REFERENCE_IMAGES = 7;
|
||||
|
||||
function toast(message, type) {
|
||||
if (typeof showToast === 'function') {
|
||||
showToast(message, type);
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(state, text) {
|
||||
if (!statusText) return;
|
||||
statusText.textContent = text;
|
||||
statusText.classList.remove('connected', 'connecting', 'error');
|
||||
if (state) {
|
||||
statusText.classList.add(state);
|
||||
}
|
||||
}
|
||||
|
||||
function setButtons(running) {
|
||||
if (!startBtn || !stopBtn) return;
|
||||
if (running) {
|
||||
startBtn.classList.add('hidden');
|
||||
stopBtn.classList.remove('hidden');
|
||||
} else {
|
||||
startBtn.classList.remove('hidden');
|
||||
stopBtn.classList.add('hidden');
|
||||
startBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function updateProgress(value) {
|
||||
const safe = Math.max(0, Math.min(100, Number(value) || 0));
|
||||
lastProgress = safe;
|
||||
if (progressFill) {
|
||||
progressFill.style.width = `${safe}%`;
|
||||
}
|
||||
if (progressText) {
|
||||
progressText.textContent = `${safe}%`;
|
||||
}
|
||||
}
|
||||
|
||||
function updateMeta() {
|
||||
if (aspectValue && ratioSelect) {
|
||||
aspectValue.textContent = ratioSelect.value;
|
||||
}
|
||||
if (lengthValue && lengthSelect) {
|
||||
lengthValue.textContent = `${lengthSelect.value}s`;
|
||||
}
|
||||
if (resolutionValue && resolutionSelect) {
|
||||
resolutionValue.textContent = resolutionSelect.value;
|
||||
}
|
||||
if (presetValue && presetSelect) {
|
||||
presetValue.textContent = presetSelect.value;
|
||||
}
|
||||
}
|
||||
|
||||
function resetOutput(keepPreview) {
|
||||
progressBuffer = '';
|
||||
contentBuffer = '';
|
||||
collectingContent = false;
|
||||
lastProgress = 0;
|
||||
currentPreviewItem = null;
|
||||
updateProgress(0);
|
||||
setIndeterminate(false);
|
||||
if (!keepPreview) {
|
||||
if (videoStage) {
|
||||
videoStage.innerHTML = '';
|
||||
videoStage.classList.add('hidden');
|
||||
}
|
||||
if (videoEmpty) {
|
||||
videoEmpty.classList.remove('hidden');
|
||||
}
|
||||
previewCount = 0;
|
||||
}
|
||||
if (durationValue) {
|
||||
durationValue.textContent = t('video.elapsedTimeNone');
|
||||
}
|
||||
}
|
||||
|
||||
function initPreviewSlot() {
|
||||
if (!videoStage) return;
|
||||
previewCount += 1;
|
||||
currentPreviewItem = document.createElement('div');
|
||||
currentPreviewItem.className = 'video-item';
|
||||
currentPreviewItem.dataset.index = String(previewCount);
|
||||
currentPreviewItem.classList.add('is-pending');
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.className = 'video-item-bar';
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'video-item-title';
|
||||
title.textContent = t('video.videoTitle', { n: previewCount });
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'video-item-actions';
|
||||
|
||||
const openBtn = document.createElement('a');
|
||||
openBtn.className = 'geist-button-outline text-xs px-3 video-open hidden';
|
||||
openBtn.target = '_blank';
|
||||
openBtn.rel = 'noopener';
|
||||
openBtn.textContent = t('video.open');
|
||||
|
||||
const downloadBtn = document.createElement('button');
|
||||
downloadBtn.className = 'geist-button-outline text-xs px-3 video-download';
|
||||
downloadBtn.type = 'button';
|
||||
downloadBtn.textContent = t('imagine.download');
|
||||
downloadBtn.disabled = true;
|
||||
|
||||
actions.appendChild(openBtn);
|
||||
actions.appendChild(downloadBtn);
|
||||
header.appendChild(title);
|
||||
header.appendChild(actions);
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'video-item-body';
|
||||
body.innerHTML = '<div class="video-item-placeholder">' + t('video.generatingPlaceholder') + '</div>';
|
||||
|
||||
const link = document.createElement('div');
|
||||
link.className = 'video-item-link';
|
||||
|
||||
currentPreviewItem.appendChild(header);
|
||||
currentPreviewItem.appendChild(body);
|
||||
currentPreviewItem.appendChild(link);
|
||||
videoStage.appendChild(currentPreviewItem);
|
||||
videoStage.classList.remove('hidden');
|
||||
if (videoEmpty) {
|
||||
videoEmpty.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePreviewSlot() {
|
||||
if (!currentPreviewItem) {
|
||||
initPreviewSlot();
|
||||
}
|
||||
return currentPreviewItem;
|
||||
}
|
||||
|
||||
function updateItemLinks(item, url) {
|
||||
if (!item) return;
|
||||
const openBtn = item.querySelector('.video-open');
|
||||
const downloadBtn = item.querySelector('.video-download');
|
||||
const link = item.querySelector('.video-item-link');
|
||||
const safeUrl = url || '';
|
||||
item.dataset.url = safeUrl;
|
||||
if (link) {
|
||||
link.textContent = safeUrl;
|
||||
link.classList.toggle('has-url', Boolean(safeUrl));
|
||||
}
|
||||
if (openBtn) {
|
||||
if (safeUrl) {
|
||||
openBtn.href = safeUrl;
|
||||
openBtn.classList.remove('hidden');
|
||||
} else {
|
||||
openBtn.classList.add('hidden');
|
||||
openBtn.removeAttribute('href');
|
||||
}
|
||||
}
|
||||
if (downloadBtn) {
|
||||
downloadBtn.dataset.url = safeUrl;
|
||||
downloadBtn.disabled = !safeUrl;
|
||||
}
|
||||
if (safeUrl) {
|
||||
item.classList.remove('is-pending');
|
||||
}
|
||||
}
|
||||
|
||||
function setIndeterminate(active) {
|
||||
if (!progressBar) return;
|
||||
if (active) {
|
||||
progressBar.classList.add('indeterminate');
|
||||
} else {
|
||||
progressBar.classList.remove('indeterminate');
|
||||
}
|
||||
}
|
||||
|
||||
function startElapsedTimer() {
|
||||
stopElapsedTimer();
|
||||
if (!durationValue) return;
|
||||
elapsedTimer = setInterval(() => {
|
||||
if (!startAt) return;
|
||||
const seconds = Math.max(0, Math.round((Date.now() - startAt) / 1000));
|
||||
durationValue.textContent = t('video.elapsedTime', { sec: seconds });
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function stopElapsedTimer() {
|
||||
if (elapsedTimer) {
|
||||
clearInterval(elapsedTimer);
|
||||
elapsedTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function clearFileSelection() {
|
||||
fileDataUrls = [];
|
||||
if (imageFileInput) {
|
||||
imageFileInput.value = '';
|
||||
}
|
||||
if (imageFileName) {
|
||||
imageFileName.textContent = t('video.noReferenceSelected');
|
||||
}
|
||||
}
|
||||
|
||||
function updateReferenceSummary(names) {
|
||||
if (!imageFileName) return;
|
||||
if (!names || !names.length) {
|
||||
imageFileName.textContent = t('video.noReferenceSelected');
|
||||
return;
|
||||
}
|
||||
imageFileName.textContent = names.join('\n');
|
||||
}
|
||||
|
||||
function parseReferenceUrls(value) {
|
||||
return (value || '')
|
||||
.split(/\r?\n/)
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function getReferenceImages() {
|
||||
const rawUrls = imageUrlInput ? parseReferenceUrls(imageUrlInput.value) : [];
|
||||
if (fileDataUrls.length && rawUrls.length) {
|
||||
toast(t('video.referenceConflict'), 'error');
|
||||
throw new Error('invalid_reference');
|
||||
}
|
||||
const images = fileDataUrls.length ? [...fileDataUrls] : rawUrls;
|
||||
if (images.length > MAX_REFERENCE_IMAGES) {
|
||||
toast(t('video.referenceLimit'), 'error');
|
||||
throw new Error('too_many_references');
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
function normalizeAuthHeader(authHeader) {
|
||||
if (!authHeader) return '';
|
||||
if (authHeader.startsWith('Bearer ')) {
|
||||
return authHeader.slice(7).trim();
|
||||
}
|
||||
return authHeader;
|
||||
}
|
||||
|
||||
function buildSseUrl(taskId, rawPublicKey) {
|
||||
const httpProtocol = window.location.protocol === 'https:' ? 'https' : 'http';
|
||||
const base = `${httpProtocol}://${window.location.host}/function/video/sse`;
|
||||
const params = new URLSearchParams();
|
||||
params.set('task_id', taskId);
|
||||
params.set('t', String(Date.now()));
|
||||
if (rawPublicKey) {
|
||||
params.set('function_key', rawPublicKey);
|
||||
}
|
||||
return `${base}?${params.toString()}`;
|
||||
}
|
||||
|
||||
async function createVideoTask(authHeader) {
|
||||
const prompt = promptInput ? promptInput.value.trim() : '';
|
||||
const imageUrls = getReferenceImages();
|
||||
const res = await fetch(`${FN_BASE}/video/start`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...buildAuthHeaders(authHeader),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
image_urls: imageUrls,
|
||||
reasoning_effort: DEFAULT_REASONING_EFFORT,
|
||||
aspect_ratio: ratioSelect ? ratioSelect.value : '3:2',
|
||||
video_length: lengthSelect ? parseInt(lengthSelect.value, 10) : 6,
|
||||
resolution_name: resolutionSelect ? resolutionSelect.value : '480p',
|
||||
preset: presetSelect ? presetSelect.value : 'normal'
|
||||
})
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || 'Failed to create task');
|
||||
}
|
||||
const data = await res.json();
|
||||
return data && data.task_id ? String(data.task_id) : '';
|
||||
}
|
||||
|
||||
async function stopVideoTask(taskId, authHeader) {
|
||||
if (!taskId) return;
|
||||
try {
|
||||
await fetch(`${FN_BASE}/video/stop`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...buildAuthHeaders(authHeader),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ task_ids: [taskId] })
|
||||
});
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function extractVideoInfo(buffer) {
|
||||
if (!buffer) return null;
|
||||
if (buffer.includes('<video')) {
|
||||
const matches = buffer.match(/<video[\s\S]*?<\/video>/gi);
|
||||
if (matches && matches.length) {
|
||||
return { html: matches[matches.length - 1] };
|
||||
}
|
||||
}
|
||||
const mdMatches = buffer.match(/\[video\]\(([^)]+)\)/g);
|
||||
if (mdMatches && mdMatches.length) {
|
||||
const last = mdMatches[mdMatches.length - 1];
|
||||
const urlMatch = last.match(/\[video\]\(([^)]+)\)/);
|
||||
if (urlMatch) {
|
||||
return { url: urlMatch[1] };
|
||||
}
|
||||
}
|
||||
const urlMatches = buffer.match(/https?:\/\/[^\s<)]+/g);
|
||||
if (urlMatches && urlMatches.length) {
|
||||
return { url: urlMatches[urlMatches.length - 1] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderVideoFromHtml(html) {
|
||||
const container = ensurePreviewSlot();
|
||||
if (!container) return;
|
||||
const body = container.querySelector('.video-item-body');
|
||||
if (!body) return;
|
||||
body.innerHTML = html;
|
||||
const videoEl = body.querySelector('video');
|
||||
let videoUrl = '';
|
||||
if (videoEl) {
|
||||
videoEl.controls = true;
|
||||
videoEl.preload = 'metadata';
|
||||
const source = videoEl.querySelector('source');
|
||||
if (source && source.getAttribute('src')) {
|
||||
videoUrl = source.getAttribute('src');
|
||||
} else if (videoEl.getAttribute('src')) {
|
||||
videoUrl = videoEl.getAttribute('src');
|
||||
}
|
||||
}
|
||||
updateItemLinks(container, videoUrl);
|
||||
}
|
||||
|
||||
function renderVideoFromUrl(url) {
|
||||
const container = ensurePreviewSlot();
|
||||
if (!container) return;
|
||||
const safeUrl = url || '';
|
||||
const body = container.querySelector('.video-item-body');
|
||||
if (!body) return;
|
||||
body.innerHTML = `\n <video controls preload="metadata">\n <source src="${safeUrl}" type="video/mp4">\n </video>\n `;
|
||||
updateItemLinks(container, safeUrl);
|
||||
}
|
||||
|
||||
function handleDelta(text) {
|
||||
if (!text) return;
|
||||
if (text.includes('<think>') || text.includes('</think>')) {
|
||||
return;
|
||||
}
|
||||
if (text.includes('超分辨率') || text.includes('super resolution')) {
|
||||
setStatus('connecting', t('video.superResolutionInProgress'));
|
||||
setIndeterminate(true);
|
||||
if (progressText) {
|
||||
progressText.textContent = t('video.superResolutionInProgress');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!collectingContent) {
|
||||
const maybeVideo = text.includes('<video') || text.includes('[video](') || text.includes('http://') || text.includes('https://');
|
||||
if (maybeVideo) {
|
||||
collectingContent = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (collectingContent) {
|
||||
contentBuffer += text;
|
||||
const info = extractVideoInfo(contentBuffer);
|
||||
if (info) {
|
||||
if (info.html) {
|
||||
renderVideoFromHtml(info.html);
|
||||
} else if (info.url) {
|
||||
renderVideoFromUrl(info.url);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
progressBuffer += text;
|
||||
const roundMatches = [...progressBuffer.matchAll(/\[round=(\d+)\/(\d+)\]\s*progress=([0-9]+(?:\.[0-9]+)?)%/g)];
|
||||
if (roundMatches.length) {
|
||||
const last = roundMatches[roundMatches.length - 1];
|
||||
const round = parseInt(last[1], 10);
|
||||
const total = parseInt(last[2], 10);
|
||||
const value = parseFloat(last[3]);
|
||||
setIndeterminate(false);
|
||||
updateProgress(value);
|
||||
if (progressText && Number.isFinite(round) && Number.isFinite(total) && total > 0) {
|
||||
progressText.textContent = `${Math.round(value)}% · ${round}/${total}`;
|
||||
}
|
||||
progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 300));
|
||||
return;
|
||||
}
|
||||
|
||||
const genericProgressMatches = [...progressBuffer.matchAll(/progress=([0-9]+(?:\.[0-9]+)?)%/g)];
|
||||
if (genericProgressMatches.length) {
|
||||
const last = genericProgressMatches[genericProgressMatches.length - 1];
|
||||
const value = parseFloat(last[1]);
|
||||
setIndeterminate(false);
|
||||
updateProgress(value);
|
||||
progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 240));
|
||||
return;
|
||||
}
|
||||
|
||||
const matches = [...progressBuffer.matchAll(/进度\s*(\d+)%/g)];
|
||||
if (matches.length) {
|
||||
const last = matches[matches.length - 1];
|
||||
const value = parseInt(last[1], 10);
|
||||
setIndeterminate(false);
|
||||
updateProgress(value);
|
||||
progressBuffer = progressBuffer.slice(Math.max(0, progressBuffer.length - 200));
|
||||
}
|
||||
}
|
||||
|
||||
function closeSource() {
|
||||
if (currentSource) {
|
||||
try {
|
||||
currentSource.close();
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
currentSource = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function startConnection() {
|
||||
const prompt = promptInput ? promptInput.value.trim() : '';
|
||||
if (!prompt) {
|
||||
toast(t('common.enterPrompt'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
toast(t('video.alreadyGenerating'), 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const authHeader = await ensureFunctionKey();
|
||||
if (authHeader === null) {
|
||||
toast(t('common.configurePublicKey'), 'error');
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
|
||||
isRunning = true;
|
||||
startBtn.disabled = true;
|
||||
updateMeta();
|
||||
resetOutput(true);
|
||||
initPreviewSlot();
|
||||
setStatus('connecting', t('common.connecting'));
|
||||
|
||||
let taskId = '';
|
||||
try {
|
||||
taskId = await createVideoTask(authHeader);
|
||||
} catch (e) {
|
||||
setStatus('error', t('common.createTaskFailed'));
|
||||
startBtn.disabled = false;
|
||||
isRunning = false;
|
||||
return;
|
||||
}
|
||||
|
||||
currentTaskId = taskId;
|
||||
startAt = Date.now();
|
||||
setStatus('connected', t('common.generating'));
|
||||
setButtons(true);
|
||||
setIndeterminate(true);
|
||||
startElapsedTimer();
|
||||
|
||||
const rawPublicKey = normalizeAuthHeader(authHeader);
|
||||
const url = buildSseUrl(taskId, rawPublicKey);
|
||||
closeSource();
|
||||
const es = new EventSource(url);
|
||||
currentSource = es;
|
||||
|
||||
es.onopen = () => {
|
||||
setStatus('connected', t('common.generating'));
|
||||
};
|
||||
|
||||
es.onmessage = (event) => {
|
||||
if (!event || !event.data) return;
|
||||
if (event.data === '[DONE]') {
|
||||
finishRun();
|
||||
return;
|
||||
}
|
||||
let payload = null;
|
||||
try {
|
||||
payload = JSON.parse(event.data);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
if (payload && payload.error) {
|
||||
toast(payload.error, 'error');
|
||||
setStatus('error', t('common.generationFailed'));
|
||||
finishRun(true);
|
||||
return;
|
||||
}
|
||||
const choice = payload.choices && payload.choices[0];
|
||||
const delta = choice && choice.delta ? choice.delta : null;
|
||||
if (delta && delta.content) {
|
||||
handleDelta(delta.content);
|
||||
}
|
||||
if (choice && choice.finish_reason === 'stop') {
|
||||
finishRun();
|
||||
}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
if (!isRunning) return;
|
||||
setStatus('error', t('common.connectionError'));
|
||||
finishRun(true);
|
||||
};
|
||||
}
|
||||
|
||||
async function stopConnection() {
|
||||
const authHeader = await ensureFunctionKey();
|
||||
if (authHeader !== null) {
|
||||
await stopVideoTask(currentTaskId, authHeader);
|
||||
}
|
||||
closeSource();
|
||||
isRunning = false;
|
||||
currentTaskId = '';
|
||||
stopElapsedTimer();
|
||||
setButtons(false);
|
||||
setStatus('', t('common.notConnected'));
|
||||
}
|
||||
|
||||
function finishRun(hasError) {
|
||||
if (!isRunning) return;
|
||||
closeSource();
|
||||
isRunning = false;
|
||||
setButtons(false);
|
||||
stopElapsedTimer();
|
||||
if (!hasError) {
|
||||
setStatus('connected', t('common.done'));
|
||||
setIndeterminate(false);
|
||||
updateProgress(100);
|
||||
}
|
||||
if (durationValue && startAt) {
|
||||
const seconds = Math.max(0, Math.round((Date.now() - startAt) / 1000));
|
||||
durationValue.textContent = t('video.elapsedTime', { sec: seconds });
|
||||
}
|
||||
}
|
||||
|
||||
if (startBtn) {
|
||||
startBtn.addEventListener('click', () => startConnection());
|
||||
}
|
||||
|
||||
if (stopBtn) {
|
||||
stopBtn.addEventListener('click', () => stopConnection());
|
||||
}
|
||||
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', () => resetOutput());
|
||||
}
|
||||
|
||||
if (videoStage) {
|
||||
videoStage.addEventListener('click', async (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
if (!target.classList.contains('video-download')) return;
|
||||
event.preventDefault();
|
||||
const item = target.closest('.video-item');
|
||||
if (!item) return;
|
||||
const url = item.dataset.url || target.dataset.url || '';
|
||||
const index = item.dataset.index || '';
|
||||
if (!url) return;
|
||||
try {
|
||||
const response = await fetch(url, { mode: 'cors' });
|
||||
if (!response.ok) {
|
||||
throw new Error('download_failed');
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = blobUrl;
|
||||
anchor.download = index ? `grok_video_${index}.mp4` : 'grok_video.mp4';
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
} catch (e) {
|
||||
toast(t('video.downloadFailed'), 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (imageFileInput) {
|
||||
imageFileInput.addEventListener('change', () => {
|
||||
const files = imageFileInput.files ? Array.from(imageFileInput.files) : [];
|
||||
if (!files.length) {
|
||||
clearFileSelection();
|
||||
return;
|
||||
}
|
||||
if (files.length > MAX_REFERENCE_IMAGES) {
|
||||
clearFileSelection();
|
||||
toast(t('video.referenceLimit'), 'error');
|
||||
return;
|
||||
}
|
||||
if (imageUrlInput && imageUrlInput.value.trim()) {
|
||||
imageUrlInput.value = '';
|
||||
}
|
||||
Promise.all(files.map(file => new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (typeof reader.result === 'string') {
|
||||
resolve({ name: file.name, data: reader.result });
|
||||
} else {
|
||||
reject(new Error('read_failed'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('read_failed'));
|
||||
reader.readAsDataURL(file);
|
||||
}))).then(items => {
|
||||
fileDataUrls = items.map(item => item.data);
|
||||
updateReferenceSummary(items.map((item, index) => `${index + 1}. ${item.name}`));
|
||||
}).catch(() => {
|
||||
fileDataUrls = [];
|
||||
toast(t('common.fileReadFailed'), 'error');
|
||||
updateReferenceSummary([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (selectImageFileBtn && imageFileInput) {
|
||||
selectImageFileBtn.addEventListener('click', () => {
|
||||
imageFileInput.click();
|
||||
});
|
||||
}
|
||||
|
||||
if (clearImageFileBtn) {
|
||||
clearImageFileBtn.addEventListener('click', () => {
|
||||
clearFileSelection();
|
||||
});
|
||||
}
|
||||
|
||||
if (imageUrlInput) {
|
||||
imageUrlInput.addEventListener('input', () => {
|
||||
const urls = parseReferenceUrls(imageUrlInput.value);
|
||||
if (urls.length > MAX_REFERENCE_IMAGES) {
|
||||
toast(t('video.referenceLimit'), 'error');
|
||||
}
|
||||
if (imageUrlInput.value.trim() && fileDataUrls.length) {
|
||||
clearFileSelection();
|
||||
}
|
||||
if (urls.length) {
|
||||
updateReferenceSummary(urls.map((url, index) => `${index + 1}. ${url}`));
|
||||
} else if (!fileDataUrls.length) {
|
||||
updateReferenceSummary([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (promptInput) {
|
||||
promptInput.addEventListener('keydown', (event) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
startConnection();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateMeta();
|
||||
})();
|
||||
@@ -1,96 +0,0 @@
|
||||
/* Voice — LiveKit session, updated API paths */
|
||||
(() => {
|
||||
let Room, createLocalTracks, RoomEvent, Track, room = null, visualizerTimer = null;
|
||||
const $ = id => document.getElementById(id);
|
||||
const startBtn=$('startBtn'), stopBtn=$('stopBtn'), statusText=$('statusText'),
|
||||
logContainer=$('log'), voiceSelect=$('voiceSelect'), personalitySelect=$('personalitySelect'),
|
||||
speedRange=$('speedRange'), speedValue=$('speedValue'), statusVoice=$('statusVoice'),
|
||||
statusPersonality=$('statusPersonality'), statusSpeed=$('statusSpeed'),
|
||||
audioRoot=$('audioRoot'), copyLogBtn=$('copyLogBtn'), clearLogBtn=$('clearLogBtn'),
|
||||
visualizer=$('visualizer');
|
||||
|
||||
function log(msg, level='info') {
|
||||
if (!logContainer) return;
|
||||
const p = document.createElement('p');
|
||||
p.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||
if (level === 'error') p.classList.add('log-error');
|
||||
else if (level === 'warn') p.classList.add('log-warn');
|
||||
logContainer.prepend(p);
|
||||
}
|
||||
function toast(msg, type) { if (typeof showToast === 'function') showToast(msg, type); else log(msg, type === 'error' ? 'error' : 'info'); }
|
||||
function setStatus(state, text) { if (!statusText) return; statusText.textContent = text; statusText.className = 'status-text' + (state ? ' ' + state : ''); }
|
||||
function setButtons(connected) { startBtn?.classList.toggle('hidden', connected); stopBtn?.classList.toggle('hidden', !connected); if (!connected && startBtn) startBtn.disabled = false; }
|
||||
function updateMeta() { if (statusVoice) statusVoice.textContent = voiceSelect.value; if (statusPersonality) statusPersonality.textContent = personalitySelect.value; if (statusSpeed) statusSpeed.textContent = speedRange.value + 'x'; }
|
||||
|
||||
function initLK() { const lk = window.LiveKitClient || window.LivekitClient; if (!lk) return false; Room=lk.Room; createLocalTracks=lk.createLocalTracks; RoomEvent=lk.RoomEvent; Track=lk.Track; return true; }
|
||||
function ensureLK() { if (Room) return true; if (!initLK()) { log(t('voice.livekitSDKError'),'error'); toast(t('voice.livekitLoadFailed'),'error'); return false; } return true; }
|
||||
|
||||
async function startSession() {
|
||||
if (!ensureLK()) return;
|
||||
const auth = await ensureFunctionKey();
|
||||
if (auth === null) { toast(t('common.configurePublicKey'),'error'); window.location.href='/login'; return; }
|
||||
startBtn.disabled = true; updateMeta(); setStatus('connecting', t('voice.connectingStatus')); log(t('voice.fetchingToken'));
|
||||
const params = new URLSearchParams({ voice: voiceSelect.value, personality: personalitySelect.value, speed: speedRange.value });
|
||||
try {
|
||||
const res = await fetch(`${FN_BASE}/voice/token?${params}`, { headers: buildAuthHeaders(auth) });
|
||||
if (!res.ok) throw new Error(t('voice.fetchTokenFailed', { status: res.status }));
|
||||
const { token, url } = await res.json();
|
||||
log(`${t('voice.fetchTokenSuccess')} (${voiceSelect.value}, ${personalitySelect.value}, ${speedRange.value}x)`);
|
||||
room = new Room({ adaptiveStream: true, dynacast: true });
|
||||
room.on(RoomEvent.ParticipantConnected, p => log(t('voice.participantConnected', { identity: p.identity })));
|
||||
room.on(RoomEvent.ParticipantDisconnected, p => log(t('voice.participantDisconnected', { identity: p.identity })));
|
||||
room.on(RoomEvent.TrackSubscribed, track => {
|
||||
log(t('voice.trackSubscribed', { kind: track.kind }));
|
||||
if (track.kind === Track.Kind.Audio) { const el = track.attach(); (audioRoot || document.body).appendChild(el); }
|
||||
});
|
||||
room.on(RoomEvent.Disconnected, () => { log(t('voice.disconnected')); resetUI(); });
|
||||
await room.connect(url, token);
|
||||
log(t('voice.connectedToServer')); setStatus('connected', t('voice.inCall')); setButtons(true);
|
||||
log(t('voice.openingMic'));
|
||||
const tracks = await createLocalTracks({ audio: true, video: false });
|
||||
for (const tr of tracks) await room.localParticipant.publishTrack(tr);
|
||||
log(t('voice.voiceEnabled')); toast(t('voice.voiceConnected'), 'success');
|
||||
} catch (err) {
|
||||
const msg = err?.message || t('common.connectionFailed');
|
||||
log(t('voice.errorPrefix', { msg }), 'error'); toast(msg, 'error');
|
||||
setStatus('error', t('common.connectionError')); startBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopSession() { if (room) await room.disconnect(); resetUI(); }
|
||||
function resetUI() { setStatus('', t('common.notConnected')); setButtons(false); if (audioRoot) audioRoot.innerHTML = ''; }
|
||||
|
||||
speedRange?.addEventListener('input', e => {
|
||||
speedValue.textContent = Number(e.target.value).toFixed(1);
|
||||
const pct = ((e.target.value - speedRange.min) / (speedRange.max - speedRange.min)) * 100;
|
||||
speedRange.style.setProperty('--range-progress', pct + '%');
|
||||
updateMeta();
|
||||
});
|
||||
voiceSelect?.addEventListener('change', updateMeta);
|
||||
personalitySelect?.addEventListener('change', updateMeta);
|
||||
startBtn?.addEventListener('click', startSession);
|
||||
stopBtn?.addEventListener('click', stopSession);
|
||||
copyLogBtn?.addEventListener('click', async () => {
|
||||
const lines = Array.from(logContainer.querySelectorAll('p')).map(p => p.textContent).join('\n');
|
||||
try { await navigator.clipboard.writeText(lines); toast(t('voice.logCopied'),'success'); } catch { toast(t('voice.copyLogFailed'),'error'); }
|
||||
});
|
||||
clearLogBtn?.addEventListener('click', () => { if (logContainer) logContainer.innerHTML = ''; });
|
||||
|
||||
// Init
|
||||
speedValue.textContent = Number(speedRange.value).toFixed(1);
|
||||
{ const pct = ((speedRange.value - speedRange.min) / (speedRange.max - speedRange.min)) * 100; speedRange.style.setProperty('--range-progress', pct + '%'); }
|
||||
|
||||
function buildBars() {
|
||||
if (!visualizer) return;
|
||||
visualizer.innerHTML = '';
|
||||
const n = Math.max(36, Math.floor(visualizer.offsetWidth / 7));
|
||||
for (let i = 0; i < n; i++) { const b = document.createElement('div'); b.className = 'bar'; visualizer.appendChild(b); }
|
||||
}
|
||||
window.addEventListener('resize', buildBars);
|
||||
buildBars(); updateMeta(); setStatus('', t('common.notConnected'));
|
||||
visualizerTimer = setInterval(() => {
|
||||
visualizer?.querySelectorAll('.bar').forEach(b => {
|
||||
b.style.height = statusText?.classList.contains('connected') ? `${Math.random()*32+6}px` : '6px';
|
||||
});
|
||||
}, 150);
|
||||
})();
|
||||
@@ -16,6 +16,7 @@ from .repository import AccountRepository
|
||||
from .state_machine import AccountFeedback, StatePolicy, apply_feedback, clear_failures, derive_status, is_selectable
|
||||
from .quota_defaults import BASIC_QUOTA_DEFAULTS, SUPER_QUOTA_DEFAULTS, default_quota_set
|
||||
from .refresh import AccountRefreshService, RefreshResult
|
||||
from .runtime import get_refresh_service, set_refresh_service
|
||||
from .scheduler import AccountRefreshScheduler, get_account_refresh_scheduler
|
||||
from .backends.factory import create_repository
|
||||
|
||||
@@ -30,6 +31,7 @@ __all__ = [
|
||||
"derive_status", "is_selectable",
|
||||
"BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set",
|
||||
"AccountRefreshService", "RefreshResult",
|
||||
"get_refresh_service", "set_refresh_service",
|
||||
"AccountRefreshScheduler", "get_account_refresh_scheduler",
|
||||
"create_repository",
|
||||
]
|
||||
@@ -1,18 +1,21 @@
|
||||
"""Account repository factory — selects the backend from configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
"""Account repository factory — selects the backend from startup env."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from app.platform.config.snapshot import get_config
|
||||
from ..repository import AccountRepository
|
||||
|
||||
_DEFAULT_LOCAL_PATH = "data/accounts.db"
|
||||
_DEFAULT_REDIS_URL = "redis://localhost:6379/0"
|
||||
_SUPPORTED_BACKENDS = {"local", "redis", "mysql", "postgresql"}
|
||||
|
||||
|
||||
def create_repository() -> AccountRepository:
|
||||
"""Instantiate the configured account storage backend.
|
||||
|
||||
Config key: ``account.storage`` (default: ``"local"``)
|
||||
Startup env: ``ACCOUNT_STORAGE`` (default: ``"local"``)
|
||||
|
||||
Supported values:
|
||||
``local`` — SQLite (default, single-process)
|
||||
@@ -20,40 +23,96 @@ def create_repository() -> AccountRepository:
|
||||
``mysql`` — MySQL via asyncmy / SQLAlchemy
|
||||
``postgresql`` — PostgreSQL via asyncpg / SQLAlchemy
|
||||
"""
|
||||
backend = get_config("account.storage", "local").strip().lower()
|
||||
backend = get_repository_backend()
|
||||
|
||||
if backend == "local":
|
||||
return _make_local()
|
||||
if backend == "redis":
|
||||
return _make_redis()
|
||||
if backend in ("mysql", "mariadb"):
|
||||
if backend == "mysql":
|
||||
return _make_sql("mysql")
|
||||
if backend in ("postgresql", "postgres", "pgsql"):
|
||||
if backend == "postgresql":
|
||||
return _make_sql("postgresql")
|
||||
|
||||
raise ValueError(f"Unknown account storage backend: {backend!r}")
|
||||
|
||||
|
||||
def describe_repository_target() -> tuple[str, str]:
|
||||
"""Return current storage backend and a log-safe target description."""
|
||||
backend = get_repository_backend()
|
||||
|
||||
if backend == "local":
|
||||
return "local", str(_resolve_local_db_path())
|
||||
if backend == "redis":
|
||||
return "redis", _redact_url(_get_env("ACCOUNT_REDIS_URL", _DEFAULT_REDIS_URL))
|
||||
if backend == "mysql":
|
||||
return "mysql", _redact_url(_get_env("ACCOUNT_MYSQL_URL"))
|
||||
if backend == "postgresql":
|
||||
return "postgresql", _redact_url(_get_env("ACCOUNT_POSTGRESQL_URL"))
|
||||
return backend, "<unknown>"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backend constructors
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def get_repository_backend() -> str:
|
||||
"""Return the configured account storage backend from startup env."""
|
||||
backend = _get_env("ACCOUNT_STORAGE", "local").lower()
|
||||
if backend not in _SUPPORTED_BACKENDS:
|
||||
raise ValueError(f"Unknown account storage backend: {backend!r}")
|
||||
return backend
|
||||
|
||||
|
||||
def _get_env(name: str, default: str = "") -> str:
|
||||
value = os.getenv(name)
|
||||
if value is None:
|
||||
return default
|
||||
value = value.strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def _resolve_local_db_path() -> Path:
|
||||
path_str = _get_env("ACCOUNT_LOCAL_PATH", _DEFAULT_LOCAL_PATH)
|
||||
db_path = Path(path_str)
|
||||
if not db_path.is_absolute():
|
||||
db_path = Path(__file__).resolve().parents[4] / db_path
|
||||
return db_path
|
||||
|
||||
|
||||
def _redact_url(url: Any) -> str:
|
||||
raw = str(url or "").strip()
|
||||
if not raw:
|
||||
return "<empty>"
|
||||
try:
|
||||
parts = urlsplit(raw)
|
||||
except Exception:
|
||||
return raw
|
||||
if not parts.scheme:
|
||||
return raw
|
||||
hostname = parts.hostname or ""
|
||||
if parts.port:
|
||||
hostname = f"{hostname}:{parts.port}"
|
||||
if parts.username:
|
||||
auth = f"{parts.username}:***@"
|
||||
elif parts.password:
|
||||
auth = "***@"
|
||||
else:
|
||||
auth = ""
|
||||
return urlunsplit((parts.scheme, f"{auth}{hostname}", parts.path, parts.query, parts.fragment))
|
||||
|
||||
|
||||
def _make_local() -> AccountRepository:
|
||||
from .local import LocalAccountRepository
|
||||
|
||||
path_str = get_config("account.local.path", "data/accounts.db")
|
||||
db_path = Path(path_str)
|
||||
if not db_path.is_absolute():
|
||||
# Resolve relative to project root.
|
||||
db_path = Path(__file__).resolve().parents[5] / db_path
|
||||
return LocalAccountRepository(db_path)
|
||||
return LocalAccountRepository(_resolve_local_db_path())
|
||||
|
||||
|
||||
def _make_redis() -> AccountRepository:
|
||||
from redis.asyncio import Redis
|
||||
from .redis import RedisAccountRepository
|
||||
|
||||
url = get_config("account.redis.url", "redis://localhost:6379/0")
|
||||
url = _get_env("ACCOUNT_REDIS_URL", _DEFAULT_REDIS_URL)
|
||||
r = Redis.from_url(url, decode_responses=False)
|
||||
return RedisAccountRepository(r)
|
||||
|
||||
@@ -62,12 +121,12 @@ def _make_sql(dialect: str) -> AccountRepository:
|
||||
from .sql import SqlAccountRepository, create_mysql_engine, create_pgsql_engine
|
||||
|
||||
if dialect == "mysql":
|
||||
url = get_config("account.mysql.url", "")
|
||||
url = _get_env("ACCOUNT_MYSQL_URL")
|
||||
engine = create_mysql_engine(url)
|
||||
else:
|
||||
url = get_config("account.postgresql.url", "")
|
||||
url = _get_env("ACCOUNT_POSTGRESQL_URL")
|
||||
engine = create_pgsql_engine(url)
|
||||
return SqlAccountRepository(engine, dialect=dialect)
|
||||
|
||||
|
||||
__all__ = ["create_repository"]
|
||||
__all__ = ["create_repository", "describe_repository_target", "get_repository_backend"]
|
||||
@@ -1,7 +1,5 @@
|
||||
"""SQLite account repository (WAL mode, single-process default backend)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
@@ -21,7 +19,7 @@ from ..models import (
|
||||
)
|
||||
from ..quota_defaults import default_quota_set
|
||||
|
||||
_SCHEMA_VERSION = 2
|
||||
_SCHEMA_VERSION = 3
|
||||
_TBL = "accounts"
|
||||
_META = "account_meta"
|
||||
|
||||
@@ -67,6 +65,7 @@ class LocalAccountRepository:
|
||||
quota_auto TEXT NOT NULL DEFAULT '{{}}',
|
||||
quota_fast TEXT NOT NULL DEFAULT '{{}}',
|
||||
quota_expert TEXT NOT NULL DEFAULT '{{}}',
|
||||
quota_heavy TEXT NOT NULL DEFAULT '{{}}',
|
||||
usage_use_count INTEGER NOT NULL DEFAULT 0,
|
||||
usage_fail_count INTEGER NOT NULL DEFAULT 0,
|
||||
usage_sync_count INTEGER NOT NULL DEFAULT 0,
|
||||
@@ -87,6 +86,21 @@ class LocalAccountRepository:
|
||||
CREATE INDEX IF NOT EXISTS idx_acc_deleted
|
||||
ON {_TBL} (deleted_at) WHERE deleted_at IS NOT NULL;
|
||||
""")
|
||||
# Incremental schema migrations.
|
||||
ver_row = conn.execute(
|
||||
f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'schema_version'"
|
||||
).fetchone()
|
||||
ver = int(ver_row[0]) if ver_row else 1
|
||||
if ver < 3:
|
||||
try:
|
||||
conn.execute(
|
||||
f"ALTER TABLE {_TBL} ADD COLUMN quota_heavy TEXT NOT NULL DEFAULT '{{}}'"
|
||||
)
|
||||
except Exception:
|
||||
pass # Column already exists in partial migrations.
|
||||
conn.execute(
|
||||
f"UPDATE {_META} SET value = '3' WHERE key = 'schema_version'"
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def _bump_revision(self, conn: sqlite3.Connection) -> int:
|
||||
@@ -108,10 +122,13 @@ class LocalAccountRepository:
|
||||
def _row_to_record(row: sqlite3.Row) -> AccountRecord:
|
||||
d = dict(row)
|
||||
d["tags"] = json.loads(d.get("tags") or "[]")
|
||||
heavy_raw = d.pop("quota_heavy", "{}") or "{}"
|
||||
heavy_dict = json.loads(heavy_raw)
|
||||
d["quota"] = {
|
||||
"auto": json.loads(d.pop("quota_auto", "{}") or "{}"),
|
||||
"fast": json.loads(d.pop("quota_fast", "{}") or "{}"),
|
||||
"expert": json.loads(d.pop("quota_expert", "{}") or "{}"),
|
||||
**({"heavy": heavy_dict} if heavy_dict else {}),
|
||||
}
|
||||
d["ext"] = json.loads(d.get("ext") or "{}")
|
||||
return AccountRecord.model_validate(d)
|
||||
@@ -129,6 +146,7 @@ class LocalAccountRepository:
|
||||
"quota_auto": json.dumps(qs.auto.to_dict()),
|
||||
"quota_fast": json.dumps(qs.fast.to_dict()),
|
||||
"quota_expert": json.dumps(qs.expert.to_dict()),
|
||||
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
||||
"usage_use_count": record.usage_use_count,
|
||||
"usage_fail_count": record.usage_fail_count,
|
||||
"usage_sync_count": record.usage_sync_count,
|
||||
@@ -156,21 +174,24 @@ class LocalAccountRepository:
|
||||
token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token
|
||||
except Exception:
|
||||
continue
|
||||
qs = default_quota_set(item.pool)
|
||||
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
||||
qs = default_quota_set(pool)
|
||||
conn.execute(
|
||||
f"""
|
||||
INSERT INTO {_TBL} (
|
||||
token, pool, status, created_at, updated_at,
|
||||
tags, quota_auto, quota_fast, quota_expert,
|
||||
tags, quota_auto, quota_fast, quota_expert, quota_heavy,
|
||||
usage_use_count, usage_fail_count, usage_sync_count,
|
||||
ext, revision
|
||||
) VALUES (
|
||||
:token, :pool, 'active', :ts, :ts,
|
||||
:tags, :qa, :qf, :qe,
|
||||
:tags, :qa, :qf, :qe, :qh,
|
||||
0, 0, 0, :ext, :rev
|
||||
)
|
||||
ON CONFLICT(token) DO UPDATE SET
|
||||
pool = excluded.pool,
|
||||
status = 'active',
|
||||
deleted_at = NULL,
|
||||
updated_at = excluded.updated_at,
|
||||
tags = excluded.tags,
|
||||
ext = excluded.ext,
|
||||
@@ -178,12 +199,13 @@ class LocalAccountRepository:
|
||||
""",
|
||||
{
|
||||
"token": token,
|
||||
"pool": item.pool if item.pool in ("basic", "super") else "basic",
|
||||
"pool": pool,
|
||||
"ts": ts,
|
||||
"tags": json.dumps(item.tags),
|
||||
"qa": json.dumps(qs.auto.to_dict()),
|
||||
"qf": json.dumps(qs.fast.to_dict()),
|
||||
"qe": json.dumps(qs.expert.to_dict()),
|
||||
"qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
||||
"ext": json.dumps(item.ext),
|
||||
"rev": revision,
|
||||
},
|
||||
@@ -211,6 +233,8 @@ class LocalAccountRepository:
|
||||
|
||||
sets: dict[str, Any] = {"updated_at": ts, "revision": revision}
|
||||
|
||||
if patch.pool is not None:
|
||||
sets["pool"] = patch.pool
|
||||
if patch.status is not None:
|
||||
sets["status"] = patch.status.value
|
||||
if patch.state_reason is not None:
|
||||
@@ -241,6 +265,8 @@ class LocalAccountRepository:
|
||||
sets["quota_fast"] = json.dumps(patch.quota_fast)
|
||||
if patch.quota_expert is not None:
|
||||
sets["quota_expert"] = json.dumps(patch.quota_expert)
|
||||
if patch.quota_heavy is not None:
|
||||
sets["quota_heavy"] = json.dumps(patch.quota_heavy)
|
||||
|
||||
# Tags.
|
||||
tags = list(record.tags)
|
||||
|
||||
@@ -7,8 +7,6 @@ Layout:
|
||||
accounts:revision_log — ZSET token → revision (for scan_changes)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
@@ -68,6 +66,7 @@ class RedisAccountRepository:
|
||||
"quota_auto": json.dumps(qs.auto.to_dict()),
|
||||
"quota_fast": json.dumps(qs.fast.to_dict()),
|
||||
"quota_expert": json.dumps(qs.expert.to_dict()),
|
||||
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
||||
"usage_use_count": str(record.usage_use_count),
|
||||
"usage_fail_count": str(record.usage_fail_count),
|
||||
"usage_sync_count": str(record.usage_sync_count),
|
||||
@@ -103,6 +102,9 @@ class RedisAccountRepository:
|
||||
"auto": json.loads(_s("quota_auto") or "{}"),
|
||||
"fast": json.loads(_s("quota_fast") or "{}"),
|
||||
"expert": json.loads(_s("quota_expert") or "{}"),
|
||||
**({
|
||||
"heavy": json.loads(_s("quota_heavy"))
|
||||
} if _s("quota_heavy") and _s("quota_heavy") != "{}" else {}),
|
||||
},
|
||||
"usage_use_count": int(_s("usage_use_count") or 0),
|
||||
"usage_fail_count": int(_s("usage_fail_count") or 0),
|
||||
@@ -205,7 +207,7 @@ class RedisAccountRepository:
|
||||
token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token
|
||||
except Exception:
|
||||
continue
|
||||
pool = item.pool if item.pool in ("basic", "super") else "basic"
|
||||
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
||||
qs = default_quota_set(pool)
|
||||
ts = now_ms()
|
||||
record = AccountRecord(
|
||||
@@ -259,12 +261,16 @@ class RedisAccountRepository:
|
||||
updates["last_sync_at"] = str(patch.last_sync_at)
|
||||
if patch.last_clear_at is not None:
|
||||
updates["last_clear_at"] = str(patch.last_clear_at)
|
||||
if patch.pool is not None:
|
||||
updates["pool"] = patch.pool
|
||||
if patch.quota_auto is not None:
|
||||
updates["quota_auto"] = json.dumps(patch.quota_auto)
|
||||
if patch.quota_fast is not None:
|
||||
updates["quota_fast"] = json.dumps(patch.quota_fast)
|
||||
if patch.quota_expert is not None:
|
||||
updates["quota_expert"] = json.dumps(patch.quota_expert)
|
||||
if patch.quota_heavy is not None:
|
||||
updates["quota_heavy"] = json.dumps(patch.quota_heavy)
|
||||
|
||||
# Usage counters.
|
||||
if patch.usage_use_delta is not None:
|
||||
|
||||
@@ -4,8 +4,6 @@ Both dialects share the same table schema and query logic;
|
||||
only the DDL fragments and upsert syntax differ.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
@@ -41,6 +39,7 @@ accounts_table = sa.Table(
|
||||
sa.Column("quota_auto", sa.Text, nullable=False, default="{}"),
|
||||
sa.Column("quota_fast", sa.Text, nullable=False, default="{}"),
|
||||
sa.Column("quota_expert", sa.Text, nullable=False, default="{}"),
|
||||
sa.Column("quota_heavy", sa.Text, nullable=False, default="{}"),
|
||||
sa.Column("usage_use_count", sa.Integer, nullable=False, default=0),
|
||||
sa.Column("usage_fail_count", sa.Integer, nullable=False, default=0),
|
||||
sa.Column("usage_sync_count", sa.Integer, nullable=False, default=0),
|
||||
@@ -66,10 +65,13 @@ meta_table = sa.Table(
|
||||
def _row_to_record(row: Any) -> AccountRecord:
|
||||
d = dict(row._mapping)
|
||||
d["tags"] = json.loads(d.get("tags") or "[]")
|
||||
heavy_raw = d.pop("quota_heavy", "{}") or "{}"
|
||||
heavy_dict = json.loads(heavy_raw)
|
||||
d["quota"] = {
|
||||
"auto": json.loads(d.pop("quota_auto", "{}") or "{}"),
|
||||
"fast": json.loads(d.pop("quota_fast", "{}") or "{}"),
|
||||
"expert": json.loads(d.pop("quota_expert", "{}") or "{}"),
|
||||
**({"heavy": heavy_dict} if heavy_dict else {}),
|
||||
}
|
||||
d["ext"] = json.loads(d.get("ext") or "{}")
|
||||
return AccountRecord.model_validate(d)
|
||||
@@ -203,7 +205,7 @@ class SqlAccountRepository:
|
||||
token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token
|
||||
except Exception:
|
||||
continue
|
||||
pool = item.pool if item.pool in ("basic", "super") else "basic"
|
||||
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
||||
qs = default_quota_set(pool)
|
||||
row = {
|
||||
"token": token,
|
||||
@@ -211,10 +213,12 @@ class SqlAccountRepository:
|
||||
"status": "active",
|
||||
"created_at": ts,
|
||||
"updated_at": ts,
|
||||
"deleted_at": None, # clear soft-delete on re-import
|
||||
"tags": json.dumps(item.tags),
|
||||
"quota_auto": json.dumps(qs.auto.to_dict()),
|
||||
"quota_fast": json.dumps(qs.fast.to_dict()),
|
||||
"quota_expert": json.dumps(qs.expert.to_dict()),
|
||||
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
||||
"usage_use_count": 0,
|
||||
"usage_fail_count": 0,
|
||||
"usage_sync_count": 0,
|
||||
@@ -245,6 +249,8 @@ class SqlAccountRepository:
|
||||
qs = record.quota_set()
|
||||
|
||||
updates: dict[str, Any] = {"updated_at": ts, "revision": rev}
|
||||
if patch.pool is not None:
|
||||
updates["pool"] = patch.pool
|
||||
if patch.status is not None:
|
||||
updates["status"] = patch.status.value
|
||||
if patch.state_reason is not None:
|
||||
@@ -265,6 +271,8 @@ class SqlAccountRepository:
|
||||
updates["quota_fast"] = json.dumps(patch.quota_fast)
|
||||
if patch.quota_expert is not None:
|
||||
updates["quota_expert"] = json.dumps(patch.quota_expert)
|
||||
if patch.quota_heavy is not None:
|
||||
updates["quota_heavy"] = json.dumps(patch.quota_heavy)
|
||||
if patch.usage_use_delta is not None:
|
||||
updates["usage_use_count"] = max(0, record.usage_use_count + patch.usage_use_delta)
|
||||
if patch.usage_fail_delta is not None:
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Command / query objects for the account control plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -28,6 +26,7 @@ class AccountPatch(BaseModel):
|
||||
"""
|
||||
|
||||
token: str
|
||||
pool: str | None = None # update pool type when inferred
|
||||
status: AccountStatus | None = None
|
||||
tags: list[str] | None = None
|
||||
add_tags: list[str] | None = None
|
||||
@@ -36,6 +35,7 @@ class AccountPatch(BaseModel):
|
||||
quota_auto: dict[str, Any] | None = None
|
||||
quota_fast: dict[str, Any] | None = None
|
||||
quota_expert: dict[str, Any] | None = None
|
||||
quota_heavy: dict[str, Any] | None = None
|
||||
# Usage counters — delta values (added to existing counts).
|
||||
usage_use_delta: int | None = None
|
||||
usage_fail_delta: int | None = None
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Control-plane account enumerations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import IntEnum, StrEnum
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Control-plane account models — persistent record shape."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
@@ -69,19 +67,25 @@ class QuotaWindow:
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AccountQuotaSet:
|
||||
"""Three-dimensional quota set — one window per mode."""
|
||||
"""Quota set — one window per mode (auto / fast / expert / heavy).
|
||||
|
||||
``heavy`` is ``None`` for basic and super accounts.
|
||||
"""
|
||||
|
||||
auto: QuotaWindow
|
||||
fast: QuotaWindow
|
||||
expert: QuotaWindow
|
||||
heavy: QuotaWindow | None = None # heavy-pool accounts only
|
||||
|
||||
def get(self, mode_id: int) -> QuotaWindow:
|
||||
"""Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert)."""
|
||||
def get(self, mode_id: int) -> QuotaWindow | None:
|
||||
"""Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert, 3=heavy)."""
|
||||
if mode_id == 0:
|
||||
return self.auto
|
||||
if mode_id == 1:
|
||||
return self.fast
|
||||
return self.expert
|
||||
if mode_id == 2:
|
||||
return self.expert
|
||||
return self.heavy # mode_id == 3
|
||||
|
||||
def set(self, mode_id: int, window: QuotaWindow) -> None:
|
||||
"""Replace the quota window for *mode_id*."""
|
||||
@@ -89,22 +93,29 @@ class AccountQuotaSet:
|
||||
self.auto = window
|
||||
elif mode_id == 1:
|
||||
self.fast = window
|
||||
else:
|
||||
elif mode_id == 2:
|
||||
self.expert = window
|
||||
else:
|
||||
self.heavy = window # mode_id == 3
|
||||
|
||||
def to_dict(self) -> dict[str, dict[str, Any]]:
|
||||
return {
|
||||
d: dict[str, dict[str, Any]] = {
|
||||
"auto": self.auto.to_dict(),
|
||||
"fast": self.fast.to_dict(),
|
||||
"expert": self.expert.to_dict(),
|
||||
}
|
||||
if self.heavy is not None:
|
||||
d["heavy"] = self.heavy.to_dict()
|
||||
return d
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, d: dict[str, Any]) -> "AccountQuotaSet":
|
||||
heavy_d = d.get("heavy")
|
||||
return cls(
|
||||
auto = QuotaWindow.from_dict(d.get("auto", {})),
|
||||
fast = QuotaWindow.from_dict(d.get("fast", {})),
|
||||
expert = QuotaWindow.from_dict(d.get("expert", {})),
|
||||
heavy = QuotaWindow.from_dict(heavy_d) if heavy_d else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -143,7 +154,7 @@ class AccountUsageStats:
|
||||
class AccountRecord(BaseModel):
|
||||
"""Persistent account record — single source of truth for all backends.
|
||||
|
||||
``pool`` values: ``"basic"`` | ``"super"``
|
||||
``pool`` values: ``"basic"`` | ``"super"`` | ``"heavy"``
|
||||
All timestamps are milliseconds since epoch.
|
||||
``ext`` carries non-core extension data only.
|
||||
"""
|
||||
@@ -181,6 +192,10 @@ class AccountRecord(BaseModel):
|
||||
def is_super(self) -> bool:
|
||||
return self.pool == "super"
|
||||
|
||||
@property
|
||||
def is_heavy(self) -> bool:
|
||||
return self.pool == "heavy"
|
||||
|
||||
def is_deleted(self) -> bool:
|
||||
return self.deleted_at is not None
|
||||
|
||||
@@ -224,10 +239,13 @@ class AccountRecord(BaseModel):
|
||||
@classmethod
|
||||
def _normalize_pool(cls, v: Any) -> str:
|
||||
val = str(v or "").strip().lower()
|
||||
# Accept legacy pool names.
|
||||
if val in ("ssosuper", "super"):
|
||||
if val in ("super"):
|
||||
return "super"
|
||||
if val in ("ssobasic", "basic", ""):
|
||||
if val in ("heavy",):
|
||||
return "heavy"
|
||||
if val in ("ssobasic", "basic", "", "auto"):
|
||||
# "auto" is a UI alias meaning "let quota sync decide";
|
||||
# save as basic for now — refresh will correct to the real type.
|
||||
return "basic"
|
||||
raise ValueError(f"Unknown pool: {v!r}")
|
||||
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
"""Default quota windows applied when upstream data is unavailable."""
|
||||
"""Default quota windows and pool inference logic.
|
||||
|
||||
from __future__ import annotations
|
||||
Canonical quota totals per pool type (from upstream rate-limits API):
|
||||
|
||||
auto fast expert heavy
|
||||
basic 20 60 8 — window: 72000 / 36000 s
|
||||
super 50 140 50 — window: 7200 s
|
||||
heavy 150 400 150 20 window: 7200 s
|
||||
|
||||
Pool inference uses ``auto.total`` as the primary signal — the three values
|
||||
(20 / 50 / 150) are mutually exclusive across pool types.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .enums import QuotaSource
|
||||
from .models import AccountQuotaSet, QuotaWindow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow:
|
||||
return QuotaWindow(
|
||||
@@ -18,34 +36,75 @@ def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Basic-pool defaults
|
||||
# (static window — no API sync required)
|
||||
# Per-pool default quota sets
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
BASIC_QUOTA_DEFAULTS = AccountQuotaSet(
|
||||
auto = _w(20, 20, 72_000), # 20 queries / 20 h
|
||||
fast = _w(60, 60, 72_000), # 60 queries / 20 h
|
||||
expert = _w(8, 8, 36_000), # 8 queries / 10 h
|
||||
auto = _w(20, 20, 72_000), # 20 queries / 20 h
|
||||
fast = _w(60, 60, 72_000), # 60 queries / 20 h
|
||||
expert = _w(8, 8, 36_000), # 8 queries / 10 h
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Super-pool defaults
|
||||
# (used only when upstream API call fails; real values fetched on import)
|
||||
# ---------------------------------------------------------------------------
|
||||
SUPER_QUOTA_DEFAULTS = AccountQuotaSet(
|
||||
auto = _w(20, 20, 72_000),
|
||||
fast = _w(60, 60, 72_000),
|
||||
expert = _w(8, 8, 36_000),
|
||||
auto = _w(50, 50, 7_200), # 50 queries / 2 h
|
||||
fast = _w(140, 140, 7_200), # 140 queries / 2 h
|
||||
expert = _w(50, 50, 7_200), # 50 queries / 2 h
|
||||
)
|
||||
|
||||
HEAVY_QUOTA_DEFAULTS = AccountQuotaSet(
|
||||
auto = _w(150, 150, 7_200), # 150 queries / 2 h
|
||||
fast = _w(400, 400, 7_200), # 400 queries / 2 h
|
||||
expert = _w(150, 150, 7_200), # 150 queries / 2 h
|
||||
heavy = _w(20, 20, 7_200), # 20 queries / 2 h
|
||||
)
|
||||
|
||||
# Map pool name → defaults object (used by backends on upsert).
|
||||
_POOL_DEFAULTS: dict[str, AccountQuotaSet] = {
|
||||
"basic": BASIC_QUOTA_DEFAULTS,
|
||||
"super": SUPER_QUOTA_DEFAULTS,
|
||||
"heavy": HEAVY_QUOTA_DEFAULTS,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pool inference — keyed on auto.total (unique across pool types)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_AUTO_TOTAL_TO_POOL: dict[int, str] = {
|
||||
20: "basic",
|
||||
50: "super",
|
||||
150: "heavy",
|
||||
}
|
||||
|
||||
|
||||
def default_quota_set(pool: str) -> AccountQuotaSet:
|
||||
"""Return a fresh copy of the default quota set for *pool*."""
|
||||
src = SUPER_QUOTA_DEFAULTS if pool == "super" else BASIC_QUOTA_DEFAULTS
|
||||
return AccountQuotaSet(
|
||||
src = _POOL_DEFAULTS.get(pool, BASIC_QUOTA_DEFAULTS)
|
||||
qs = AccountQuotaSet(
|
||||
auto = _w(src.auto.remaining, src.auto.total, src.auto.window_seconds),
|
||||
fast = _w(src.fast.remaining, src.fast.total, src.fast.window_seconds),
|
||||
expert = _w(src.expert.remaining, src.expert.total, src.expert.window_seconds),
|
||||
)
|
||||
if src.heavy is not None:
|
||||
qs.heavy = _w(src.heavy.remaining, src.heavy.total, src.heavy.window_seconds)
|
||||
return qs
|
||||
|
||||
|
||||
__all__ = ["BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set"]
|
||||
def infer_pool(windows: dict[int, QuotaWindow]) -> str:
|
||||
"""Infer pool type from live quota windows returned by the rate-limits API.
|
||||
|
||||
Uses ``auto.total`` (mode_id=0) as the discriminating signal.
|
||||
Falls back to ``"basic"`` when the value is absent or unrecognised.
|
||||
"""
|
||||
auto_win = windows.get(0)
|
||||
if auto_win is None:
|
||||
return "basic"
|
||||
return _AUTO_TOTAL_TO_POOL.get(auto_win.total, "basic")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BASIC_QUOTA_DEFAULTS",
|
||||
"SUPER_QUOTA_DEFAULTS",
|
||||
"HEAVY_QUOTA_DEFAULTS",
|
||||
"default_quota_set",
|
||||
"infer_pool",
|
||||
]
|
||||
+146
-50
@@ -1,7 +1,5 @@
|
||||
"""Account refresh service — mode-aware usage synchronisation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -10,10 +8,10 @@ from app.platform.config.snapshot import get_config
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.runtime.clock import now_ms
|
||||
from app.platform.runtime.batch import run_batch
|
||||
from app.control.model.enums import ALL_MODES, ModeId
|
||||
from app.control.model.enums import ALL_MODES_WITH_HEAVY, ModeId
|
||||
from .enums import AccountStatus, FeedbackKind, QuotaSource
|
||||
from .models import AccountRecord, QuotaWindow
|
||||
from .quota_defaults import default_quota_set
|
||||
from .quota_defaults import default_quota_set, infer_pool
|
||||
from .state_machine import AccountFeedback, apply_feedback
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -89,7 +87,11 @@ class AccountRefreshService:
|
||||
return RefreshResult(checked=len(records))
|
||||
|
||||
concurrency = get_config("account.refresh.usage_concurrency", 10)
|
||||
results = await run_batch(active, self._refresh_one, concurrency=concurrency)
|
||||
results = await run_batch(
|
||||
active,
|
||||
lambda r: self._refresh_one(r, apply_fallback=True),
|
||||
concurrency=concurrency,
|
||||
)
|
||||
agg = RefreshResult(checked=len(records))
|
||||
for r in results:
|
||||
agg.merge(r)
|
||||
@@ -101,17 +103,24 @@ class AccountRefreshService:
|
||||
if record is None or record.is_deleted():
|
||||
return
|
||||
window = await self._fetch_mode_quota(token, mode_id)
|
||||
await self._apply_single_mode(record, mode_id, window)
|
||||
await self._apply_single_mode(record, mode_id, window, is_use=True, use_at_ms=now_ms())
|
||||
|
||||
async def refresh_scheduled(self) -> RefreshResult:
|
||||
"""Periodic refresh — super: fetch API; basic: static reset check."""
|
||||
async def refresh_scheduled(self, pool: str | None = None) -> RefreshResult:
|
||||
"""Periodic refresh — fetch real quotas for all (or one pool's) accounts.
|
||||
|
||||
Args:
|
||||
pool: When set, only refreshes accounts belonging to that pool.
|
||||
When ``None``, refreshes all pools (legacy / manual trigger path).
|
||||
"""
|
||||
snapshot = await self._repo.runtime_snapshot()
|
||||
records = snapshot.items
|
||||
if pool is not None:
|
||||
records = [r for r in records if r.pool == pool]
|
||||
|
||||
concurrency = get_config("account.refresh.usage_concurrency", 10)
|
||||
results = await run_batch(
|
||||
records,
|
||||
self._refresh_one,
|
||||
lambda r: self._refresh_one(r, apply_fallback=True),
|
||||
concurrency=concurrency,
|
||||
)
|
||||
agg = RefreshResult()
|
||||
@@ -150,61 +159,87 @@ class AccountRefreshService:
|
||||
# Per-account refresh
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _refresh_one(self, record: AccountRecord) -> RefreshResult:
|
||||
"""Fetch all 3 modes for any account type; apply real data or fall back gracefully."""
|
||||
async def _refresh_one(
|
||||
self,
|
||||
record: AccountRecord,
|
||||
*,
|
||||
apply_fallback: bool = False,
|
||||
) -> RefreshResult:
|
||||
"""Fetch all 3 modes from the usage API and persist real quota data.
|
||||
|
||||
apply_fallback=True — used by scheduled/import paths: when API fails,
|
||||
decrement REAL quotas or reset expired DEFAULT windows.
|
||||
apply_fallback=False — used by manual/on-demand paths: if API fails, return
|
||||
failed=1 immediately without touching stored data.
|
||||
"""
|
||||
if record.is_deleted():
|
||||
return RefreshResult()
|
||||
|
||||
windows = await self._fetch_all_quotas(record.token)
|
||||
qs = record.quota_set()
|
||||
now = now_ms()
|
||||
patches: dict[str, dict] = {}
|
||||
windows = await self._fetch_all_quotas(record.token)
|
||||
|
||||
# API call completely failed — no real data available.
|
||||
if windows is None:
|
||||
if not apply_fallback:
|
||||
return RefreshResult(checked=1, failed=1)
|
||||
# Scheduled/import path: apply conservative fallback.
|
||||
return await self._apply_fallback(record)
|
||||
|
||||
# We got at least a response — apply real data per mode.
|
||||
qs = record.quota_set()
|
||||
now = now_ms()
|
||||
patches: dict[str, dict] = {}
|
||||
refreshed = False
|
||||
|
||||
_MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert"}
|
||||
_MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert", 3: "quota_heavy"}
|
||||
|
||||
for mode in ALL_MODES:
|
||||
for mode in ALL_MODES_WITH_HEAVY:
|
||||
mode_id = int(mode)
|
||||
|
||||
if windows and mode_id in windows:
|
||||
# ✅ Got real data from API.
|
||||
if mode_id in windows:
|
||||
patches[_MODE_KEYS[mode_id]] = windows[mode_id].to_dict()
|
||||
refreshed = True
|
||||
continue
|
||||
|
||||
# ❌ API failed for this mode — apply fallback strategy.
|
||||
existing = qs.get(mode_id)
|
||||
|
||||
if existing.source == QuotaSource.REAL:
|
||||
# Had real data before: decrement by 1 (conservative estimate).
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = max(0, existing.remaining - 1),
|
||||
total = existing.total,
|
||||
window_seconds = existing.window_seconds,
|
||||
reset_at = existing.reset_at,
|
||||
synced_at = existing.synced_at,
|
||||
source = QuotaSource.ESTIMATED,
|
||||
).to_dict()
|
||||
elif existing.is_window_expired(now):
|
||||
# Default/estimated data and window has expired: reset to defaults.
|
||||
default = default_quota_set(record.pool).get(mode_id)
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = default.total,
|
||||
total = default.total,
|
||||
window_seconds = default.window_seconds,
|
||||
reset_at = now + default.window_seconds * 1000,
|
||||
synced_at = now,
|
||||
source = QuotaSource.DEFAULT,
|
||||
).to_dict()
|
||||
# else: window still valid, leave unchanged.
|
||||
elif apply_fallback:
|
||||
existing = qs.get(mode_id)
|
||||
if existing is None:
|
||||
continue
|
||||
if existing.source == QuotaSource.REAL:
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = max(0, existing.remaining - 1),
|
||||
total = existing.total,
|
||||
window_seconds = existing.window_seconds,
|
||||
reset_at = existing.reset_at,
|
||||
synced_at = existing.synced_at,
|
||||
source = QuotaSource.ESTIMATED,
|
||||
).to_dict()
|
||||
elif existing.is_window_expired(now):
|
||||
default = default_quota_set(record.pool).get(mode_id)
|
||||
if default is None:
|
||||
continue
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = default.total,
|
||||
total = default.total,
|
||||
window_seconds = default.window_seconds,
|
||||
reset_at = now + default.window_seconds * 1000,
|
||||
synced_at = now,
|
||||
source = QuotaSource.DEFAULT,
|
||||
).to_dict()
|
||||
|
||||
if not patches:
|
||||
return RefreshResult(checked=1)
|
||||
return RefreshResult(checked=1, failed=0 if refreshed else 1)
|
||||
|
||||
# Infer pool type from live quota data and patch if it changed.
|
||||
inferred = infer_pool(windows) # type: ignore[arg-type]
|
||||
pool_patch = inferred if inferred != record.pool else None
|
||||
if pool_patch:
|
||||
logger.info(
|
||||
"Pool auto-updated: token={}... {} → {}",
|
||||
record.token[:10], record.pool, inferred,
|
||||
)
|
||||
|
||||
from .commands import AccountPatch
|
||||
await self._repo.patch_accounts([
|
||||
AccountPatch(
|
||||
token = record.token,
|
||||
pool = pool_patch,
|
||||
last_sync_at = now_ms() if refreshed else None,
|
||||
usage_sync_delta = 1 if refreshed else None,
|
||||
**patches, # type: ignore[arg-type]
|
||||
@@ -214,14 +249,73 @@ class AccountRefreshService:
|
||||
return RefreshResult(
|
||||
checked=1,
|
||||
refreshed=1 if refreshed else 0,
|
||||
failed=0 if refreshed else 1,
|
||||
recovered=1 if (was_cooling and refreshed) else 0,
|
||||
)
|
||||
|
||||
async def _apply_fallback(self, record: AccountRecord) -> RefreshResult:
|
||||
"""Conservative fallback when API is unreachable (scheduled/import path only)."""
|
||||
qs = record.quota_set()
|
||||
now = now_ms()
|
||||
patches: dict[str, dict] = {}
|
||||
|
||||
_MODE_KEYS = {0: "quota_auto", 1: "quota_fast", 2: "quota_expert", 3: "quota_heavy"}
|
||||
|
||||
for mode in ALL_MODES_WITH_HEAVY:
|
||||
mode_id = int(mode)
|
||||
existing = qs.get(mode_id)
|
||||
if existing is None:
|
||||
continue
|
||||
if existing.source == QuotaSource.REAL:
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = max(0, existing.remaining - 1),
|
||||
total = existing.total,
|
||||
window_seconds = existing.window_seconds,
|
||||
reset_at = existing.reset_at,
|
||||
synced_at = existing.synced_at,
|
||||
source = QuotaSource.ESTIMATED,
|
||||
).to_dict()
|
||||
elif existing.is_window_expired(now):
|
||||
default = default_quota_set(record.pool).get(mode_id)
|
||||
if default is None:
|
||||
continue
|
||||
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
||||
remaining = default.total,
|
||||
total = default.total,
|
||||
window_seconds = default.window_seconds,
|
||||
reset_at = now + default.window_seconds * 1000,
|
||||
synced_at = now,
|
||||
source = QuotaSource.DEFAULT,
|
||||
).to_dict()
|
||||
|
||||
if patches:
|
||||
from .commands import AccountPatch
|
||||
await self._repo.patch_accounts([AccountPatch(token=record.token, **patches)]) # type: ignore[arg-type]
|
||||
|
||||
return RefreshResult(checked=1, failed=1)
|
||||
|
||||
async def record_failure_async(self, token: str, mode_id: int) -> None:
|
||||
"""Fire-and-forget: persist failure counter and timestamp after a failed call."""
|
||||
from .commands import AccountPatch
|
||||
try:
|
||||
await self._repo.patch_accounts([
|
||||
AccountPatch(
|
||||
token = token,
|
||||
usage_fail_delta = 1,
|
||||
last_fail_at = now_ms(),
|
||||
)
|
||||
])
|
||||
except Exception as exc:
|
||||
logger.debug("Failure record failed: token={}... error={}", token[:10], exc)
|
||||
|
||||
async def _apply_single_mode(
|
||||
self,
|
||||
record: AccountRecord,
|
||||
mode_id: int,
|
||||
window: QuotaWindow | None,
|
||||
*,
|
||||
is_use: bool = False,
|
||||
use_at_ms: int | None = None,
|
||||
) -> None:
|
||||
qs = record.quota_set()
|
||||
if window is not None:
|
||||
@@ -241,9 +335,11 @@ class AccountRefreshService:
|
||||
from .commands import AccountPatch
|
||||
await self._repo.patch_accounts([
|
||||
AccountPatch(
|
||||
token = record.token,
|
||||
last_sync_at = now_ms() if window is not None else None,
|
||||
token = record.token,
|
||||
last_sync_at = now_ms() if window is not None else None,
|
||||
usage_sync_delta = 1 if window is not None else None,
|
||||
usage_use_delta = 1 if is_use else None,
|
||||
last_use_at = use_at_ms if is_use else None,
|
||||
**{mode_key: win.to_dict()}, # type: ignore[arg-type]
|
||||
)
|
||||
])
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Account repository protocol — the contract every backend must satisfy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Account runtime singletons exposed without importing app.main."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .refresh import AccountRefreshService
|
||||
|
||||
_refresh_service: "AccountRefreshService | None" = None
|
||||
|
||||
|
||||
def set_refresh_service(service: "AccountRefreshService | None") -> None:
|
||||
"""Register the process-global account refresh service."""
|
||||
global _refresh_service
|
||||
_refresh_service = service
|
||||
|
||||
|
||||
def get_refresh_service() -> "AccountRefreshService | None":
|
||||
"""Return the registered account refresh service, if any."""
|
||||
return _refresh_service
|
||||
|
||||
|
||||
__all__ = ["get_refresh_service", "set_refresh_service"]
|
||||
@@ -1,6 +1,15 @@
|
||||
"""Background scheduler for periodic account quota refresh."""
|
||||
"""Background scheduler for periodic account quota refresh.
|
||||
|
||||
from __future__ import annotations
|
||||
Runs one independent loop per pool type (basic / super / heavy), each with
|
||||
its own configurable interval read from:
|
||||
|
||||
account.refresh.basic_interval_sec (default 36000 — 10 h)
|
||||
account.refresh.super_interval_sec (default 7200 — 2 h)
|
||||
account.refresh.heavy_interval_sec (default 7200 — 2 h)
|
||||
|
||||
Falls back to the legacy ``account.refresh.interval_sec`` key if the
|
||||
pool-specific key is absent (backward compatibility with existing configs).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -8,37 +17,60 @@ from app.platform.config.snapshot import get_config
|
||||
from app.platform.logging.logger import logger
|
||||
from .refresh import AccountRefreshService
|
||||
|
||||
# Pool → (config key, built-in default seconds)
|
||||
_POOL_CONFIG: dict[str, tuple[str, int]] = {
|
||||
"basic": ("account.refresh.basic_interval_sec", 36_000),
|
||||
"super": ("account.refresh.super_interval_sec", 7_200),
|
||||
"heavy": ("account.refresh.heavy_interval_sec", 7_200),
|
||||
}
|
||||
|
||||
|
||||
def _interval(pool: str) -> int:
|
||||
key, default = _POOL_CONFIG[pool]
|
||||
# Pool-specific key takes precedence; legacy key as second fallback.
|
||||
v = get_config(key, None)
|
||||
if v is None:
|
||||
v = get_config("account.refresh.interval_sec", None)
|
||||
return int(v) if v is not None else default
|
||||
|
||||
|
||||
class AccountRefreshScheduler:
|
||||
"""Runs ``AccountRefreshService.refresh_scheduled`` on a fixed interval.
|
||||
"""Runs one refresh loop per pool type at pool-specific intervals.
|
||||
|
||||
Lifecycle: ``start()`` → runs in background → ``stop()`` to cancel.
|
||||
Lifecycle: ``start()`` → loops run in background → ``stop()`` to cancel.
|
||||
"""
|
||||
|
||||
def __init__(self, refresh_service: AccountRefreshService) -> None:
|
||||
self._service = refresh_service
|
||||
self._task: asyncio.Task | None = None
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self._stop = asyncio.Event()
|
||||
|
||||
def start(self) -> None:
|
||||
if self._task and not self._task.done():
|
||||
if self._tasks and not all(t.done() for t in self._tasks):
|
||||
return
|
||||
self._stop.clear()
|
||||
self._task = asyncio.create_task(self._loop(), name="account-refresh-scheduler")
|
||||
logger.info("AccountRefreshScheduler started.")
|
||||
self._tasks = [
|
||||
asyncio.create_task(self._loop(pool), name=f"account-refresh-{pool}")
|
||||
for pool in _POOL_CONFIG
|
||||
]
|
||||
logger.info(
|
||||
"AccountRefreshScheduler started — basic={}s super={}s heavy={}s",
|
||||
_interval("basic"), _interval("super"), _interval("heavy"),
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._task and not self._task.done():
|
||||
self._task.cancel()
|
||||
for t in self._tasks:
|
||||
if not t.done():
|
||||
t.cancel()
|
||||
logger.info("AccountRefreshScheduler stopped.")
|
||||
|
||||
async def _loop(self) -> None:
|
||||
async def _loop(self, pool: str) -> None:
|
||||
while not self._stop.is_set():
|
||||
interval = int(get_config("account.refresh.interval_sec", 300))
|
||||
interval = _interval(pool)
|
||||
try:
|
||||
await asyncio.wait_for(self._stop.wait(), timeout=float(interval))
|
||||
break # stop was set
|
||||
break # stop event fired
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
@@ -46,17 +78,15 @@ class AccountRefreshScheduler:
|
||||
break
|
||||
|
||||
try:
|
||||
result = await self._service.refresh_scheduled()
|
||||
result = await self._service.refresh_scheduled(pool=pool)
|
||||
logger.info(
|
||||
"Account refresh complete: checked={} refreshed={} recovered={} "
|
||||
"expired={} disabled={} failed={}",
|
||||
result.checked, result.refreshed, result.recovered,
|
||||
result.expired, result.disabled, result.failed,
|
||||
"Account refresh [{}]: checked={} refreshed={} recovered={} failed={}",
|
||||
pool, result.checked, result.refreshed, result.recovered, result.failed,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.error("Account refresh error: {}", exc)
|
||||
logger.error("Account refresh [{}] error: {}", pool, exc)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -4,8 +4,6 @@ Applies feedback events to an AccountRecord, advancing its status
|
||||
and updating quota / usage fields accordingly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
"""Admin service layer — aggregates token CRUD and proxy management.
|
||||
|
||||
Provides a service-level API that admin handlers call instead of
|
||||
reaching directly into repositories. Centralises validation, audit
|
||||
logging, and cross-cutting concerns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.runtime.clock import now_ms
|
||||
from app.control.account.commands import (
|
||||
AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery,
|
||||
)
|
||||
from app.control.account.models import (
|
||||
AccountMutationResult, AccountPage, AccountRecord,
|
||||
)
|
||||
from app.control.account.repository import AccountRepository
|
||||
|
||||
|
||||
class AccountAdminService:
|
||||
"""High-level account administration operations."""
|
||||
|
||||
def __init__(self, repo: AccountRepository) -> None:
|
||||
self._repo = repo
|
||||
|
||||
async def list_accounts(self, query: ListAccountsQuery) -> AccountPage:
|
||||
return await self._repo.list_accounts(query)
|
||||
|
||||
async def get_accounts(self, tokens: list[str]) -> list[AccountRecord]:
|
||||
return await self._repo.get_accounts(tokens)
|
||||
|
||||
async def upsert(self, items: list[AccountUpsert]) -> AccountMutationResult:
|
||||
result = await self._repo.upsert_accounts(items)
|
||||
logger.info("Admin upsert: {} accounts affected", result.upserted)
|
||||
return result
|
||||
|
||||
async def delete(self, tokens: list[str]) -> AccountMutationResult:
|
||||
result = await self._repo.delete_accounts(tokens)
|
||||
logger.info("Admin delete: {} accounts affected", result.deleted)
|
||||
return result
|
||||
|
||||
async def patch(self, patches: list[AccountPatch]) -> AccountMutationResult:
|
||||
result = await self._repo.patch_accounts(patches)
|
||||
logger.info("Admin patch: {} accounts affected", result.patched)
|
||||
return result
|
||||
|
||||
async def replace_pool(self, command: BulkReplacePoolCommand) -> AccountMutationResult:
|
||||
result = await self._repo.replace_pool(command)
|
||||
logger.info(
|
||||
"Admin replace_pool({}): upserted={} deleted={}",
|
||||
command.pool, result.upserted, result.deleted,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class ProxyAdminService:
|
||||
"""High-level proxy administration operations."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._directory = None
|
||||
|
||||
async def _get_directory(self):
|
||||
if self._directory is None:
|
||||
from app.control.proxy import get_proxy_directory
|
||||
self._directory = await get_proxy_directory()
|
||||
return self._directory
|
||||
|
||||
async def status(self) -> dict[str, Any]:
|
||||
"""Return current proxy status summary."""
|
||||
d = await self._get_directory()
|
||||
return {
|
||||
"egress_mode": d.egress_mode.value,
|
||||
"clearance_mode": d.clearance_mode.value,
|
||||
"node_count": d.node_count,
|
||||
}
|
||||
|
||||
async def reload(self) -> dict[str, Any]:
|
||||
"""Reload proxy configuration."""
|
||||
d = await self._get_directory()
|
||||
await d.load()
|
||||
logger.info("Admin proxy reload complete")
|
||||
return await self.status()
|
||||
|
||||
|
||||
__all__ = ["AccountAdminService", "ProxyAdminService"]
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Control-plane model enumerations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import IntEnum, IntFlag
|
||||
|
||||
|
||||
@@ -14,6 +12,7 @@ class ModeId(IntEnum):
|
||||
AUTO = 0 # modeId="auto"
|
||||
FAST = 1 # modeId="fast"
|
||||
EXPERT = 2 # modeId="expert"
|
||||
HEAVY = 3 # modeId="heavy" — only available on heavy-pool accounts
|
||||
|
||||
def to_api_str(self) -> str:
|
||||
return self.name.lower()
|
||||
@@ -24,6 +23,7 @@ class Tier(IntEnum):
|
||||
|
||||
BASIC = 0 # pool="basic"
|
||||
SUPER = 1 # pool="super"
|
||||
HEAVY = 2 # pool="heavy"
|
||||
|
||||
|
||||
class Capability(IntFlag):
|
||||
@@ -42,8 +42,10 @@ MODE_STRINGS: dict[ModeId, str] = {
|
||||
ModeId.AUTO: "auto",
|
||||
ModeId.FAST: "fast",
|
||||
ModeId.EXPERT: "expert",
|
||||
ModeId.HEAVY: "heavy",
|
||||
}
|
||||
|
||||
ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT)
|
||||
ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT)
|
||||
ALL_MODES_WITH_HEAVY: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT, ModeId.HEAVY)
|
||||
|
||||
__all__ = ["ModeId", "Tier", "Capability", "MODE_STRINGS", "ALL_MODES"]
|
||||
__all__ = ["ModeId", "Tier", "Capability", "MODE_STRINGS", "ALL_MODES", "ALL_MODES_WITH_HEAVY"]
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Model registry — all supported model variants defined in one place."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .enums import Capability, ModeId, Tier
|
||||
from .spec import ModelSpec
|
||||
|
||||
@@ -11,21 +9,28 @@ from .spec import ModelSpec
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MODELS: tuple[ModelSpec, ...] = (
|
||||
# ── Basic · Chat ────────────────────────────────────────────────────────
|
||||
ModelSpec("grok-3", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 3"),
|
||||
ModelSpec("grok-3-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 3 Fast"),
|
||||
ModelSpec("grok-3-expert", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 3 Expert"),
|
||||
ModelSpec("grok-4", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 4"),
|
||||
ModelSpec("grok-4-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4 Fast"),
|
||||
ModelSpec("grok-4-expert", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 4 Expert"),
|
||||
# ── Super · Chat ────────────────────────────────────────────────────────
|
||||
ModelSpec("grok-4-heavy", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4 Heavy"),
|
||||
# ── Basic · Image ───────────────────────────────────────────────────────
|
||||
ModelSpec("grok-image", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Image"),
|
||||
ModelSpec("grok-image-fast", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Image Fast"),
|
||||
ModelSpec("grok-image-edit", ModeId.FAST, Tier.BASIC, Capability.IMAGE_EDIT, True, "Grok Image Edit"),
|
||||
# ── Basic · Video ───────────────────────────────────────────────────────
|
||||
ModelSpec("grok-video", ModeId.FAST, Tier.BASIC, Capability.VIDEO, True, "Grok Video"),
|
||||
# === Chat ==============================================================
|
||||
# Basic
|
||||
ModelSpec("grok-4.20-0309", ModeId.AUTO, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309"),
|
||||
ModelSpec("grok-4.20-0309-non-reasoning", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309-non-reasoning"),
|
||||
ModelSpec("grok-4.20-0309-reasoning", ModeId.EXPERT, Tier.BASIC, Capability.CHAT, True, "Grok 4.20-0309-reasoning"),
|
||||
# Heavy
|
||||
ModelSpec("grok-4.20-multi-agent-0309", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20-multi-agent-0309"),
|
||||
|
||||
# === Image ==============================================================
|
||||
# Basic
|
||||
ModelSpec("grok-imagine-image-lite", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Imagine Image Lite"),
|
||||
# Super
|
||||
ModelSpec("grok-imagine-image", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image"),
|
||||
ModelSpec("grok-imagine-image-pro", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image Pro"),
|
||||
|
||||
# === Image Edit =========================================================
|
||||
# Super
|
||||
ModelSpec("grok-imagine-image-edit", ModeId.AUTO, Tier.SUPER, Capability.IMAGE_EDIT, True, "Grok Imagine Image Edit"),
|
||||
|
||||
# === Video ==============================================================
|
||||
# Super
|
||||
ModelSpec("grok-imagine-video", ModeId.AUTO, Tier.SUPER, Capability.VIDEO, True, "Grok Imagine Video"),
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""ModelSpec — the single source of truth for model metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .enums import Capability, ModeId, Tier
|
||||
@@ -35,12 +33,26 @@ class ModelSpec:
|
||||
def is_voice(self) -> bool: return bool(self.capability & Capability.VOICE)
|
||||
|
||||
def pool_name(self) -> str:
|
||||
"""Return the pool string expected by the account selector."""
|
||||
return "super" if self.tier == Tier.SUPER else "basic"
|
||||
"""Return the canonical pool string for this tier."""
|
||||
if self.tier == Tier.SUPER: return "super"
|
||||
if self.tier == Tier.HEAVY: return "heavy"
|
||||
return "basic"
|
||||
|
||||
def pool_id(self) -> int:
|
||||
"""Return the integer PoolId for the dataplane account table."""
|
||||
return int(self.tier)
|
||||
|
||||
def pool_candidates(self) -> tuple[int, ...]:
|
||||
"""Return pool IDs to try in priority order.
|
||||
|
||||
A higher-tier account can always serve a lower-tier model:
|
||||
BASIC tier → try basic first, then super, then heavy
|
||||
SUPER tier → try super first, then heavy
|
||||
HEAVY tier → heavy only
|
||||
"""
|
||||
if self.tier == Tier.BASIC: return (0, 1, 2) # basic, super, heavy
|
||||
if self.tier == Tier.SUPER: return (1, 2) # super, heavy
|
||||
return (2,) # heavy only
|
||||
|
||||
|
||||
__all__ = ["ModelSpec"]
|
||||
@@ -5,8 +5,6 @@ Selection delegates to the dataplane ProxyTable; this module owns
|
||||
configuration loading and clearance refresh lifecycle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Sequence
|
||||
|
||||
@@ -30,11 +28,12 @@ class ProxyDirectory:
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._nodes: list[EgressNode] = []
|
||||
self._bundles: dict[str, ClearanceBundle] = {} # affinity_key → bundle
|
||||
self._lock = asyncio.Lock()
|
||||
self._manual = ManualClearanceProvider()
|
||||
self._flare = FlareSolverrClearanceProvider()
|
||||
self._nodes: list[EgressNode] = []
|
||||
self._resource_nodes: list[EgressNode] = [] # for media downloads
|
||||
self._bundles: dict[str, ClearanceBundle] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._manual = ManualClearanceProvider()
|
||||
self._flare = FlareSolverrClearanceProvider()
|
||||
self._egress_mode: EgressMode = EgressMode.DIRECT
|
||||
self._clearance_mode: ClearanceMode = ClearanceMode.NONE
|
||||
|
||||
@@ -48,20 +47,28 @@ class ProxyDirectory:
|
||||
self._egress_mode = EgressMode(cfg.get_str("proxy.egress.mode", "direct"))
|
||||
self._clearance_mode = ClearanceMode(cfg.get_str("proxy.clearance.mode", "none"))
|
||||
|
||||
nodes: list[EgressNode] = []
|
||||
nodes: list[EgressNode] = []
|
||||
resource_nodes: list[EgressNode] = []
|
||||
|
||||
if self._egress_mode == EgressMode.SINGLE_PROXY:
|
||||
url = cfg.get_str("proxy.egress.proxy_url", "")
|
||||
if url:
|
||||
nodes.append(EgressNode(node_id="single", proxy_url=url))
|
||||
base_url = cfg.get_str("proxy.egress.proxy_url", "")
|
||||
res_url = cfg.get_str("proxy.egress.resource_proxy_url", "")
|
||||
if base_url:
|
||||
nodes.append(EgressNode(node_id="single", proxy_url=base_url))
|
||||
if res_url:
|
||||
resource_nodes.append(EgressNode(node_id="res-single", proxy_url=res_url))
|
||||
|
||||
elif self._egress_mode == EgressMode.PROXY_POOL:
|
||||
urls: list[str] = cfg.get_list("proxy.egress.proxy_pool", [])
|
||||
for i, url in enumerate(urls):
|
||||
base_pool: list[str] = cfg.get_list("proxy.egress.proxy_pool", [])
|
||||
res_pool: list[str] = cfg.get_list("proxy.egress.resource_proxy_pool", [])
|
||||
for i, url in enumerate(base_pool):
|
||||
nodes.append(EgressNode(node_id=f"pool-{i}", proxy_url=url))
|
||||
for i, url in enumerate(res_pool):
|
||||
resource_nodes.append(EgressNode(node_id=f"res-pool-{i}", proxy_url=url))
|
||||
|
||||
async with self._lock:
|
||||
self._nodes = nodes
|
||||
self._nodes = nodes
|
||||
self._resource_nodes = resource_nodes
|
||||
|
||||
logger.info(
|
||||
"ProxyDirectory loaded: egress={} clearance={} nodes={}",
|
||||
@@ -75,14 +82,15 @@ class ProxyDirectory:
|
||||
async def acquire(
|
||||
self,
|
||||
*,
|
||||
scope: ProxyScope = ProxyScope.APP,
|
||||
kind: RequestKind = RequestKind.HTTP,
|
||||
scope: ProxyScope = ProxyScope.APP,
|
||||
kind: RequestKind = RequestKind.HTTP,
|
||||
resource: bool = False,
|
||||
) -> ProxyLease:
|
||||
"""Return a ProxyLease for the next request.
|
||||
|
||||
For DIRECT mode, returns a lease with no proxy or clearance.
|
||||
"""
|
||||
proxy_url = await self._pick_proxy_url()
|
||||
proxy_url = await self._pick_proxy_url(resource=resource)
|
||||
affinity = proxy_url or "direct"
|
||||
|
||||
bundle = await self._get_or_build_bundle(affinity_key=affinity, proxy_url=proxy_url or "")
|
||||
@@ -117,20 +125,19 @@ class ProxyDirectory:
|
||||
# Internal
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _pick_proxy_url(self) -> str | None:
|
||||
async def _pick_proxy_url(self, resource: bool = False) -> str | None:
|
||||
if self._egress_mode == EgressMode.DIRECT:
|
||||
return None
|
||||
if self._egress_mode == EgressMode.SINGLE_PROXY:
|
||||
async with self._lock:
|
||||
if self._nodes:
|
||||
return self._nodes[0].proxy_url
|
||||
return None
|
||||
# PROXY_POOL: round-robin by inflight count (minimal implementation).
|
||||
async with self._lock:
|
||||
if not self._nodes:
|
||||
# Prefer resource-specific nodes when available; fall back to base nodes.
|
||||
nodes = (self._resource_nodes if resource and self._resource_nodes
|
||||
else self._nodes)
|
||||
if not nodes:
|
||||
return None
|
||||
node = min(self._nodes, key=lambda n: n.inflight)
|
||||
return node.proxy_url
|
||||
if self._egress_mode == EgressMode.SINGLE_PROXY:
|
||||
return nodes[0].proxy_url
|
||||
# PROXY_POOL: pick least-inflight node.
|
||||
return min(nodes, key=lambda n: n.inflight).proxy_url
|
||||
|
||||
async def _get_or_build_bundle(
|
||||
self,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Classify upstream HTTP responses into proxy feedback categories."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .models import ProxyFeedback, ProxyFeedbackKind
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Control-plane proxy domain models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import IntEnum, StrEnum
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""FlareSolverr-backed managed clearance provider."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Manual clearance provider — uses operator-supplied cookies directly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.platform.config.snapshot import get_config
|
||||
from ..models import ClearanceBundle, ClearanceMode
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ Periodically refreshes ClearanceBundles for managed (FlareSolverr) mode.
|
||||
Previously inline in ProxyDirectory; extracted for separation of concerns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
|
||||
@@ -5,8 +5,6 @@ Bootstrap loads a full snapshot; incremental sync applies revision-based
|
||||
changesets without holding the selection lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -80,7 +78,7 @@ class AccountDirectory:
|
||||
|
||||
async def reserve(
|
||||
self,
|
||||
pool_id: int,
|
||||
pool_candidates: tuple[int, ...] | int,
|
||||
mode_id: int,
|
||||
*,
|
||||
exclude_tokens: list[str] | None = None,
|
||||
@@ -89,12 +87,18 @@ class AccountDirectory:
|
||||
) -> AccountLease | None:
|
||||
"""Select and reserve the best available account slot.
|
||||
|
||||
``pool_candidates`` is tried in order; the first pool with an available
|
||||
account wins. A plain ``int`` is accepted for backward compatibility.
|
||||
|
||||
Returns an AccountLease, or None if no account is available.
|
||||
"""
|
||||
table = self._table
|
||||
if table is None:
|
||||
return None
|
||||
|
||||
pools: tuple[int, ...] = (
|
||||
(pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates
|
||||
)
|
||||
ts = now_s_override if now_s_override is not None else now_s()
|
||||
|
||||
# Resolve exclude set (O(n) once, before lock).
|
||||
@@ -112,25 +116,31 @@ class AccountDirectory:
|
||||
prefer_tag_idxs = set().union(*sets)
|
||||
|
||||
async with self._lock:
|
||||
idx = select(
|
||||
table,
|
||||
pool_id,
|
||||
mode_id,
|
||||
exclude_idxs = exclude_idxs,
|
||||
prefer_tag_idxs = prefer_tag_idxs,
|
||||
now_s = ts,
|
||||
)
|
||||
idx: int | None = None
|
||||
for pool_id in pools:
|
||||
idx = select(
|
||||
table,
|
||||
pool_id,
|
||||
mode_id,
|
||||
exclude_idxs = exclude_idxs,
|
||||
prefer_tag_idxs = prefer_tag_idxs,
|
||||
now_s = ts,
|
||||
)
|
||||
if idx is not None:
|
||||
break
|
||||
|
||||
if idx is None:
|
||||
return None
|
||||
|
||||
fb.increment_inflight(table, idx)
|
||||
fb.update_last_use(table, idx, ts)
|
||||
token = table.get_token(idx)
|
||||
token = table.get_token(idx)
|
||||
actual_pool = table.get_pool_id(idx)
|
||||
|
||||
return new_lease(
|
||||
idx = idx,
|
||||
token = token,
|
||||
pool_id = pool_id,
|
||||
pool_id = actual_pool,
|
||||
mode_id = mode_id,
|
||||
selected_at = ts,
|
||||
)
|
||||
|
||||
@@ -4,9 +4,7 @@ The caller (AccountDirectory) is responsible for holding the state lock
|
||||
before calling these functions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ..shared.enums import StatusId
|
||||
from ..shared.enums import ALL_MODE_IDS, StatusId
|
||||
from .table import AccountRuntimeTable
|
||||
|
||||
# Health adjustment constants.
|
||||
@@ -68,13 +66,13 @@ def apply_status_change(table: AccountRuntimeTable, idx: int, new_status_id: int
|
||||
|
||||
if new_status_id != int(StatusId.ACTIVE):
|
||||
# Remove from all mode availability buckets.
|
||||
for mode_id in (0, 1, 2):
|
||||
for mode_id in ALL_MODE_IDS:
|
||||
bucket = table.mode_available.get((pool_id, mode_id))
|
||||
if bucket:
|
||||
bucket.discard(idx)
|
||||
else:
|
||||
# Re-add to mode buckets where quota > 0.
|
||||
for mode_id in (0, 1, 2):
|
||||
for mode_id in ALL_MODE_IDS:
|
||||
if int(table._quota_col(mode_id)[idx]) > 0:
|
||||
table.mode_available.setdefault((pool_id, mode_id), set()).add(idx)
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""AccountLease — minimal hot-path rental object."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.platform.runtime.ids import next_id
|
||||
|
||||
@@ -5,9 +5,7 @@ overhead. The caller provides the frozen set of excluded indices and
|
||||
pre-resolved tag index set.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ..shared.enums import StatusId
|
||||
from ..shared.enums import PoolId, StatusId
|
||||
from .table import AccountRuntimeTable
|
||||
|
||||
# Scoring weights — tuned for throughput/fairness balance.
|
||||
@@ -65,7 +63,14 @@ def _maybe_reset_windows(
|
||||
pool_id: int,
|
||||
now_s: int,
|
||||
) -> None:
|
||||
"""Reset expired windows for basic-pool accounts (no API call required)."""
|
||||
"""Reset expired windows for basic-pool accounts (no API call required).
|
||||
|
||||
Only applies to the basic pool — super/heavy quotas are managed exclusively
|
||||
by the periodic refresh service and must not be reset inline.
|
||||
"""
|
||||
if pool_id != int(PoolId.BASIC):
|
||||
return
|
||||
|
||||
from app.control.account.quota_defaults import BASIC_QUOTA_DEFAULTS
|
||||
|
||||
defaults = BASIC_QUOTA_DEFAULTS.get(mode_id)
|
||||
|
||||
@@ -5,8 +5,6 @@ Two modes:
|
||||
incremental — revision-based change scan at runtime.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
@@ -30,15 +28,18 @@ def _record_to_slot_args(record: AccountRecord) -> dict:
|
||||
return 0
|
||||
return int(ms_to_s(window.reset_at))
|
||||
|
||||
heavy_w = qs.heavy
|
||||
return dict(
|
||||
pool_id = pool_id,
|
||||
status_id = status_id,
|
||||
quota_auto = max(0, qs.auto.remaining),
|
||||
quota_fast = max(0, qs.fast.remaining),
|
||||
quota_expert = max(0, qs.expert.remaining),
|
||||
quota_heavy = max(0, heavy_w.remaining) if heavy_w is not None else -1,
|
||||
reset_auto = _reset_s(qs.auto),
|
||||
reset_fast = _reset_s(qs.fast),
|
||||
reset_expert = _reset_s(qs.expert),
|
||||
reset_heavy = _reset_s(heavy_w) if heavy_w is not None else 0,
|
||||
health = 1.0,
|
||||
last_use_s = ms_to_s(record.last_use_at) if record.last_use_at else 0,
|
||||
last_fail_s = ms_to_s(record.last_fail_at) if record.last_fail_at else 0,
|
||||
|
||||
@@ -8,8 +8,6 @@ All quota, status, health, and counter fields are stored as typed
|
||||
``array.array`` columns indexed by a compact integer slot index.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterator
|
||||
@@ -25,8 +23,8 @@ from ..shared.enums import ALL_MODE_IDS, POOL_STR_TO_ID, STATUS_STR_TO_ID, PoolI
|
||||
# 'L' uint32 — epoch-second timestamps (valid until year 2106)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_QUOTA_COLS = ("quota_auto", "quota_fast", "quota_expert")
|
||||
_RESET_COLS = ("reset_auto", "reset_fast", "reset_expert")
|
||||
_QUOTA_COLS = ("quota_auto", "quota_fast", "quota_expert", "quota_heavy")
|
||||
_RESET_COLS = ("reset_auto", "reset_fast", "reset_expert", "reset_heavy")
|
||||
_INFLIGHT_CAP = 32_767 # avoid int16 overflow on quota
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -55,11 +53,13 @@ class AccountRuntimeTable:
|
||||
quota_auto_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h"))
|
||||
quota_fast_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h"))
|
||||
quota_expert_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h"))
|
||||
quota_heavy_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("h"))
|
||||
|
||||
# --- Window reset timestamps (uint32 epoch-seconds; 0 = unknown) ---
|
||||
reset_auto_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L"))
|
||||
reset_fast_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L"))
|
||||
reset_expert_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L"))
|
||||
reset_heavy_at_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("L"))
|
||||
|
||||
# --- Runtime counters (uint16) ---
|
||||
inflight_by_idx: "array.array[int]" = field(default_factory=lambda: array.array("H"))
|
||||
@@ -89,12 +89,14 @@ class AccountRuntimeTable:
|
||||
def _quota_col(self, mode_id: int) -> "array.array[int]":
|
||||
if mode_id == 0: return self.quota_auto_by_idx
|
||||
if mode_id == 1: return self.quota_fast_by_idx
|
||||
return self.quota_expert_by_idx
|
||||
if mode_id == 2: return self.quota_expert_by_idx
|
||||
return self.quota_heavy_by_idx
|
||||
|
||||
def _reset_col(self, mode_id: int) -> "array.array[int]":
|
||||
if mode_id == 0: return self.reset_auto_at_by_idx
|
||||
if mode_id == 1: return self.reset_fast_at_by_idx
|
||||
return self.reset_expert_at_by_idx
|
||||
if mode_id == 2: return self.reset_expert_at_by_idx
|
||||
return self.reset_heavy_at_by_idx
|
||||
|
||||
def _add_to_indexes(self, idx: int) -> None:
|
||||
pool_id = int(self.pool_by_idx[idx])
|
||||
@@ -128,20 +130,22 @@ class AccountRuntimeTable:
|
||||
|
||||
def _append_slot(
|
||||
self,
|
||||
token: str,
|
||||
pool_id: int,
|
||||
status_id: int,
|
||||
quota_auto: int,
|
||||
quota_fast: int,
|
||||
token: str,
|
||||
pool_id: int,
|
||||
status_id: int,
|
||||
quota_auto: int,
|
||||
quota_fast: int,
|
||||
quota_expert: int,
|
||||
reset_auto: int,
|
||||
reset_fast: int,
|
||||
quota_heavy: int,
|
||||
reset_auto: int,
|
||||
reset_fast: int,
|
||||
reset_expert: int,
|
||||
health: float,
|
||||
last_use_s: int,
|
||||
last_fail_s: int,
|
||||
fail_count: int,
|
||||
tags: list[str],
|
||||
reset_heavy: int,
|
||||
health: float,
|
||||
last_use_s: int,
|
||||
last_fail_s: int,
|
||||
fail_count: int,
|
||||
tags: list[str],
|
||||
) -> int:
|
||||
idx = len(self.token_by_idx)
|
||||
self.token_by_idx.append(token)
|
||||
@@ -151,9 +155,11 @@ class AccountRuntimeTable:
|
||||
self.quota_auto_by_idx.append(max(-1, min(quota_auto, 32767)))
|
||||
self.quota_fast_by_idx.append(max(-1, min(quota_fast, 32767)))
|
||||
self.quota_expert_by_idx.append(max(-1, min(quota_expert, 32767)))
|
||||
self.quota_heavy_by_idx.append(max(-1, min(quota_heavy, 32767)))
|
||||
self.reset_auto_at_by_idx.append(reset_auto)
|
||||
self.reset_fast_at_by_idx.append(reset_fast)
|
||||
self.reset_expert_at_by_idx.append(reset_expert)
|
||||
self.reset_heavy_at_by_idx.append(reset_heavy)
|
||||
self.inflight_by_idx.append(0)
|
||||
self.fail_count_by_idx.append(min(fail_count, 65535))
|
||||
self.health_by_idx.append(health)
|
||||
@@ -170,36 +176,40 @@ class AccountRuntimeTable:
|
||||
|
||||
def _update_slot(
|
||||
self,
|
||||
idx: int,
|
||||
pool_id: int,
|
||||
status_id: int,
|
||||
quota_auto: int,
|
||||
quota_fast: int,
|
||||
idx: int,
|
||||
pool_id: int,
|
||||
status_id: int,
|
||||
quota_auto: int,
|
||||
quota_fast: int,
|
||||
quota_expert: int,
|
||||
reset_auto: int,
|
||||
reset_fast: int,
|
||||
quota_heavy: int,
|
||||
reset_auto: int,
|
||||
reset_fast: int,
|
||||
reset_expert: int,
|
||||
health: float,
|
||||
last_use_s: int,
|
||||
last_fail_s: int,
|
||||
fail_count: int,
|
||||
old_tags: list[str],
|
||||
new_tags: list[str],
|
||||
reset_heavy: int,
|
||||
health: float,
|
||||
last_use_s: int,
|
||||
last_fail_s: int,
|
||||
fail_count: int,
|
||||
old_tags: list[str],
|
||||
new_tags: list[str],
|
||||
) -> None:
|
||||
self._remove_from_indexes(idx)
|
||||
self._remove_from_tag_idx(idx, old_tags)
|
||||
|
||||
self.pool_by_idx[idx] = pool_id
|
||||
self.status_by_idx[idx] = status_id
|
||||
self.quota_auto_by_idx[idx] = max(-1, min(quota_auto, 32767))
|
||||
self.quota_fast_by_idx[idx] = max(-1, min(quota_fast, 32767))
|
||||
self.quota_expert_by_idx[idx] = max(-1, min(quota_expert, 32767))
|
||||
self.reset_auto_at_by_idx[idx] = reset_auto
|
||||
self.reset_fast_at_by_idx[idx] = reset_fast
|
||||
self.reset_expert_at_by_idx[idx] = reset_expert
|
||||
self.fail_count_by_idx[idx] = min(fail_count, 65535)
|
||||
self.last_use_at_by_idx[idx] = last_use_s
|
||||
self.last_fail_at_by_idx[idx] = last_fail_s
|
||||
self.pool_by_idx[idx] = pool_id
|
||||
self.status_by_idx[idx] = status_id
|
||||
self.quota_auto_by_idx[idx] = max(-1, min(quota_auto, 32767))
|
||||
self.quota_fast_by_idx[idx] = max(-1, min(quota_fast, 32767))
|
||||
self.quota_expert_by_idx[idx] = max(-1, min(quota_expert, 32767))
|
||||
self.quota_heavy_by_idx[idx] = max(-1, min(quota_heavy, 32767))
|
||||
self.reset_auto_at_by_idx[idx] = reset_auto
|
||||
self.reset_fast_at_by_idx[idx] = reset_fast
|
||||
self.reset_expert_at_by_idx[idx] = reset_expert
|
||||
self.reset_heavy_at_by_idx[idx] = reset_heavy
|
||||
self.fail_count_by_idx[idx] = min(fail_count, 65535)
|
||||
self.last_use_at_by_idx[idx] = last_use_s
|
||||
self.last_fail_at_by_idx[idx] = last_fail_s
|
||||
# health is not reset on update
|
||||
|
||||
self._add_to_indexes(idx)
|
||||
|
||||
@@ -5,8 +5,6 @@ Kept as a thin shim so callers in the dataplane need not import control
|
||||
modules directly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.control.proxy import ProxyDirectory, get_proxy_directory
|
||||
from app.control.proxy.models import (
|
||||
ProxyLease, ProxyFeedback, ProxyScope, RequestKind,
|
||||
@@ -22,10 +20,11 @@ class ProxyRuntime:
|
||||
async def acquire(
|
||||
self,
|
||||
*,
|
||||
scope: ProxyScope = ProxyScope.APP,
|
||||
kind: RequestKind = RequestKind.HTTP,
|
||||
scope: ProxyScope = ProxyScope.APP,
|
||||
kind: RequestKind = RequestKind.HTTP,
|
||||
resource: bool = False,
|
||||
) -> ProxyLease:
|
||||
return await self._dir.acquire(scope=scope, kind=kind)
|
||||
return await self._dir.acquire(scope=scope, kind=kind, resource=resource)
|
||||
|
||||
async def feedback(self, lease: ProxyLease, result: ProxyFeedback) -> None:
|
||||
await self._dir.feedback(lease, result)
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
All values are sanitized to ASCII-safe Latin-1 before use.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import random
|
||||
import re
|
||||
@@ -49,7 +47,7 @@ def _sanitize(value: Optional[str], *, field: str, strip_spaces: bool = False) -
|
||||
|
||||
def _statsig_id() -> str:
|
||||
cfg = get_config()
|
||||
if cfg.get_bool("app.dynamic_statsig", False):
|
||||
if cfg.get_bool("features.dynamic_statsig", False):
|
||||
if random.choice((True, False)):
|
||||
rand = "".join(random.choices(string.ascii_lowercase + string.digits, k=5))
|
||||
msg = f"e:TypeError: Cannot read properties of null (reading 'children['{rand}']')"
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""curl_cffi session builder for reverse-proxy requests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
@@ -24,7 +22,10 @@ def _resolve_browser(lease: ProxyLease | None) -> str:
|
||||
def _skip_proxy_ssl(proxy_url: str) -> bool:
|
||||
if not proxy_url:
|
||||
return False
|
||||
return get_config().get_bool("proxy.skip_proxy_ssl_verify", False)
|
||||
cfg = get_config()
|
||||
# New key; fall back to old key for backward compatibility.
|
||||
return cfg.get_bool("proxy.egress.skip_ssl_verify",
|
||||
cfg.get_bool("proxy.skip_proxy_ssl_verify", False))
|
||||
|
||||
|
||||
def normalize_proxy_url(url: str) -> str:
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
Extracted from ProxyDirectory.acquire() to formalize the dataplane separation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.control.proxy.models import (
|
||||
EgressMode, EgressNode, EgressNodeState,
|
||||
ProxyScope, RequestKind,
|
||||
|
||||
@@ -5,8 +5,6 @@ dataplane/control-plane boundary. The control-plane ProxyDirectory owns
|
||||
mutation; this module provides a read-only snapshot for selector logic.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from app.control.proxy.models import (
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
Maps upstream HTTP status codes and response bodies to a ResultCategory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .types import ResultCategory
|
||||
|
||||
@@ -7,8 +7,6 @@ directly continues to work; the executor wraps the same pattern with
|
||||
structured feedback and classification.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
@@ -57,7 +55,7 @@ async def execute(
|
||||
# Step 2: Acquire account
|
||||
directory = await get_account_directory()
|
||||
|
||||
lease = await directory.reserve(plan.pool_id, plan.mode_id)
|
||||
lease = await directory.reserve(plan.pool_candidates, plan.mode_id)
|
||||
if lease is None:
|
||||
return ReverseResult(
|
||||
category=ResultCategory.RATE_LIMITED,
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
Called after every upstream call to update account health/quota and proxy state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.control.account.commands import AccountPatch
|
||||
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind
|
||||
from app.platform.runtime.clock import now_ms
|
||||
|
||||
@@ -4,8 +4,6 @@ Determines the endpoint URL, transport kind, pool/mode IDs, and timeout
|
||||
for a given operation. Does NOT execute anything — pure data transform.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.control.model.spec import ModelSpec
|
||||
@@ -41,12 +39,12 @@ def build_plan(spec: ModelSpec, request: dict[str, Any] | None = None) -> Revers
|
||||
defaults = _DEFAULTS.get(tkind, _DEFAULTS[TransportKind.HTTP_JSON])
|
||||
|
||||
return ReversePlan(
|
||||
endpoint = endpoint,
|
||||
transport_kind = tkind,
|
||||
pool_id = spec.pool_id(),
|
||||
mode_id = int(spec.mode_id),
|
||||
timeout_s = defaults["timeout_s"],
|
||||
content_type = defaults["content_type"],
|
||||
endpoint = endpoint,
|
||||
transport_kind = tkind,
|
||||
pool_candidates = spec.pool_candidates(),
|
||||
mode_id = int(spec.mode_id),
|
||||
timeout_s = defaults["timeout_s"],
|
||||
content_type = defaults["content_type"],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -8,9 +8,8 @@ URL reference (from production reverse analysis):
|
||||
The app-chat upload endpoint is handled separately in transport/asset_upload.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
import pathlib
|
||||
import urllib.parse
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ASSETS_LIST_URL = "https://grok.com/rest/assets"
|
||||
@@ -21,7 +20,7 @@ ASSETS_DOWNLOAD_BASE = "https://assets.grok.com"
|
||||
APP_CHAT_UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file"
|
||||
|
||||
# MIME type mapping used for download content-type inference.
|
||||
_EXTENSION_MIME: Dict[str, str] = {
|
||||
_EXTENSION_MIME: dict[str, str] = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
@@ -30,10 +29,6 @@ _EXTENSION_MIME: Dict[str, str] = {
|
||||
".webm": "video/webm",
|
||||
}
|
||||
|
||||
import pathlib
|
||||
import urllib.parse
|
||||
|
||||
|
||||
def asset_delete_url(asset_id: str) -> str:
|
||||
return f"{ASSETS_DELETE_URL}/{asset_id}"
|
||||
|
||||
@@ -57,14 +52,30 @@ def resolve_download_url(file_path: str) -> tuple[str, str, str]:
|
||||
return url, origin, f"{origin}/"
|
||||
|
||||
|
||||
def infer_content_type(url: str) -> Optional[str]:
|
||||
def infer_content_type(url: str) -> str | None:
|
||||
"""Return a best-guess MIME type for *url* based on file extension."""
|
||||
path = pathlib.Path(urllib.parse.urlparse(url).path)
|
||||
return _EXTENSION_MIME.get(path.suffix.lower())
|
||||
|
||||
|
||||
def resolve_asset_reference(
|
||||
file_id: str,
|
||||
file_uri: str,
|
||||
*,
|
||||
user_id: str | None = None,
|
||||
) -> str | None:
|
||||
"""Return the absolute asset content URL used by image-edit requests."""
|
||||
if file_uri:
|
||||
url, _, _ = resolve_download_url(file_uri)
|
||||
return url
|
||||
if file_id and user_id:
|
||||
return f"{ASSETS_DOWNLOAD_BASE}/users/{user_id}/{file_id}/content"
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ASSETS_LIST_URL", "ASSETS_DELETE_URL", "ASSETS_DOWNLOAD_BASE",
|
||||
"APP_CHAT_UPLOAD_URL",
|
||||
"asset_delete_url", "resolve_download_url", "infer_content_type",
|
||||
"resolve_asset_reference",
|
||||
]
|
||||
@@ -4,10 +4,9 @@ Each public function handles proxy acquisition, the upstream call, and
|
||||
proxy feedback, returning a simple result or raising ``UpstreamError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import random
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.config.snapshot import get_config
|
||||
@@ -15,9 +14,13 @@ from app.platform.errors import UpstreamError
|
||||
from app.platform.net.grpc import GrpcClient, GrpcStatus
|
||||
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
|
||||
from app.dataplane.proxy import get_proxy_runtime
|
||||
from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs
|
||||
from app.dataplane.reverse.transport.grpc_web import post_grpc_web
|
||||
from app.dataplane.reverse.transport.http import post_json
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Endpoint URLs
|
||||
# ------------------------------------------------------------------
|
||||
@@ -35,11 +38,11 @@ def build_accept_tos_payload() -> bytes:
|
||||
return GrpcClient.encode_payload(b"\x10\x01")
|
||||
|
||||
|
||||
def build_nsfw_mgmt_payload() -> bytes:
|
||||
"""gRPC-Web payload that sets always_show_nsfw_content=true."""
|
||||
def build_nsfw_mgmt_payload(enabled: bool = True) -> bytes:
|
||||
"""gRPC-Web payload that sets always_show_nsfw_content to *enabled*."""
|
||||
name = b"always_show_nsfw_content"
|
||||
inner = b"\x0a" + bytes([len(name)]) + name
|
||||
protobuf = b"\x0a\x02\x10\x01\x12" + bytes([len(inner)]) + inner
|
||||
protobuf = b"\x0a\x02\x10" + (b"\x01" if enabled else b"\x00") + b"\x12" + bytes([len(inner)]) + inner
|
||||
return GrpcClient.encode_payload(protobuf)
|
||||
|
||||
|
||||
@@ -72,59 +75,57 @@ async def _grpc_call(
|
||||
label: str,
|
||||
origin: str = "https://grok.com",
|
||||
referer: str = "https://grok.com/",
|
||||
session: ResettableSession | None = None,
|
||||
lease=None,
|
||||
) -> GrpcStatus:
|
||||
"""Acquire a proxy lease, POST a gRPC-Web frame, report feedback, parse status."""
|
||||
"""POST a gRPC-Web frame and parse the status.
|
||||
|
||||
When *session* and *lease* are both provided the caller manages the proxy
|
||||
lifecycle (no acquire / feedback is done here). This allows multiple calls
|
||||
to share one TCP connection and one proxy lease, avoiding repeated TLS
|
||||
handshakes.
|
||||
|
||||
When called without *session* / *lease* (the default) the function acquires
|
||||
its own lease and manages proxy feedback, preserving the original behaviour.
|
||||
"""
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("nsfw.timeout", 30.0)
|
||||
shared = session is not None and lease is not None
|
||||
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP)
|
||||
if not shared:
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP)
|
||||
|
||||
try:
|
||||
_, trailers = await post_grpc_web(
|
||||
url,
|
||||
token,
|
||||
payload,
|
||||
lease = lease,
|
||||
timeout_s = timeout_s,
|
||||
origin = origin,
|
||||
referer = referer,
|
||||
url, token, payload,
|
||||
lease=lease, timeout_s=timeout_s, origin=origin, referer=referer,
|
||||
session=session,
|
||||
)
|
||||
except UpstreamError as exc:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(
|
||||
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
|
||||
else ProxyFeedbackKind.FORBIDDEN,
|
||||
status_code = exc.status or 502,
|
||||
),
|
||||
)
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(
|
||||
kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
|
||||
else ProxyFeedbackKind.FORBIDDEN,
|
||||
status_code=exc.status or 502,
|
||||
))
|
||||
raise
|
||||
except Exception as exc:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR),
|
||||
)
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
|
||||
raise UpstreamError(f"{label}: transport error: {exc}") from exc
|
||||
|
||||
status = GrpcClient.get_status(trailers)
|
||||
if status.ok or status.code == -1:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200),
|
||||
)
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200))
|
||||
logger.debug("{}: gRPC ok (code={})", label, status.code)
|
||||
else:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(
|
||||
kind = ProxyFeedbackKind.UPSTREAM_5XX,
|
||||
status_code = status.http_equiv,
|
||||
),
|
||||
)
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.UPSTREAM_5XX, status_code=status.http_equiv))
|
||||
raise UpstreamError(
|
||||
f"{label}: gRPC error code={status.code} message={status.message!r}",
|
||||
status = status.http_equiv,
|
||||
status=status.http_equiv,
|
||||
)
|
||||
|
||||
return status
|
||||
@@ -146,66 +147,111 @@ async def accept_tos(token: str) -> GrpcStatus:
|
||||
)
|
||||
|
||||
|
||||
async def enable_nsfw(token: str) -> GrpcStatus:
|
||||
"""Enable always_show_nsfw_content for *token* via gRPC-Web."""
|
||||
async def set_nsfw(token: str, enabled: bool) -> GrpcStatus:
|
||||
"""Set always_show_nsfw_content for *token* via gRPC-Web."""
|
||||
return await _grpc_call(
|
||||
NSFW_MGMT_URL,
|
||||
token,
|
||||
build_nsfw_mgmt_payload(),
|
||||
label = "enable_nsfw",
|
||||
build_nsfw_mgmt_payload(enabled),
|
||||
label = "enable_nsfw" if enabled else "disable_nsfw",
|
||||
origin = "https://grok.com",
|
||||
referer = "https://grok.com/?_s=data",
|
||||
)
|
||||
|
||||
|
||||
async def set_birth_date(token: str) -> dict:
|
||||
"""Post a random adult birth date for *token* via REST."""
|
||||
async def enable_nsfw(token: str) -> GrpcStatus:
|
||||
"""Enable always_show_nsfw_content for *token* via gRPC-Web."""
|
||||
return await set_nsfw(token, True)
|
||||
|
||||
|
||||
async def disable_nsfw(token: str) -> GrpcStatus:
|
||||
"""Disable always_show_nsfw_content for *token* via gRPC-Web."""
|
||||
return await set_nsfw(token, False)
|
||||
|
||||
|
||||
async def set_birth_date(
|
||||
token: str,
|
||||
session: ResettableSession | None = None,
|
||||
lease=None,
|
||||
) -> dict:
|
||||
"""Post a random adult birth date for *token* via REST.
|
||||
|
||||
Accepts optional *session* / *lease* for connection reuse (see ``_grpc_call``).
|
||||
"""
|
||||
import orjson
|
||||
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("nsfw.timeout", 30.0)
|
||||
shared = session is not None and lease is not None
|
||||
|
||||
if not shared:
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP)
|
||||
|
||||
payload = orjson.dumps(build_set_birth_payload())
|
||||
try:
|
||||
result = await post_json(
|
||||
SET_BIRTH_URL, token, payload,
|
||||
lease=lease, timeout_s=timeout_s,
|
||||
origin="https://grok.com", referer="https://grok.com/?_s=data",
|
||||
session=session,
|
||||
)
|
||||
except UpstreamError as exc:
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(
|
||||
kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
|
||||
else ProxyFeedbackKind.FORBIDDEN,
|
||||
status_code=exc.status or 502,
|
||||
))
|
||||
raise
|
||||
except Exception as exc:
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
|
||||
raise UpstreamError(f"set_birth_date: transport error: {exc}") from exc
|
||||
|
||||
if not shared:
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200))
|
||||
logger.debug("set_birth_date: ok")
|
||||
return result
|
||||
|
||||
|
||||
async def nsfw_sequence(token: str) -> None:
|
||||
"""Run set_birth_date → enable_nsfw sharing one session + lease.
|
||||
|
||||
Compared to calling the two functions individually this saves one TCP+TLS
|
||||
handshake per token, which matters in high-concurrency batch scenarios.
|
||||
"""
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("nsfw.timeout", 30.0)
|
||||
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP)
|
||||
|
||||
payload = orjson.dumps(build_set_birth_payload())
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
try:
|
||||
result = await post_json(
|
||||
SET_BIRTH_URL,
|
||||
token,
|
||||
payload,
|
||||
lease = lease,
|
||||
timeout_s = timeout_s,
|
||||
origin = "https://grok.com",
|
||||
referer = "https://grok.com/?_s=home",
|
||||
)
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
await set_birth_date(token, session=session, lease=lease)
|
||||
await _grpc_call(
|
||||
NSFW_MGMT_URL, token, build_nsfw_mgmt_payload(),
|
||||
label="enable_nsfw", origin="https://grok.com", referer="https://grok.com/?_s=data",
|
||||
session=session, lease=lease,
|
||||
)
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200))
|
||||
logger.debug("nsfw_sequence: completed for token={}", token[:8])
|
||||
except UpstreamError as exc:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(
|
||||
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
|
||||
else ProxyFeedbackKind.FORBIDDEN,
|
||||
status_code = exc.status or 502,
|
||||
),
|
||||
)
|
||||
await proxy.feedback(lease, ProxyFeedback(
|
||||
kind=ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
|
||||
else ProxyFeedbackKind.FORBIDDEN,
|
||||
status_code=exc.status or 502,
|
||||
))
|
||||
raise
|
||||
except Exception as exc:
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR),
|
||||
)
|
||||
raise UpstreamError(f"set_birth_date: transport error: {exc}") from exc
|
||||
|
||||
await proxy.feedback(
|
||||
lease,
|
||||
ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200),
|
||||
)
|
||||
logger.debug("set_birth_date: ok")
|
||||
return result
|
||||
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
|
||||
raise UpstreamError(f"nsfw_sequence: transport error: {exc}") from exc
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ACCEPT_TOS_URL", "NSFW_MGMT_URL", "SET_BIRTH_URL",
|
||||
"build_accept_tos_payload", "build_nsfw_mgmt_payload", "build_set_birth_payload",
|
||||
"accept_tos", "enable_nsfw", "set_birth_date",
|
||||
"accept_tos", "set_nsfw", "enable_nsfw", "disable_nsfw", "set_birth_date", "nsfw_sequence",
|
||||
]
|
||||
@@ -1,45 +1,32 @@
|
||||
"""XAI app-chat protocol — payload builder and response line classifier."""
|
||||
|
||||
from __future__ import annotations
|
||||
"""XAI app-chat protocol — payload builder and SSE stream adapter."""
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import orjson
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.config.snapshot import get_config
|
||||
from app.control.model.enums import ModeId
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mode → modeId string map (derived from browser JS reverse)
|
||||
# Applies to SuperGrok multi-agent models that require modeId field.
|
||||
# ---------------------------------------------------------------------------
|
||||
_GROK_MODE_IDS: dict[str, str] = {
|
||||
"MODEL_MODE_FAST": "fast",
|
||||
"MODEL_MODE_EXPERT": "expert",
|
||||
"MODEL_MODE_HEAVY": "heavy",
|
||||
"MODEL_MODE_GROK_420": "expert",
|
||||
"MODEL_MODE_GROK_4_1_THINKING": "expert",
|
||||
"MODEL_MODE_GROK_4_1_MINI_THINKING": "expert",
|
||||
}
|
||||
from app.control.model.enums import ModeId, MODE_STRINGS
|
||||
from app.dataplane.reverse.protocol.xai_chat_reasoning import ReasoningAggregator
|
||||
|
||||
|
||||
def build_chat_payload(
|
||||
*,
|
||||
message: str,
|
||||
model_name: str,
|
||||
model_mode: str | None = None,
|
||||
file_attachments: list[str] = (),
|
||||
tool_overrides: dict[str, Any] | None = None,
|
||||
message: str,
|
||||
mode_id: ModeId,
|
||||
file_attachments: list[str] = (),
|
||||
tool_overrides: dict[str, Any] | None = None,
|
||||
model_config_override: dict[str, Any] | None = None,
|
||||
request_overrides: dict[str, Any] | None = None,
|
||||
request_overrides: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the JSON payload for POST /rest/app-chat/conversations/new."""
|
||||
cfg = get_config()
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"collectionIds": [],
|
||||
"connectors": [],
|
||||
"deviceEnvInfo": {
|
||||
"darkModeEnabled": False,
|
||||
"devicePixelRatio": 2,
|
||||
@@ -48,7 +35,7 @@ def build_chat_payload(
|
||||
"viewportHeight": 1083,
|
||||
"viewportWidth": 2056,
|
||||
},
|
||||
"disableMemory": cfg.get_bool("app.disable_memory", False),
|
||||
"disableMemory": not cfg.get_bool("features.memory", False),
|
||||
"disableSearch": False,
|
||||
"disableSelfHarmShortCircuit": False,
|
||||
"disableTextFollowUps": False,
|
||||
@@ -61,31 +48,24 @@ def build_chat_payload(
|
||||
"imageAttachments": [],
|
||||
"imageGenerationCount": 2,
|
||||
"isAsyncChat": False,
|
||||
"isReasoning": False,
|
||||
"message": message,
|
||||
"modelMode": model_mode,
|
||||
"modelName": model_name,
|
||||
"responseMetadata": {
|
||||
"requestModelDetails": {"modelId": model_name},
|
||||
},
|
||||
"modeId": MODE_STRINGS[mode_id],
|
||||
"responseMetadata": {},
|
||||
"returnImageBytes": False,
|
||||
"returnRawGrokInXaiRequest": False,
|
||||
"searchAllConnectors": False,
|
||||
"sendFinalMetadata": True,
|
||||
"temporary": cfg.get_bool("app.temporary", True),
|
||||
"toolOverrides": tool_overrides or {},
|
||||
"temporary": cfg.get_bool("features.temporary", True),
|
||||
"toolOverrides": tool_overrides or {
|
||||
"gmailSearch": False,
|
||||
"googleCalendarSearch": False,
|
||||
"outlookSearch": False,
|
||||
"outlookCalendarSearch": False,
|
||||
"googleDriveSearch": False,
|
||||
},
|
||||
}
|
||||
|
||||
# For models that expose modeId, prefer it and strip modelName/modelMode
|
||||
# (mirrors browser front-end logic).
|
||||
if model_mode:
|
||||
mode_id = _GROK_MODE_IDS.get(model_mode)
|
||||
if mode_id:
|
||||
payload["modeId"] = mode_id
|
||||
payload.pop("modelName", None)
|
||||
payload.pop("modelMode", None)
|
||||
|
||||
# Optional operator-supplied system instruction.
|
||||
custom = cfg.get_str("app.custom_instruction", "").strip()
|
||||
custom = cfg.get_str("features.custom_instruction", "").strip()
|
||||
if custom:
|
||||
payload["customPersonality"] = custom
|
||||
|
||||
@@ -96,24 +76,27 @@ def build_chat_payload(
|
||||
payload.update({k: v for k, v in request_overrides.items() if v is not None})
|
||||
|
||||
logger.debug(
|
||||
"Chat payload: model={} mode={} msg_len={} files={}",
|
||||
model_name, model_mode, len(message), len(file_attachments),
|
||||
"Chat payload: mode={} msg_len={} files={}",
|
||||
MODE_STRINGS[mode_id], len(message), len(file_attachments),
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Response line parsing
|
||||
# SSE line classification (unchanged)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RESULT_TAG_RE = re.compile(r'"result"\s*:\s*"([^"]*)"')
|
||||
|
||||
|
||||
def classify_line(line: str) -> tuple[str, str]:
|
||||
def classify_line(line: str | bytes) -> tuple[str, str]:
|
||||
"""Return (event_type, data) for a raw SSE line.
|
||||
|
||||
event_type: 'data' | 'error' | 'done' | 'skip'
|
||||
event_type: 'data' | 'done' | 'skip'
|
||||
|
||||
Handles both standard SSE ``data: {...}`` lines and raw JSON lines
|
||||
(upstream sometimes omits the ``data:`` prefix).
|
||||
"""
|
||||
if isinstance(line, bytes):
|
||||
line = line.decode("utf-8", "replace")
|
||||
line = line.strip()
|
||||
if not line:
|
||||
return "skip", ""
|
||||
@@ -124,35 +107,319 @@ def classify_line(line: str) -> tuple[str, str]:
|
||||
return "data", data
|
||||
if line.startswith("event:"):
|
||||
return "skip", ""
|
||||
# Raw JSON line (no "data:" prefix) — treat as data.
|
||||
if line.startswith("{"):
|
||||
return "data", line
|
||||
return "skip", ""
|
||||
|
||||
|
||||
def parse_token(data: str) -> str | None:
|
||||
"""Extract text token from a single SSE data payload."""
|
||||
try:
|
||||
obj = orjson.loads(data)
|
||||
except Exception:
|
||||
return None
|
||||
# ---------------------------------------------------------------------------
|
||||
# FrameEvent — single output event from StreamAdapter.feed()
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
result = obj.get("result")
|
||||
if not result:
|
||||
return None
|
||||
@dataclass(slots=True)
|
||||
class FrameEvent:
|
||||
"""One parsed event produced by StreamAdapter."""
|
||||
|
||||
# Text streaming token.
|
||||
token = result.get("message", {}).get("token")
|
||||
if token is not None:
|
||||
return token
|
||||
kind: str
|
||||
"""Event kind:
|
||||
- ``text`` — cleaned final text token (content = token string)
|
||||
- ``thinking`` — Grok main-model thinking (content = raw token)
|
||||
- ``image`` — generated image final URL (content = full URL, image_id = upstream UUID)
|
||||
- ``image_progress`` — generated image progress (content = percent string, image_id = upstream UUID)
|
||||
- ``soft_stop`` — stream end signal
|
||||
- ``skip`` — filtered frame, do nothing
|
||||
"""
|
||||
content: str = ""
|
||||
image_id: str = ""
|
||||
rollout_id: str = ""
|
||||
message_tag: str = ""
|
||||
message_step_id: int | None = None
|
||||
|
||||
# Complete message fallback.
|
||||
msg = result.get("message", {})
|
||||
if msg.get("finalMetadata"):
|
||||
return None
|
||||
return None
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# StreamAdapter — stateful SSE frame parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_GROK_RENDER_RE = re.compile(
|
||||
r'<grok:render\s+card_id="([^"]+)"\s+card_type="([^"]+)"\s+type="([^"]+)"'
|
||||
r'[^>]*>.*?</grok:render>',
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
_IMAGE_BASE = "https://assets.grok.com/"
|
||||
|
||||
|
||||
class StreamAdapter:
|
||||
"""Parse upstream SSE frames and emit :class:`FrameEvent` objects.
|
||||
|
||||
One instance per HTTP request. Call :meth:`feed` for every ``data:``
|
||||
line; iterate over the returned list of events.
|
||||
"""
|
||||
|
||||
__slots__ = (
|
||||
"_card_cache",
|
||||
"_citation_order",
|
||||
"_citation_map",
|
||||
"_emitted_reasoning_keys",
|
||||
"_reasoning",
|
||||
"thinking_buf",
|
||||
"text_buf",
|
||||
"image_urls",
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._card_cache: dict[str, dict] = {}
|
||||
self._citation_order: list[str] = []
|
||||
self._citation_map: dict[str, int] = {}
|
||||
self._emitted_reasoning_keys: set[str] = set()
|
||||
self._reasoning = ReasoningAggregator()
|
||||
self.thinking_buf: list[str] = []
|
||||
self.text_buf: list[str] = []
|
||||
self.image_urls: list[tuple[str, str]] = [] # [(url, imageUuid), ...]
|
||||
|
||||
def references_suffix(self) -> str:
|
||||
"""Return a stable, language-neutral reference list for collected citations."""
|
||||
if not self._citation_order:
|
||||
return ""
|
||||
lines = [f"[{index}] {url}" for index, url in enumerate(self._citation_order, start=1)]
|
||||
return "\n\n" + "\n".join(lines)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def feed(self, data: str) -> list[FrameEvent]:
|
||||
"""Parse one JSON ``data:`` payload; return 0-N events."""
|
||||
try:
|
||||
obj = orjson.loads(data)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
result = obj.get("result")
|
||||
if not result:
|
||||
return []
|
||||
resp = result.get("response")
|
||||
if not resp:
|
||||
return []
|
||||
|
||||
events: list[FrameEvent] = []
|
||||
|
||||
# ── cache every cardAttachment first ──────────────────────
|
||||
card_raw = resp.get("cardAttachment")
|
||||
if card_raw:
|
||||
events.extend(self._handle_card(card_raw))
|
||||
|
||||
token = resp.get("token")
|
||||
think = resp.get("isThinking")
|
||||
tag = resp.get("messageTag")
|
||||
rollout = resp.get("rolloutId")
|
||||
step_id = resp.get("messageStepId")
|
||||
|
||||
if tag == "tool_usage_card":
|
||||
for line in self._summarize_tool_usage(resp, rollout=rollout, step_id=step_id):
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout=rollout,
|
||||
tag=tag,
|
||||
step_id=step_id,
|
||||
)
|
||||
return events # card events (if any) already added
|
||||
|
||||
# ── raw_function_result ───────────────────────────────────
|
||||
if tag == "raw_function_result":
|
||||
return events
|
||||
|
||||
# ── toolUsageCardId-only follow-up frame ──────────────────
|
||||
if resp.get("toolUsageCardId") and not resp.get("webSearchResults") and not resp.get("codeExecutionResult"):
|
||||
return events
|
||||
|
||||
# ── thinking token ────────────────────────────────────────
|
||||
if token is not None and think is True:
|
||||
for line in self._reasoning.on_thinking(
|
||||
str(token),
|
||||
tag=tag,
|
||||
rollout=rollout,
|
||||
step_id=step_id if isinstance(step_id, int) else None,
|
||||
):
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout=rollout,
|
||||
tag=tag,
|
||||
step_id=step_id,
|
||||
)
|
||||
return events
|
||||
|
||||
# ── final text token (needs cleaning) ─────────────────────
|
||||
if token is not None and think is not True and tag == "final":
|
||||
cleaned = self._clean_token(token)
|
||||
if cleaned:
|
||||
self.text_buf.append(cleaned)
|
||||
events.append(FrameEvent("text", cleaned))
|
||||
return events
|
||||
|
||||
# ── end signals ───────────────────────────────────────────
|
||||
if resp.get("isSoftStop"):
|
||||
self._flush_pending_reasoning(events)
|
||||
events.append(FrameEvent("soft_stop"))
|
||||
return events
|
||||
|
||||
if resp.get("finalMetadata"):
|
||||
self._flush_pending_reasoning(events)
|
||||
events.append(FrameEvent("soft_stop"))
|
||||
return events
|
||||
|
||||
return events
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Card attachment handling
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _handle_card(self, card_raw: dict) -> list[FrameEvent]:
|
||||
"""Cache card data; emit image event on progress=100."""
|
||||
try:
|
||||
jd = orjson.loads(card_raw["jsonData"])
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
card_id = jd.get("id", "")
|
||||
self._card_cache[card_id] = jd
|
||||
|
||||
chunk = jd.get("image_chunk")
|
||||
if chunk:
|
||||
progress = chunk.get("progress")
|
||||
uuid = chunk.get("imageUuid", "")
|
||||
events: list[FrameEvent] = []
|
||||
try:
|
||||
if progress is not None:
|
||||
events.append(FrameEvent("image_progress", str(int(progress)), uuid))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if chunk.get("progress") == 100 and not chunk.get("moderated"):
|
||||
url = _IMAGE_BASE + chunk["imageUrl"]
|
||||
self.image_urls.append((url, uuid))
|
||||
events.append(FrameEvent("image", url, uuid))
|
||||
return events
|
||||
|
||||
return []
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Token cleaning — <grok:render> → markdown
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _clean_token(self, token: str) -> str:
|
||||
if "<grok:render" not in token:
|
||||
return token
|
||||
return _GROK_RENDER_RE.sub(self._render_replace, token)
|
||||
|
||||
def _render_replace(self, m: re.Match) -> str:
|
||||
card_id = m.group(1)
|
||||
render_type = m.group(3)
|
||||
card = self._card_cache.get(card_id)
|
||||
if not card:
|
||||
return ""
|
||||
|
||||
if render_type == "render_searched_image":
|
||||
img = card.get("image", {})
|
||||
title = img.get("title", "image")
|
||||
thumb = img.get("thumbnail") or img.get("original", "")
|
||||
link = img.get("link", "")
|
||||
if link:
|
||||
return f"[]({link})"
|
||||
return f""
|
||||
|
||||
if render_type == "render_generated_image":
|
||||
return "" # actual URL emitted by progress=100 card frame
|
||||
|
||||
if render_type == "render_inline_citation":
|
||||
url = card.get("url", "")
|
||||
if not url:
|
||||
return ""
|
||||
index = self._citation_map.get(url)
|
||||
if index is None:
|
||||
self._citation_order.append(url)
|
||||
index = len(self._citation_order)
|
||||
self._citation_map[url] = index
|
||||
return f" [{index}]"
|
||||
|
||||
return ""
|
||||
|
||||
def _append_reasoning(
|
||||
self,
|
||||
events: list[FrameEvent],
|
||||
line: str,
|
||||
*,
|
||||
rollout: str | None,
|
||||
tag: str | None,
|
||||
step_id: Any,
|
||||
) -> None:
|
||||
text = line.strip()
|
||||
if not text:
|
||||
return
|
||||
|
||||
key = self._normalize_key(text)
|
||||
if key in self._emitted_reasoning_keys:
|
||||
return
|
||||
|
||||
self._emitted_reasoning_keys.add(key)
|
||||
formatted = text if text.endswith("\n") else text + "\n"
|
||||
self.thinking_buf.append(formatted)
|
||||
events.append(FrameEvent(
|
||||
"thinking",
|
||||
formatted,
|
||||
rollout_id=rollout or "",
|
||||
message_tag=tag or "",
|
||||
message_step_id=step_id if isinstance(step_id, int) else None,
|
||||
))
|
||||
|
||||
def _flush_pending_reasoning(self, events: list[FrameEvent]) -> None:
|
||||
for line in self._reasoning.finalize():
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout="",
|
||||
tag="summary",
|
||||
step_id=None,
|
||||
)
|
||||
|
||||
def _summarize_tool_usage(self, resp: dict[str, Any], *, rollout: str | None, step_id: int | None) -> list[str]:
|
||||
card = resp.get("toolUsageCard")
|
||||
if not isinstance(card, dict):
|
||||
return []
|
||||
|
||||
tool_name = ""
|
||||
args: dict[str, Any] = {}
|
||||
for key, value in card.items():
|
||||
if key == "toolUsageCardId" or not isinstance(value, dict):
|
||||
continue
|
||||
tool_name = re.sub(r"(?<!^)([A-Z])", r"_\1", key).lower()
|
||||
raw_args = value.get("args")
|
||||
if isinstance(raw_args, dict):
|
||||
args = raw_args
|
||||
break
|
||||
|
||||
if not tool_name:
|
||||
return []
|
||||
|
||||
return self._reasoning.on_tool_usage(
|
||||
tool_name,
|
||||
args,
|
||||
rollout=rollout,
|
||||
step_id=step_id,
|
||||
)
|
||||
|
||||
def _normalize_key(self, text: str) -> str:
|
||||
lowered = text.lower()
|
||||
lowered = re.sub(r"https?://\S+", "", lowered)
|
||||
lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered)
|
||||
return lowered
|
||||
|
||||
|
||||
__all__ = [
|
||||
"build_chat_payload",
|
||||
"classify_line",
|
||||
"parse_token",
|
||||
"_GROK_MODE_IDS",
|
||||
"FrameEvent",
|
||||
"StreamAdapter",
|
||||
]
|
||||
@@ -0,0 +1,633 @@
|
||||
"""Reasoning normalization and aggregation for XAI app-chat streams."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
_GENERIC_HEADERS = {
|
||||
"",
|
||||
"thinking about your request",
|
||||
}
|
||||
|
||||
_PROGRESSIVE_HINTS = (
|
||||
"正在", "准备", "计划", "查找", "搜索", "浏览", "确认", "核对", "整合", "挖掘", "比对",
|
||||
"checking", "browsing", "verifying", "integrating", "digging", "cross-checking", "searching", "planning",
|
||||
)
|
||||
|
||||
_FINDING_HINTS = (
|
||||
"尚未", "已经", "已", "确认", "表明", "说明", "显示", "主要", "通常", "支持", "出现", "启动",
|
||||
"持续", "提升", "更新", "灰度", "发布", "上线", "多模态", "视觉", "专家", "context", "token",
|
||||
"参数", "每天", "大潮", "小潮", "半日潮", "引力", "周期", "模式", "confirmed", "launched",
|
||||
"released", "rollout", "testing", "native multimodal", "widely believed", "latest",
|
||||
)
|
||||
|
||||
_LOW_VALUE_PREFIXES = (
|
||||
"用户", "user", "i can", "我可以", "我收集", "建议", "need", "需要", "应该", "since instructions",
|
||||
"proposed", "mermaid", "可以用", "我建议",
|
||||
)
|
||||
|
||||
_TRACK_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("latest_updates", ("最新", "latest", "today", "recent", "最近", "update", "news", "本周", "4月", "april")),
|
||||
("release_status", ("release date", "released", "release", "launch", "上线", "发布", "正式发布", "current status")),
|
||||
("gray_rollout", ("灰度", "grayscale", "gray release", "灰度测试", "内测", "rollout")),
|
||||
("official_confirmation", ("official", "官网", "official site", "site:", "platform.deepseek.com", "deepseek.ai")),
|
||||
("ui_modes", ("vision", "视觉", "expert", "专家模式", "fast", "default", "ui", "界面", "mode")),
|
||||
("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")),
|
||||
("specs_architecture", ("specs", "parameters", "architecture", "engram", "mhc", "moe", "context", "benchmarks", "规格", "参数", "架构", "万亿")),
|
||||
("definition_basics", ("定义", "解释", "什么是", "what is", "phenomenon", "现象")),
|
||||
("causes_mechanism", ("成因", "原因", "cause", "causes", "gravity", "引力", "机制")),
|
||||
("categories_types", ("春潮", "小潮", "半日潮", "全日潮", "类型", "分类")),
|
||||
("impacts_applications", ("影响", "应用", "发电", "航运", "生活", "生态")),
|
||||
)
|
||||
|
||||
_ZH_LABELS = {
|
||||
"understanding": "理解问题",
|
||||
"scope": "检索范围",
|
||||
"evidence": "核验与证据",
|
||||
"finding": "关键发现",
|
||||
"latest_updates": "最新动态",
|
||||
"release_status": "发布状态与上线节奏",
|
||||
"gray_rollout": "灰度进展",
|
||||
"official_confirmation": "官方渠道确认",
|
||||
"ui_modes": "Expert / Vision 模式关联",
|
||||
"v4_lite": "V4 Lite 与 Sealion 线索",
|
||||
"specs_architecture": "规格、架构与上下文能力",
|
||||
"definition_basics": "定义与基础解释",
|
||||
"causes_mechanism": "成因与机制",
|
||||
"categories_types": "分类与相关类型",
|
||||
"impacts_applications": "影响与应用",
|
||||
}
|
||||
|
||||
_EN_LABELS = {
|
||||
"understanding": "Understanding",
|
||||
"scope": "Research Scope",
|
||||
"evidence": "Verification",
|
||||
"finding": "Key Findings",
|
||||
"latest_updates": "latest updates",
|
||||
"release_status": "release status and rollout timing",
|
||||
"gray_rollout": "gray rollout progress",
|
||||
"official_confirmation": "official confirmation",
|
||||
"ui_modes": "Expert / Vision mode signals",
|
||||
"v4_lite": "V4 Lite and Sealion clues",
|
||||
"specs_architecture": "specs, architecture, and context capability",
|
||||
"definition_basics": "definition and basic explanation",
|
||||
"causes_mechanism": "causes and mechanism",
|
||||
"categories_types": "categories and related types",
|
||||
"impacts_applications": "impacts and applications",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ReasoningEvent:
|
||||
section: str
|
||||
text: str
|
||||
track: str = ""
|
||||
evidence_level: int = 0
|
||||
dedupe_key: str = ""
|
||||
|
||||
|
||||
class ReasoningAggregator:
|
||||
"""Normalize raw stream fragments into enterprise-style reasoning output."""
|
||||
|
||||
__slots__ = (
|
||||
"_language",
|
||||
"_en_votes",
|
||||
"_zh_votes",
|
||||
"_agent_search_started",
|
||||
"_emitted_keys",
|
||||
"_seen_tracks",
|
||||
"_seen_findings",
|
||||
"_pending_events",
|
||||
"_section_started",
|
||||
"_track_best_level",
|
||||
"_track_emit_counts",
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._language: str | None = None
|
||||
self._en_votes = 0
|
||||
self._zh_votes = 0
|
||||
self._agent_search_started = False
|
||||
self._emitted_keys: set[str] = set()
|
||||
self._seen_tracks: set[str] = set()
|
||||
self._seen_findings: set[str] = set()
|
||||
self._pending_events: list[ReasoningEvent] = []
|
||||
self._section_started: set[str] = set()
|
||||
self._track_best_level: dict[tuple[str, str], int] = {}
|
||||
self._track_emit_counts: dict[tuple[str, str], int] = {}
|
||||
|
||||
def on_thinking(
|
||||
self,
|
||||
token: str,
|
||||
*,
|
||||
tag: str | None,
|
||||
rollout: str | None,
|
||||
step_id: int | None,
|
||||
) -> list[str]:
|
||||
self._observe_language(token)
|
||||
tag_name = str(tag or "").strip()
|
||||
text = str(token or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
if tag_name == "header":
|
||||
event = self._normalize_header(text, step_id=step_id)
|
||||
return self._dispatch(event) if event else []
|
||||
|
||||
if tag_name == "summary":
|
||||
event = self._normalize_summary(text, step_id=step_id)
|
||||
return self._dispatch(event) if event else []
|
||||
|
||||
event = self._normalize_summary(text, step_id=step_id)
|
||||
return self._dispatch(event) if event else []
|
||||
|
||||
def on_tool_usage(
|
||||
self,
|
||||
tool_name: str,
|
||||
args: dict[str, Any],
|
||||
*,
|
||||
rollout: str | None,
|
||||
step_id: int | None,
|
||||
) -> list[str]:
|
||||
lines: list[str] = []
|
||||
self._observe_language(str(args.get("query") or args.get("message") or args.get("instructions") or ""))
|
||||
|
||||
if tool_name == "web_search":
|
||||
query = str(args.get("query") or args.get("q") or "").strip()
|
||||
if not query:
|
||||
return []
|
||||
if str(rollout or "").startswith("Agent") and not self._agent_search_started:
|
||||
self._agent_search_started = True
|
||||
lines.extend(self._dispatch(ReasoningEvent(
|
||||
"scope",
|
||||
self._localized_line("agents_started"),
|
||||
dedupe_key="scope:agents_started",
|
||||
)))
|
||||
track = self._infer_track(query)
|
||||
if not track:
|
||||
return lines
|
||||
lines.extend(self._dispatch(ReasoningEvent(
|
||||
"scope",
|
||||
self._localized_track_line(track),
|
||||
track=track,
|
||||
evidence_level=1,
|
||||
dedupe_key=f"scope:web:{track}",
|
||||
)))
|
||||
return lines
|
||||
|
||||
if tool_name in {"x_search", "x_keyword_search", "x_semantic_search"}:
|
||||
query = str(args.get("query") or "").strip()
|
||||
track = self._infer_track(query)
|
||||
if not track:
|
||||
return []
|
||||
return self._dispatch(ReasoningEvent(
|
||||
"evidence",
|
||||
self._localized_social_line(track),
|
||||
track=track,
|
||||
evidence_level=2,
|
||||
dedupe_key=f"evidence:social:{track}",
|
||||
))
|
||||
|
||||
if tool_name == "browse_page":
|
||||
url = str(args.get("url") or "").strip()
|
||||
source_kind, track = self._classify_page_source(url, args)
|
||||
if not source_kind:
|
||||
return []
|
||||
return self._dispatch(ReasoningEvent(
|
||||
"evidence",
|
||||
self._localized_browse_line(source_kind, track),
|
||||
track=track or source_kind,
|
||||
evidence_level=4 if source_kind in {"official", "product"} else 3,
|
||||
dedupe_key=f"evidence:browse:{source_kind}:{track or ''}",
|
||||
))
|
||||
|
||||
if tool_name in {"search_images", "image_search"}:
|
||||
description = str(args.get("image_description") or args.get("imageDescription") or "").strip()
|
||||
if not description:
|
||||
return []
|
||||
topic = self._classify_image_topic(description)
|
||||
if not topic:
|
||||
return []
|
||||
return self._dispatch(ReasoningEvent(
|
||||
"scope",
|
||||
self._localized_image_line(topic),
|
||||
track="visual_assets",
|
||||
evidence_level=1,
|
||||
dedupe_key=f"scope:image:{topic}",
|
||||
))
|
||||
|
||||
if tool_name == "chatroom_send":
|
||||
message = str(args.get("message") or "").strip()
|
||||
if not message:
|
||||
return []
|
||||
lines = []
|
||||
for section, text, track, level in self._extract_report_events(message):
|
||||
lines.extend(self._dispatch(ReasoningEvent(
|
||||
section,
|
||||
text,
|
||||
track=track,
|
||||
evidence_level=level,
|
||||
dedupe_key=f"{section}:report:{track}:{self._normalize_key(text)}",
|
||||
)))
|
||||
return lines
|
||||
|
||||
if tool_name == "code_execution":
|
||||
return self._dispatch(ReasoningEvent(
|
||||
"evidence",
|
||||
self._localized_line("code_execution"),
|
||||
dedupe_key="evidence:code_execution",
|
||||
))
|
||||
|
||||
return []
|
||||
|
||||
def finalize(self) -> list[str]:
|
||||
if not self._pending_events:
|
||||
return []
|
||||
if self._language is None:
|
||||
self._language = "en" if self._en_votes > 0 and self._zh_votes == 0 else "zh"
|
||||
return self._flush_pending()
|
||||
|
||||
def _normalize_header(self, text: str, *, step_id: int | None) -> ReasoningEvent | None:
|
||||
stripped = text.strip()
|
||||
if stripped.lower() in _GENERIC_HEADERS:
|
||||
return None
|
||||
section = "understanding" if not self._looks_like_verification(stripped) and (step_id or 0) <= 1 else "evidence"
|
||||
return ReasoningEvent(section, self._to_bullet_text(stripped), dedupe_key=f"{section}:header:{self._normalize_key(stripped)}")
|
||||
|
||||
def _normalize_summary(self, text: str, *, step_id: int | None) -> ReasoningEvent | None:
|
||||
summary = text.lstrip("- ").strip()
|
||||
if not summary:
|
||||
return None
|
||||
if summary.startswith(("建议搜索", "正在调用工具搜索")):
|
||||
return None
|
||||
|
||||
track = self._infer_track(summary)
|
||||
if self._looks_like_progress(summary):
|
||||
section = "evidence" if self._looks_like_verification(summary) else "scope"
|
||||
return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=2 if section == "evidence" else 1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}")
|
||||
|
||||
if self._looks_like_finding(summary):
|
||||
if self._is_unconfirmed_signal(summary):
|
||||
return ReasoningEvent("evidence", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"evidence:summary:{self._normalize_key(summary)}")
|
||||
if not self._agent_search_started and (step_id or 0) <= 1:
|
||||
return ReasoningEvent("understanding", self._to_bullet_text(summary), track=track, evidence_level=2, dedupe_key=f"understanding:summary:{self._normalize_key(summary)}")
|
||||
return ReasoningEvent("finding", self._to_bullet_text(summary), track=track, evidence_level=3, dedupe_key=f"finding:summary:{self._normalize_key(summary)}")
|
||||
|
||||
section = "understanding" if (step_id or 0) <= 1 else "scope"
|
||||
return ReasoningEvent(section, self._to_bullet_text(summary), track=track, evidence_level=1, dedupe_key=f"{section}:summary:{self._normalize_key(summary)}")
|
||||
|
||||
def _extract_report_events(self, message: str) -> list[tuple[str, str, str, int]]:
|
||||
parts = re.split(r"(?:\n+|[。!?!?;;]+|\s+-\s+)", message.replace("\\n", "\n"))
|
||||
candidates: list[tuple[int, str]] = []
|
||||
for raw_part in parts:
|
||||
clause = self._clean_report_clause(raw_part)
|
||||
if not clause:
|
||||
continue
|
||||
if self._language == "zh" and not re.search(r"[\u4e00-\u9fff]", clause):
|
||||
continue
|
||||
if self._language == "en" and re.search(r"[\u4e00-\u9fff]", clause):
|
||||
continue
|
||||
score = self._score_report_clause(clause)
|
||||
if score <= 0:
|
||||
continue
|
||||
candidates.append((score, clause))
|
||||
|
||||
candidates.sort(key=lambda item: (-item[0], len(item[1])))
|
||||
results: list[tuple[str, str, str, int]] = []
|
||||
seen_local: set[str] = set()
|
||||
seen_track_counts: dict[tuple[str, str], int] = {}
|
||||
for _, clause in candidates:
|
||||
key = self._normalize_key(clause)
|
||||
if key in seen_local:
|
||||
continue
|
||||
seen_local.add(key)
|
||||
track = self._infer_track(clause)
|
||||
section = "finding" if self._looks_like_finding(clause) else "evidence"
|
||||
if self._is_unconfirmed_signal(clause):
|
||||
section = "evidence"
|
||||
track_key = (section, track or "_")
|
||||
current_track_count = seen_track_counts.get(track_key, 0)
|
||||
max_track_count = 2 if section == "finding" else 1
|
||||
if current_track_count >= max_track_count:
|
||||
continue
|
||||
seen_track_counts[track_key] = current_track_count + 1
|
||||
level = self._infer_evidence_level(clause, default=3 if section == "finding" else 2)
|
||||
results.append((section, self._to_bullet_text(clause), track, level))
|
||||
if len(results) >= 6:
|
||||
break
|
||||
results.sort(key=lambda item: (0 if item[0] == "evidence" else 1, item[2], -item[3]))
|
||||
return results
|
||||
|
||||
def _dispatch(self, event: ReasoningEvent) -> list[str]:
|
||||
if self._language is None:
|
||||
self._pending_events.append(event)
|
||||
if self._zh_votes > 0:
|
||||
self._language = "zh"
|
||||
elif self._en_votes >= 3:
|
||||
self._language = "en"
|
||||
elif len(self._pending_events) < 4:
|
||||
return []
|
||||
else:
|
||||
self._language = "en"
|
||||
return self._flush_pending()
|
||||
|
||||
lines: list[str] = []
|
||||
if self._pending_events:
|
||||
lines.extend(self._flush_pending())
|
||||
lines.extend(self._emit(event))
|
||||
return lines
|
||||
|
||||
def _flush_pending(self) -> list[str]:
|
||||
lines: list[str] = []
|
||||
pending = self._pending_events
|
||||
self._pending_events = []
|
||||
for event in pending:
|
||||
lines.extend(self._emit(event))
|
||||
return lines
|
||||
|
||||
def _emit(self, event: ReasoningEvent) -> list[str]:
|
||||
text = event.text.strip()
|
||||
if not text:
|
||||
return []
|
||||
if event.section == "scope" and ("evidence" in self._section_started or "finding" in self._section_started):
|
||||
return []
|
||||
if event.section == "evidence" and "finding" in self._section_started:
|
||||
if event.evidence_level >= 4 or event.track in {
|
||||
"latest_updates",
|
||||
"release_status",
|
||||
"official_confirmation",
|
||||
"specs_architecture",
|
||||
"v4_lite",
|
||||
}:
|
||||
promoted_key = event.dedupe_key or f"evidence:{self._normalize_key(text)}"
|
||||
event = ReasoningEvent(
|
||||
"finding",
|
||||
text,
|
||||
track=event.track,
|
||||
evidence_level=event.evidence_level,
|
||||
dedupe_key=f"finding:promoted:{promoted_key}",
|
||||
)
|
||||
else:
|
||||
return []
|
||||
|
||||
dedupe_key = event.dedupe_key or f"{event.section}:{self._normalize_key(text)}"
|
||||
if dedupe_key in self._emitted_keys:
|
||||
return []
|
||||
|
||||
if event.track:
|
||||
count_key = (event.section, event.track)
|
||||
emitted_count = self._track_emit_counts.get(count_key, 0)
|
||||
max_per_track = 1 if event.section in {"scope", "evidence"} else 2
|
||||
if emitted_count >= max_per_track and not dedupe_key.endswith("agents_started"):
|
||||
return []
|
||||
best_key = (event.section, event.track)
|
||||
best_level = self._track_best_level.get(best_key, -1)
|
||||
if best_level > event.evidence_level:
|
||||
return []
|
||||
self._track_best_level[best_key] = max(best_level, event.evidence_level)
|
||||
self._track_emit_counts[count_key] = emitted_count + 1
|
||||
|
||||
self._emitted_keys.add(dedupe_key)
|
||||
lines: list[str] = []
|
||||
if event.section not in self._section_started:
|
||||
self._section_started.add(event.section)
|
||||
lines.append(self._section_title(event.section) + "\n")
|
||||
lines.append(text + "\n")
|
||||
return lines
|
||||
|
||||
def _observe_language(self, text: str) -> None:
|
||||
if not text:
|
||||
return
|
||||
cjk_count = len(re.findall(r"[\u4e00-\u9fff]", text))
|
||||
en_count = len(re.findall(r"[A-Za-z]", text))
|
||||
if cjk_count >= 4 or cjk_count > max(2, en_count // 2):
|
||||
self._zh_votes += 1
|
||||
if self._language is None:
|
||||
self._language = "zh"
|
||||
return
|
||||
if en_count >= 4:
|
||||
self._en_votes += 1
|
||||
|
||||
def _section_title(self, section: str) -> str:
|
||||
labels = _ZH_LABELS if self._language != "en" else _EN_LABELS
|
||||
return labels.get(section, section)
|
||||
|
||||
def _localized_line(self, key: str) -> str:
|
||||
zh_map = {
|
||||
"agents_started": "- 已启动并行代理进行交叉检索与核验。",
|
||||
"code_execution": "- 正在执行代码或生成可运行内容。",
|
||||
}
|
||||
en_map = {
|
||||
"agents_started": "- Parallel agents have started cross-checking the topic.",
|
||||
"code_execution": "- Executing code or generating runnable content.",
|
||||
}
|
||||
mapping = zh_map if self._language != "en" else en_map
|
||||
return mapping[key]
|
||||
|
||||
def _localized_track_line(self, track: str) -> str:
|
||||
label = self._track_label(track)
|
||||
if self._language == "en":
|
||||
return f"- Parallel research: {label}."
|
||||
return f"- 并行检索:{label}。"
|
||||
|
||||
def _localized_social_line(self, track: str) -> str:
|
||||
label = self._track_label(track)
|
||||
if self._language == "en":
|
||||
return f"- Social cross-check: {label}."
|
||||
return f"- 社媒交叉核验:{label}。"
|
||||
|
||||
def _localized_browse_line(self, source_kind: str, track: str) -> str:
|
||||
track_label = self._track_label(track) if track else ""
|
||||
if self._language == "en":
|
||||
mapping = {
|
||||
"official": "Page verification: official site and official pages",
|
||||
"product": "Page verification: product page and live UI",
|
||||
"community": "Page verification: public reports and community write-ups",
|
||||
}
|
||||
else:
|
||||
mapping = {
|
||||
"official": "页面核对:官网与官方页面",
|
||||
"product": "页面核对:产品页面与实际界面",
|
||||
"community": "页面核对:公开报道与社区文章",
|
||||
}
|
||||
base = mapping[source_kind]
|
||||
if track_label:
|
||||
connector = ", focusing on " if self._language == "en" else ",重点核对"
|
||||
return f"- {base}{connector}{track_label}{'.' if self._language == 'en' else '。'}"
|
||||
return f"- {base}{'.' if self._language == 'en' else '。'}"
|
||||
|
||||
def _localized_image_line(self, topic: str) -> str:
|
||||
if self._language == "en":
|
||||
mapping = {
|
||||
"diagram": "- Visual asset search: diagrams and explanatory graphics.",
|
||||
"photo": "- Visual asset search: real-world comparison photos.",
|
||||
"generic": "- Visual asset search: supporting image references.",
|
||||
}
|
||||
else:
|
||||
mapping = {
|
||||
"diagram": "- 视觉素材检索:示意图与结构说明素材。",
|
||||
"photo": "- 视觉素材检索:实景对比图片。",
|
||||
"generic": "- 视觉素材检索:补充说明图片。",
|
||||
}
|
||||
return mapping[topic]
|
||||
|
||||
def _track_label(self, track: str) -> str:
|
||||
labels = _ZH_LABELS if self._language != "en" else _EN_LABELS
|
||||
return labels.get(track, track)
|
||||
|
||||
def _infer_track(self, text: str) -> str:
|
||||
lowered = self._compact_query(text).lower()
|
||||
if not lowered:
|
||||
return ""
|
||||
for track, keywords in _TRACK_RULES:
|
||||
if any(keyword in lowered for keyword in keywords):
|
||||
return track
|
||||
return ""
|
||||
|
||||
def _classify_page_source(self, url: str, args: dict[str, Any]) -> tuple[str, str]:
|
||||
lowered = url.lower()
|
||||
instructions = str(args.get("instructions") or "")
|
||||
track = self._pick_browse_track(f"{url} {instructions}")
|
||||
if any(domain in lowered for domain in ("deepseek.ai", "deepseek.com")):
|
||||
if "chat.deepseek.com" in lowered or "platform.deepseek.com" in lowered:
|
||||
return "product", track or "ui_modes"
|
||||
return "official", track or "official_confirmation"
|
||||
if url:
|
||||
return "community", track
|
||||
return "", track
|
||||
|
||||
def _pick_browse_track(self, text: str) -> str:
|
||||
lowered = self._compact_query(text).lower()
|
||||
priority = (
|
||||
("ui_modes", ("expert", "vision", "mode", "界面", "ui")),
|
||||
("release_status", ("release", "released", "launch", "发布", "上线", "status")),
|
||||
("specs_architecture", ("spec", "parameter", "architecture", "context", "engram", "moe", "规格", "参数", "架构", "上下文")),
|
||||
("v4_lite", ("v4 lite", "sealion", "sealion-lite", "海狮")),
|
||||
("official_confirmation", ("official", "官网", "current models", "offering")),
|
||||
)
|
||||
for track, keywords in priority:
|
||||
if any(keyword in lowered for keyword in keywords):
|
||||
return track
|
||||
return self._infer_track(text)
|
||||
|
||||
def _classify_image_topic(self, text: str) -> str:
|
||||
lowered = text.lower()
|
||||
if any(token in lowered for token in ("diagram", "示意图", "bulge")):
|
||||
return "diagram"
|
||||
if any(token in lowered for token in ("photo", "照片", "real", "high tide", "low tide", "高潮", "低潮")):
|
||||
return "photo"
|
||||
return "generic"
|
||||
|
||||
def _looks_like_progress(self, text: str) -> bool:
|
||||
lowered = text.lower()
|
||||
return any(hint in lowered for hint in _PROGRESSIVE_HINTS)
|
||||
|
||||
def _looks_like_verification(self, text: str) -> bool:
|
||||
lowered = text.lower()
|
||||
return any(token in lowered for token in ("确认", "核对", "浏览", "整合", "比对", "check", "verify", "browse", "integrat"))
|
||||
|
||||
def _looks_like_finding(self, text: str) -> bool:
|
||||
lowered = text.lower()
|
||||
if self._looks_like_progress(text):
|
||||
return False
|
||||
return any(hint in lowered for hint in _FINDING_HINTS)
|
||||
|
||||
def _clean_report_clause(self, raw_part: str) -> str:
|
||||
clause = re.sub(r"\s+", " ", raw_part).strip(" -•\t")
|
||||
if not clause:
|
||||
return ""
|
||||
delimiter = ":" if ":" in clause else ":" if ":" in clause else ""
|
||||
if delimiter:
|
||||
head, tail = clause.split(delimiter, 1)
|
||||
head_lower = head.strip().lower()
|
||||
if len(head.strip()) <= 18 or any(token in head_lower for token in ("总结", "最新", "关键", "补充", "latest", "summary", "note")):
|
||||
clause = tail.strip()
|
||||
clause = clause.strip(" -•\t")
|
||||
clause = re.sub(r"^(?:我知道|我收集了可靠信息|我收集到的?信息|从搜索结果总结|详细解释要点(?:([^)]+))?|补充)\s*", "", clause)
|
||||
clause = re.sub(r"^(?:that|it shows|it seems)\s+", "", clause, flags=re.IGNORECASE)
|
||||
if len(clause) < 8:
|
||||
return ""
|
||||
lowered = clause.lower()
|
||||
if any(lowered.startswith(prefix) for prefix in _LOW_VALUE_PREFIXES):
|
||||
return ""
|
||||
if "?" in clause or "?" in clause:
|
||||
return ""
|
||||
return self._compact_text(clause, limit=120)
|
||||
|
||||
def _score_report_clause(self, clause: str) -> int:
|
||||
lowered = clause.lower()
|
||||
score = 0
|
||||
if any(hint in lowered for hint in _FINDING_HINTS):
|
||||
score += 3
|
||||
if re.search(r"\b\d+(?:\.\d+)?\b", clause):
|
||||
score += 2
|
||||
if any(token in clause for token in ("月", "日", "年", "小时", "分钟")):
|
||||
score += 1
|
||||
if any(token in clause for token in ("重要", "航运", "渔业", "发电", "生态", "模式", "视觉")):
|
||||
score += 1
|
||||
if any(token in lowered for token in ("可能", "rumor", "传闻", "widely believed", "believed")):
|
||||
score -= 1
|
||||
if any(token in lowered for token in ("可以", "suggest", "建议", "should", "friendly", "reply")):
|
||||
score -= 2
|
||||
if len(clause) > 150:
|
||||
score -= 1
|
||||
return score
|
||||
|
||||
def _infer_evidence_level(self, clause: str, *, default: int) -> int:
|
||||
lowered = clause.lower()
|
||||
if any(token in lowered for token in ("官网", "official", "chat ui", "界面更新", "页面")):
|
||||
return 4
|
||||
if any(token in lowered for token in ("x平台", "x posts", "社区", "widely believed", "传闻", "rumor")):
|
||||
return max(2, default - 1)
|
||||
return default
|
||||
|
||||
def _is_unconfirmed_signal(self, clause: str) -> bool:
|
||||
lowered = clause.lower()
|
||||
return any(
|
||||
token in lowered
|
||||
for token in (
|
||||
"x平台", "x posts", "社区", "community", "widely believed", "believed",
|
||||
"传闻", "rumor", "曝光", "泄露",
|
||||
)
|
||||
)
|
||||
|
||||
def _to_bullet_text(self, text: str) -> str:
|
||||
stripped = text.strip()
|
||||
if stripped.startswith("- "):
|
||||
stripped = stripped[2:].strip()
|
||||
stripped = self._ensure_terminal_punctuation(stripped)
|
||||
return f"- {stripped}"
|
||||
|
||||
def _ensure_terminal_punctuation(self, text: str) -> str:
|
||||
stripped = text.strip()
|
||||
if not stripped:
|
||||
return ""
|
||||
if stripped.endswith(("。", "!", "?", ".", "!", "?")):
|
||||
return stripped
|
||||
if re.search(r"[\u4e00-\u9fff]", stripped):
|
||||
return stripped + "。"
|
||||
return stripped + "."
|
||||
|
||||
def _compact_query(self, text: str) -> str:
|
||||
cleaned = re.sub(r"\b(?:or|and|site:[^\s]+|since:\S+|from:\S+|date:\S+)\b", " ", text, flags=re.IGNORECASE)
|
||||
cleaned = re.sub(r"[()\"']", " ", cleaned)
|
||||
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||
return cleaned
|
||||
|
||||
def _compact_text(self, text: str, *, limit: int) -> str:
|
||||
compact = re.sub(r"\s+", " ", text).strip()
|
||||
if len(compact) <= limit:
|
||||
return compact
|
||||
return compact[: limit - 3].rstrip() + "..."
|
||||
|
||||
def _normalize_key(self, text: str) -> str:
|
||||
lowered = text.lower()
|
||||
lowered = re.sub(r"https?://\S+", "", lowered)
|
||||
lowered = re.sub(r"[^\w\u4e00-\u9fff]+", "", lowered)
|
||||
return lowered
|
||||
|
||||
|
||||
__all__ = ["ReasoningAggregator", "ReasoningEvent"]
|
||||
@@ -1,27 +1,38 @@
|
||||
"""XAI Imagine WebSocket protocol — message builders and image classifier."""
|
||||
|
||||
from __future__ import annotations
|
||||
"""XAI Imagine WebSocket protocol — message builders and frame parsers."""
|
||||
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
|
||||
_URL_PATTERN = re.compile(r"/images/([a-f0-9-]+)\.(png|jpg|jpeg)", re.IGNORECASE)
|
||||
_URL_PATTERN = re.compile(r"/images/([a-f0-9\-]+)\.(png|jpg|jpeg)", re.IGNORECASE)
|
||||
|
||||
WS_IMAGINE_URL = "wss://grok.com/ws/imagine/listen"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Client message builders
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_reset_message() -> dict[str, Any]:
|
||||
"""Build the reset message that must be sent before each prompt."""
|
||||
return {
|
||||
"type": "conversation.item.create",
|
||||
"timestamp": int(time.time() * 1000),
|
||||
"item": {"type": "message", "content": [{"type": "reset"}]},
|
||||
}
|
||||
|
||||
|
||||
def build_request_message(
|
||||
request_id: str,
|
||||
prompt: str,
|
||||
aspect_ratio: str = "2:3",
|
||||
enable_nsfw: bool = True,
|
||||
enable_pro: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the WebSocket conversation.item.create message."""
|
||||
"""Build the image generation request message."""
|
||||
return {
|
||||
"type": "conversation.item.create",
|
||||
"type": "conversation.item.create",
|
||||
"timestamp": int(time.time() * 1000),
|
||||
"item": {
|
||||
"type": "message",
|
||||
@@ -30,56 +41,72 @@ def build_request_message(
|
||||
"text": prompt,
|
||||
"type": "input_text",
|
||||
"properties": {
|
||||
"section_count": 0,
|
||||
"is_kids_mode": False,
|
||||
"enable_nsfw": enable_nsfw,
|
||||
"skip_upsampler": False,
|
||||
"is_initial": False,
|
||||
"aspect_ratio": aspect_ratio,
|
||||
"section_count": 0,
|
||||
"is_kids_mode": False,
|
||||
"enable_nsfw": enable_nsfw,
|
||||
"skip_upsampler": False,
|
||||
"enable_side_by_side": True,
|
||||
"is_initial": False,
|
||||
"aspect_ratio": aspect_ratio,
|
||||
"enable_pro": enable_pro,
|
||||
},
|
||||
}],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def classify_image(
|
||||
url: str,
|
||||
blob: str,
|
||||
*,
|
||||
final_min_bytes: int = 50_000,
|
||||
medium_min_bytes: int = 5_000,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Classify a WebSocket image message into stage metadata.
|
||||
# ---------------------------------------------------------------------------
|
||||
# Server frame parsers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Returns a dict with keys: type, image_id, ext, stage, blob, blob_size, url, is_final.
|
||||
Returns None if url or blob are empty.
|
||||
def parse_image_url(url: str) -> tuple[str, str]:
|
||||
"""Extract (image_id, ext) from a /images/{id}.{ext} URL.
|
||||
|
||||
Falls back to a random UUID and 'jpg' if pattern not found.
|
||||
"""
|
||||
if not url or not blob:
|
||||
match = _URL_PATTERN.search(url or "")
|
||||
if match:
|
||||
return match.group(1), match.group(2).lower()
|
||||
return uuid.uuid4().hex, "jpg"
|
||||
|
||||
|
||||
def parse_json_frame(msg: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Parse a {type: "json"} frame.
|
||||
|
||||
Returns a normalised dict on success, None if unrecognised status.
|
||||
|
||||
Returned keys:
|
||||
status "start_stage" | "completed"
|
||||
image_id str
|
||||
order int
|
||||
width int
|
||||
height int
|
||||
moderated bool (only meaningful for "completed")
|
||||
r_rated bool (only meaningful for "completed")
|
||||
"""
|
||||
status = msg.get("current_status")
|
||||
if status not in ("start_stage", "completed"):
|
||||
return None
|
||||
|
||||
match = _URL_PATTERN.search(url)
|
||||
image_id = match.group(1) if match else uuid.uuid4().hex
|
||||
ext = match.group(2).lower() if match else "png"
|
||||
blob_size = len(blob)
|
||||
is_final = blob_size >= final_min_bytes
|
||||
|
||||
if is_final:
|
||||
stage = "final"
|
||||
elif blob_size > medium_min_bytes:
|
||||
stage = "medium"
|
||||
else:
|
||||
stage = "preview"
|
||||
image_id = str(msg.get("image_id") or msg.get("job_id") or "")
|
||||
if not image_id:
|
||||
return None
|
||||
|
||||
return {
|
||||
"type": "image",
|
||||
"status": status,
|
||||
"image_id": image_id,
|
||||
"ext": ext,
|
||||
"stage": stage,
|
||||
"blob": blob,
|
||||
"blob_size": blob_size,
|
||||
"url": url,
|
||||
"is_final": is_final,
|
||||
"order": int(msg.get("order") or 0),
|
||||
"width": int(msg.get("width") or 0),
|
||||
"height": int(msg.get("height") or 0),
|
||||
"moderated": bool(msg.get("moderated")),
|
||||
"r_rated": bool(msg.get("r_rated")),
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["WS_IMAGINE_URL", "build_request_message", "classify_image"]
|
||||
__all__ = [
|
||||
"WS_IMAGINE_URL",
|
||||
"build_reset_message",
|
||||
"build_request_message",
|
||||
"parse_image_url",
|
||||
"parse_json_frame",
|
||||
]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""XAI image-edit protocol — payload builder and SSE field extractors."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.platform.config.snapshot import get_config
|
||||
|
||||
IMAGE_EDIT_MODEL_NAME = "imagine-image-edit"
|
||||
IMAGE_EDIT_MODEL_KIND = "imagine"
|
||||
IMAGE_POST_MEDIA_TYPE = "MEDIA_POST_TYPE_IMAGE"
|
||||
IMAGE_EDIT_GENERATION_COUNT = 2
|
||||
|
||||
|
||||
def build_image_edit_payload(
|
||||
*,
|
||||
prompt: str,
|
||||
image_references: list[str],
|
||||
parent_post_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the JSON payload for imagine image-edit chat requests."""
|
||||
cfg = get_config()
|
||||
return {
|
||||
"temporary": cfg.get_bool("features.temporary", True),
|
||||
"modelName": IMAGE_EDIT_MODEL_NAME,
|
||||
"message": prompt,
|
||||
"enableImageGeneration": True,
|
||||
"returnImageBytes": False,
|
||||
"returnRawGrokInXaiRequest": False,
|
||||
"enableImageStreaming": True,
|
||||
"imageGenerationCount": IMAGE_EDIT_GENERATION_COUNT,
|
||||
"forceConcise": False,
|
||||
"toolOverrides": {"imageGen": True},
|
||||
"enableSideBySide": True,
|
||||
"sendFinalMetadata": True,
|
||||
"isReasoning": False,
|
||||
"disableTextFollowUps": True,
|
||||
"responseMetadata": {
|
||||
"modelConfigOverride": {
|
||||
"modelMap": {
|
||||
"imageEditModel": IMAGE_EDIT_MODEL_KIND,
|
||||
"imageEditModelConfig": {
|
||||
"imageReferences": image_references,
|
||||
"parentPostId": parent_post_id,
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
"disableMemory": not cfg.get_bool("features.memory", False),
|
||||
"forceSideBySide": False,
|
||||
}
|
||||
|
||||
|
||||
def extract_streaming_response(data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Return ``response.streamingImageGenerationResponse`` when present."""
|
||||
result = data.get("result")
|
||||
if not isinstance(result, dict):
|
||||
return None
|
||||
response = result.get("response")
|
||||
if not isinstance(response, dict):
|
||||
return None
|
||||
stream = response.get("streamingImageGenerationResponse")
|
||||
return stream if isinstance(stream, dict) else None
|
||||
|
||||
|
||||
def extract_model_response_urls(data: dict[str, Any]) -> list[str]:
|
||||
"""Return fallback ``modelResponse.generatedImageUrls`` values."""
|
||||
result = data.get("result")
|
||||
if not isinstance(result, dict):
|
||||
return []
|
||||
response = result.get("response")
|
||||
if not isinstance(response, dict):
|
||||
return []
|
||||
model_response = response.get("modelResponse")
|
||||
if not isinstance(model_response, dict):
|
||||
return []
|
||||
urls = model_response.get("generatedImageUrls")
|
||||
if not isinstance(urls, list):
|
||||
return []
|
||||
return [url for url in urls if isinstance(url, str) and url]
|
||||
|
||||
|
||||
def extract_model_response_file_attachments(data: dict[str, Any]) -> list[str]:
|
||||
"""Return fallback ``modelResponse.fileAttachments`` asset IDs."""
|
||||
result = data.get("result")
|
||||
if not isinstance(result, dict):
|
||||
return []
|
||||
response = result.get("response")
|
||||
if not isinstance(response, dict):
|
||||
return []
|
||||
model_response = response.get("modelResponse")
|
||||
if not isinstance(model_response, dict):
|
||||
return []
|
||||
attachments = model_response.get("fileAttachments")
|
||||
if not isinstance(attachments, list):
|
||||
return []
|
||||
return [attachment for attachment in attachments if isinstance(attachment, str) and attachment]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"IMAGE_EDIT_MODEL_NAME",
|
||||
"IMAGE_EDIT_MODEL_KIND",
|
||||
"IMAGE_POST_MEDIA_TYPE",
|
||||
"IMAGE_EDIT_GENERATION_COUNT",
|
||||
"build_image_edit_payload",
|
||||
"extract_streaming_response",
|
||||
"extract_model_response_urls",
|
||||
"extract_model_response_file_attachments",
|
||||
]
|
||||
@@ -5,8 +5,6 @@ a short-lived LiveKit access token. The WebSocket connection uses that
|
||||
access token as a query parameter on wss://livekit.grok.com/rtc.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
from urllib.parse import urlencode
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""XAI rate-limits API protocol — fetch live quota data per mode."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import orjson
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
@@ -18,13 +16,15 @@ _MODE_NAMES: dict[int, str] = {
|
||||
0: "auto",
|
||||
1: "fast",
|
||||
2: "expert",
|
||||
3: "heavy",
|
||||
}
|
||||
|
||||
# Default window durations used as fallback when API call fails.
|
||||
_DEFAULT_WINDOW_SECS: dict[int, int] = {
|
||||
0: 72_000, # auto — 20 h
|
||||
1: 72_000, # fast — 20 h
|
||||
2: 36_000, # expert — 10 h
|
||||
0: 72_000, # auto — 20 h (basic) / 2 h (super/heavy, real value overrides)
|
||||
1: 72_000, # fast — 20 h (basic)
|
||||
2: 36_000, # expert — 10 h (basic)
|
||||
3: 7_200, # heavy — 2 h (heavy-pool only)
|
||||
}
|
||||
|
||||
|
||||
@@ -141,16 +141,19 @@ async def _fetch_one(token: str, mode_id: int) -> object | None:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def fetch_all_quotas(token: str) -> dict[int, object] | None:
|
||||
"""Fetch quota windows for all three modes (auto / fast / expert) concurrently.
|
||||
"""Fetch quota windows for all four modes (auto / fast / expert / heavy) concurrently.
|
||||
|
||||
Issues three requests in parallel. Returns ``{mode_id: QuotaWindow}``
|
||||
for every mode that responded successfully, or ``None`` if all failed.
|
||||
Issues four requests in parallel. Mode 3 (heavy) will silently return
|
||||
``None`` for basic and super accounts — this is expected and harmless.
|
||||
Returns ``{mode_id: QuotaWindow}`` for every mode that responded
|
||||
successfully, or ``None`` if all four failed.
|
||||
"""
|
||||
import asyncio
|
||||
results = await asyncio.gather(
|
||||
_fetch_one(token, 0),
|
||||
_fetch_one(token, 1),
|
||||
_fetch_one(token, 2),
|
||||
_fetch_one(token, 3),
|
||||
return_exceptions=False,
|
||||
)
|
||||
windows = {mode_id: win for mode_id, win in enumerate(results) if win is not None}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""XAI video creation protocol — payload builders for media/post/create endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MEDIA_POST_URL = "https://grok.com/rest/media/post/create"
|
||||
@@ -24,24 +22,6 @@ def build_media_post_payload(
|
||||
return payload
|
||||
|
||||
|
||||
def build_video_request_payload(
|
||||
*,
|
||||
prompt: str,
|
||||
aspect_ratio: str = "3:2",
|
||||
video_length: int = 6,
|
||||
resolution: str = "480p",
|
||||
preset: str = "custom",
|
||||
) -> dict[str, Any]:
|
||||
"""Build the app-chat request_overrides for video generation."""
|
||||
return {
|
||||
"mediaType": "video",
|
||||
"aspectRatio": aspect_ratio,
|
||||
"videoDuration": video_length,
|
||||
"resolution": resolution,
|
||||
"preset": preset,
|
||||
}
|
||||
|
||||
|
||||
def build_upscale_payload(video_id: str) -> dict[str, Any]:
|
||||
return {"videoId": video_id}
|
||||
|
||||
@@ -57,6 +37,6 @@ def build_media_link_payload(post_id: str) -> dict[str, Any]:
|
||||
|
||||
__all__ = [
|
||||
"MEDIA_POST_URL", "MEDIA_LINK_URL", "VIDEO_UPSCALE_URL",
|
||||
"build_media_post_payload", "build_video_request_payload",
|
||||
"build_media_post_payload",
|
||||
"build_upscale_payload", "build_media_link_payload",
|
||||
]
|
||||
@@ -8,8 +8,6 @@ NOTE: gRPC-Web endpoints (accept_tos, nsfw_mgmt) live on different
|
||||
hosts (accounts.x.ai, grok.com with gRPC path), listed separately.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
BASE = "https://grok.com"
|
||||
ASSETS_CDN = "https://assets.grok.com"
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ Pre-built profiles eliminate per-request config lookups in the hot path.
|
||||
Each profile specifies timeout, max retries, and retry-eligible status codes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@ Calls POST /rest/app-chat/upload-file with base64-encoded content and
|
||||
returns the file metadata ID used as a file attachment reference in chat.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import mimetypes
|
||||
import re
|
||||
@@ -17,11 +16,25 @@ from app.platform.logging.logger import logger
|
||||
from app.platform.config.snapshot import get_config
|
||||
from app.platform.errors import UpstreamError, ValidationError
|
||||
from app.dataplane.proxy import get_proxy_runtime
|
||||
from app.dataplane.proxy.adapters.headers import build_sso_cookie
|
||||
from app.dataplane.proxy.adapters.headers import build_http_headers
|
||||
from app.dataplane.proxy.adapters.session import ResettableSession, build_session_kwargs
|
||||
from app.dataplane.reverse.protocol.xai_assets import resolve_asset_reference
|
||||
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind
|
||||
|
||||
_UPLOAD_URL = "https://grok.com/rest/app-chat/upload-file"
|
||||
_X_USER_ID_RE = re.compile(r"(?:^|;\s*)x-userid=([^;]+)")
|
||||
|
||||
# Global semaphore — limits concurrent upload_file() calls across all requests.
|
||||
# Initialised lazily on first call so the event loop is guaranteed to be running.
|
||||
_upload_sem: asyncio.Semaphore | None = None
|
||||
|
||||
def _get_upload_sem() -> asyncio.Semaphore:
|
||||
global _upload_sem
|
||||
if _upload_sem is None:
|
||||
n = max(1, int(get_config("batch.asset_upload_concurrency", 10)))
|
||||
_upload_sem = asyncio.Semaphore(n)
|
||||
return _upload_sem
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -90,6 +103,16 @@ async def upload_file(
|
||||
Raises:
|
||||
``UpstreamError`` on HTTP failure.
|
||||
"""
|
||||
async with _get_upload_sem():
|
||||
return await _upload_file_inner(token, filename, mime, b64)
|
||||
|
||||
|
||||
async def _upload_file_inner(
|
||||
token: str,
|
||||
filename: str,
|
||||
mime: str,
|
||||
b64: str,
|
||||
) -> tuple[str, str]:
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("asset.upload_timeout", 60.0)
|
||||
|
||||
@@ -113,7 +136,7 @@ async def upload_file(
|
||||
timeout = timeout_s,
|
||||
)
|
||||
|
||||
body_bytes = await response.aread()
|
||||
body_bytes = response.content
|
||||
if response.status_code != 200:
|
||||
body_text = body_bytes.decode("utf-8", "replace")[:300]
|
||||
logger.error(
|
||||
@@ -169,7 +192,7 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]:
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
resp = await session.get(file_input, headers=headers, timeout=30.0)
|
||||
raw = await resp.aread()
|
||||
raw = resp.content
|
||||
if resp.status_code != 200:
|
||||
raise UpstreamError(
|
||||
f"Failed to fetch input URL: {resp.status_code}",
|
||||
@@ -189,4 +212,26 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]:
|
||||
return await upload_file(token, filename, mime, b64)
|
||||
|
||||
|
||||
__all__ = ["upload_file", "upload_from_input", "parse_data_uri"]
|
||||
def resolve_uploaded_asset_reference(token: str, file_id: str, file_uri: str) -> str:
|
||||
"""Resolve an uploaded asset to the content URL required by image-edit."""
|
||||
user_id = _extract_user_id(token)
|
||||
url = resolve_asset_reference(file_id, file_uri, user_id=user_id)
|
||||
if url:
|
||||
return url
|
||||
raise UpstreamError("Could not resolve uploaded asset reference URL")
|
||||
|
||||
|
||||
def _extract_user_id(token: str) -> str | None:
|
||||
cookie = build_sso_cookie(token)
|
||||
match = _X_USER_ID_RE.search(cookie)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"upload_file",
|
||||
"upload_from_input",
|
||||
"parse_data_uri",
|
||||
"resolve_uploaded_asset_reference",
|
||||
]
|
||||
@@ -4,12 +4,30 @@ All functions acquire a proxy lease internally, execute the upstream call,
|
||||
give feedback, and return results to the caller.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, AsyncGenerator, Dict, Optional
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.config.snapshot import get_config
|
||||
|
||||
# Global semaphores — limit concurrent transport calls across all callers.
|
||||
# Lazily initialised so the event loop is guaranteed to be running on first use.
|
||||
_list_sem: asyncio.Semaphore | None = None
|
||||
_delete_sem: asyncio.Semaphore | None = None
|
||||
|
||||
def _get_list_sem() -> asyncio.Semaphore:
|
||||
global _list_sem
|
||||
if _list_sem is None:
|
||||
n = max(1, int(get_config("batch.asset_list_concurrency", 50)))
|
||||
_list_sem = asyncio.Semaphore(n)
|
||||
return _list_sem
|
||||
|
||||
def _get_delete_sem() -> asyncio.Semaphore:
|
||||
global _delete_sem
|
||||
if _delete_sem is None:
|
||||
n = max(1, int(get_config("batch.asset_delete_concurrency", 50)))
|
||||
_delete_sem = asyncio.Semaphore(n)
|
||||
return _delete_sem
|
||||
from app.platform.errors import UpstreamError
|
||||
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
|
||||
from app.dataplane.proxy import get_proxy_runtime
|
||||
@@ -40,6 +58,14 @@ async def list_assets(
|
||||
token: SSO session token.
|
||||
params: Optional query parameters (e.g. ``{"cursor": "...", "limit": 50}``).
|
||||
"""
|
||||
async with _get_list_sem():
|
||||
return await _list_assets_inner(token, params)
|
||||
|
||||
|
||||
async def _list_assets_inner(
|
||||
token: str,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
) -> dict:
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("asset.list_timeout", 30.0)
|
||||
|
||||
@@ -86,6 +112,11 @@ async def list_assets(
|
||||
|
||||
async def delete_asset(token: str, asset_id: str) -> dict:
|
||||
"""DELETE /rest/assets-metadata/{asset_id} and return the JSON body (may be {})."""
|
||||
async with _get_delete_sem():
|
||||
return await _delete_asset_inner(token, asset_id)
|
||||
|
||||
|
||||
async def _delete_asset_inner(token: str, asset_id: str) -> dict:
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("asset.delete_timeout", 30.0)
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ Sends a pre-framed gRPC-Web request to *url* and returns the parsed
|
||||
the caller controls acquisition and feedback.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
@@ -33,13 +31,17 @@ async def post_grpc_web(
|
||||
token: str,
|
||||
payload: bytes,
|
||||
*,
|
||||
lease: ProxyLease | None = None,
|
||||
timeout_s: float = 30.0,
|
||||
origin: str = "https://grok.com",
|
||||
referer: str = "https://grok.com/",
|
||||
lease: ProxyLease | None = None,
|
||||
timeout_s: float = 30.0,
|
||||
origin: str = "https://grok.com",
|
||||
referer: str = "https://grok.com/",
|
||||
session: "ResettableSession | None" = None,
|
||||
) -> Tuple[List[bytes], Dict[str, str]]:
|
||||
"""POST a gRPC-Web frame to *url*.
|
||||
|
||||
Pass *session* to reuse an existing connection (avoids a new TLS handshake).
|
||||
When *session* is ``None`` a fresh session is created and closed automatically.
|
||||
|
||||
Returns:
|
||||
``(messages, trailers)`` — raw protobuf message payloads and the
|
||||
gRPC trailer map (includes ``grpc-status``, ``grpc-message``).
|
||||
@@ -56,35 +58,20 @@ async def post_grpc_web(
|
||||
)
|
||||
headers.update(_GRPC_WEB_HEADERS)
|
||||
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
response = await session.post(
|
||||
url,
|
||||
headers = headers,
|
||||
data = payload,
|
||||
timeout = timeout_s,
|
||||
)
|
||||
|
||||
body_bytes = await response.aread()
|
||||
async def _do(s: "ResettableSession") -> Tuple[List[bytes], Dict[str, str]]:
|
||||
response = await s.post(url, headers=headers, data=payload, timeout=timeout_s)
|
||||
body_bytes = response.content
|
||||
if response.status_code != 200:
|
||||
body_text = body_bytes.decode("utf-8", "replace")[:300]
|
||||
logger.error(
|
||||
"gRPC-Web POST failed: url={} status={} body={}",
|
||||
url, response.status_code, body_text,
|
||||
)
|
||||
raise UpstreamError(
|
||||
f"Upstream returned {response.status_code}",
|
||||
status = response.status_code,
|
||||
body = body_text,
|
||||
)
|
||||
logger.error("gRPC-Web POST failed: url={} status={} body={}", url, response.status_code, body_text)
|
||||
raise UpstreamError(f"Upstream returned {response.status_code}", status=response.status_code, body=body_text)
|
||||
return GrpcClient.parse_response(body_bytes, content_type=response.headers.get("content-type"), headers=response.headers)
|
||||
|
||||
content_type = response.headers.get("content-type")
|
||||
return GrpcClient.parse_response(
|
||||
body_bytes,
|
||||
content_type = content_type,
|
||||
headers = response.headers,
|
||||
)
|
||||
if session is not None:
|
||||
return await _do(session)
|
||||
|
||||
async with ResettableSession(**build_session_kwargs(lease=lease)) as s:
|
||||
return await _do(s)
|
||||
|
||||
|
||||
__all__ = ["post_grpc_web"]
|
||||
@@ -4,8 +4,6 @@ Wraps curl_cffi AsyncSession; handles proxy selection, header building,
|
||||
retry-on-reset, and timeout.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, AsyncGenerator
|
||||
|
||||
@@ -41,7 +39,8 @@ async def post_stream(
|
||||
)
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
session = ResettableSession(**kwargs)
|
||||
try:
|
||||
response = await session.post(
|
||||
url,
|
||||
headers = headers,
|
||||
@@ -52,30 +51,37 @@ async def post_stream(
|
||||
|
||||
if response.status_code != 200:
|
||||
try:
|
||||
body = (await response.aread()).decode("utf-8", "replace")[:400]
|
||||
body = (response.content).decode("utf-8", "replace")[:400]
|
||||
except Exception:
|
||||
body = ""
|
||||
logger.error(
|
||||
"HTTP POST failed: url={} status={} body={}",
|
||||
url, response.status_code, body,
|
||||
)
|
||||
await session.close()
|
||||
raise UpstreamError(
|
||||
f"Upstream returned {response.status_code}",
|
||||
status = response.status_code,
|
||||
body = body,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
async def _lines() -> AsyncGenerator[str, None]:
|
||||
async def _lines() -> AsyncGenerator[str, None]:
|
||||
try:
|
||||
async for line in response.aiter_lines():
|
||||
yield line
|
||||
finally:
|
||||
try:
|
||||
async for line in response.aiter_lines():
|
||||
yield line
|
||||
finally:
|
||||
try:
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return _lines()
|
||||
return _lines()
|
||||
|
||||
|
||||
async def post_json(
|
||||
@@ -83,47 +89,36 @@ async def post_json(
|
||||
token: str,
|
||||
payload: bytes,
|
||||
*,
|
||||
lease: ProxyLease | None = None,
|
||||
timeout_s: float = 30.0,
|
||||
content_type: str = "application/json",
|
||||
origin: str = "https://grok.com",
|
||||
referer: str = "https://grok.com/",
|
||||
lease: ProxyLease | None = None,
|
||||
timeout_s: float = 30.0,
|
||||
content_type: str = "application/json",
|
||||
origin: str = "https://grok.com",
|
||||
referer: str = "https://grok.com/",
|
||||
session: "ResettableSession | None" = None,
|
||||
) -> dict:
|
||||
"""POST *url* and return parsed JSON response body."""
|
||||
headers = build_http_headers(
|
||||
token,
|
||||
content_type = content_type,
|
||||
origin = origin,
|
||||
referer = referer,
|
||||
lease = lease,
|
||||
)
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
"""POST *url* and return parsed JSON response body.
|
||||
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
response = await session.post(
|
||||
url,
|
||||
headers = headers,
|
||||
data = payload,
|
||||
timeout = timeout_s,
|
||||
)
|
||||
Pass *session* to reuse an existing connection (avoids a new TLS handshake).
|
||||
When *session* is ``None`` a fresh session is created and closed automatically.
|
||||
"""
|
||||
headers = build_http_headers(token, content_type=content_type, origin=origin, referer=referer, lease=lease)
|
||||
|
||||
body_bytes = await response.aread()
|
||||
import orjson
|
||||
|
||||
async def _do(s: "ResettableSession") -> dict:
|
||||
response = await s.post(url, headers=headers, data=payload, timeout=timeout_s)
|
||||
body_bytes = response.content
|
||||
if response.status_code not in (200, 201, 204):
|
||||
body_text = body_bytes.decode("utf-8", "replace")[:400]
|
||||
logger.error(
|
||||
"HTTP POST JSON failed: url={} status={} body={}",
|
||||
url, response.status_code, body_text,
|
||||
)
|
||||
raise UpstreamError(
|
||||
f"Upstream returned {response.status_code}",
|
||||
status = response.status_code,
|
||||
body = body_text,
|
||||
)
|
||||
logger.error("HTTP POST JSON failed: url={} status={} body={}", url, response.status_code, body_text)
|
||||
raise UpstreamError(f"Upstream returned {response.status_code}", status=response.status_code, body=body_text)
|
||||
return orjson.loads(body_bytes) if body_bytes.strip() else {}
|
||||
|
||||
if not body_bytes.strip():
|
||||
return {}
|
||||
import orjson
|
||||
return orjson.loads(body_bytes)
|
||||
if session is not None:
|
||||
return await _do(session)
|
||||
|
||||
async with ResettableSession(**build_session_kwargs(lease=lease)) as s:
|
||||
return await _do(s)
|
||||
|
||||
|
||||
async def get_json(
|
||||
@@ -154,7 +149,7 @@ async def get_json(
|
||||
timeout = timeout_s,
|
||||
)
|
||||
|
||||
body_bytes = await response.aread()
|
||||
body_bytes = response.content
|
||||
if response.status_code != 200:
|
||||
body_text = body_bytes.decode("utf-8", "replace")[:400]
|
||||
logger.error(
|
||||
@@ -197,7 +192,7 @@ async def delete_json(
|
||||
timeout = timeout_s,
|
||||
)
|
||||
|
||||
body_bytes = await response.aread()
|
||||
body_bytes = response.content
|
||||
if response.status_code not in (200, 204):
|
||||
body_text = body_bytes.decode("utf-8", "replace")[:400]
|
||||
logger.error(
|
||||
@@ -241,7 +236,8 @@ async def get_bytes_stream(
|
||||
headers.update(extra_headers)
|
||||
kwargs = build_session_kwargs(lease=lease)
|
||||
|
||||
async with ResettableSession(**kwargs) as session:
|
||||
session = ResettableSession(**kwargs)
|
||||
try:
|
||||
response = await session.get(
|
||||
url,
|
||||
headers = headers,
|
||||
@@ -252,31 +248,38 @@ async def get_bytes_stream(
|
||||
|
||||
if response.status_code != 200:
|
||||
try:
|
||||
body = (await response.aread()).decode("utf-8", "replace")[:400]
|
||||
body = (response.content).decode("utf-8", "replace")[:400]
|
||||
except Exception:
|
||||
body = ""
|
||||
logger.error(
|
||||
"HTTP GET stream failed: url={} status={} body={}",
|
||||
url, response.status_code, body,
|
||||
)
|
||||
await session.close()
|
||||
raise UpstreamError(
|
||||
f"Upstream returned {response.status_code}",
|
||||
status = response.status_code,
|
||||
body = body,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
async def _chunks() -> AsyncGenerator[bytes, None]:
|
||||
async def _chunks() -> AsyncGenerator[bytes, None]:
|
||||
try:
|
||||
async for chunk in response.aiter_content():
|
||||
if chunk:
|
||||
yield chunk
|
||||
finally:
|
||||
try:
|
||||
async for chunk in response.aiter_content():
|
||||
if chunk:
|
||||
yield chunk
|
||||
finally:
|
||||
try:
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
await session.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return _chunks()
|
||||
return _chunks()
|
||||
|
||||
|
||||
__all__ = ["post_stream", "post_json", "get_json", "delete_json", "get_bytes_stream"]
|
||||
@@ -1,14 +1,20 @@
|
||||
"""Imagine WebSocket reverse transport.
|
||||
|
||||
Connects to wss://grok.com/ws/imagine/listen and streams image events.
|
||||
Handles blocked-state detection and parallel retry.
|
||||
"""
|
||||
Protocol (per round):
|
||||
Client → reset message
|
||||
Client → prompt message
|
||||
Server → N × (start_stage json → image frames → completed json)
|
||||
Server → [may close WS, or keep open for next round]
|
||||
|
||||
from __future__ import annotations
|
||||
One WS connection is reused across rounds until the server closes it or n
|
||||
images have been collected. This avoids a TLS handshake per round when
|
||||
requesting more images than a single round produces (speed=6, quality=4).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, AsyncGenerator
|
||||
|
||||
import aiohttp
|
||||
@@ -16,22 +22,258 @@ import orjson
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
from app.platform.config.snapshot import get_config
|
||||
from app.control.proxy.models import ProxyLease, ProxyScope, RequestKind
|
||||
from app.control.proxy.models import ProxyScope, RequestKind
|
||||
from app.dataplane.proxy import get_proxy_runtime
|
||||
from app.dataplane.proxy.adapters.headers import build_ws_headers
|
||||
from app.dataplane.reverse.protocol.xai_image import (
|
||||
WS_IMAGINE_URL, build_request_message, classify_image,
|
||||
WS_IMAGINE_URL,
|
||||
build_reset_message,
|
||||
build_request_message,
|
||||
parse_image_url,
|
||||
parse_json_frame,
|
||||
)
|
||||
from .websocket import WebSocketClient
|
||||
|
||||
|
||||
class _BlockedError(Exception):
|
||||
"""Upstream is reviewing/blocking the image — safe to retry."""
|
||||
|
||||
|
||||
_client = WebSocketClient()
|
||||
_INTER_ROUND_WAIT_S = 2.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Slot state
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class _Slot:
|
||||
"""Tracks one in-flight image generation slot."""
|
||||
image_id: str
|
||||
order: int
|
||||
width: int
|
||||
height: int
|
||||
last_blob: str = field(default="", repr=False)
|
||||
last_url: str = ""
|
||||
done: bool = False
|
||||
progress: int = 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _final_event(slot: _Slot, r_rated: bool = False) -> dict[str, Any]:
|
||||
return {
|
||||
"type": "image",
|
||||
"image_id": slot.image_id,
|
||||
"order": slot.order,
|
||||
"stage": "final",
|
||||
"blob": slot.last_blob,
|
||||
"url": slot.last_url,
|
||||
"width": slot.width,
|
||||
"height": slot.height,
|
||||
"is_final": True,
|
||||
"moderated": False,
|
||||
"r_rated": r_rated,
|
||||
}
|
||||
|
||||
|
||||
async def _probe_ws_closed(ws: aiohttp.ClientWebSocketResponse, wait_s: float) -> bool:
|
||||
"""Wait up to *wait_s* seconds for a CLOSE frame.
|
||||
|
||||
Returns True if the server closed the connection, False if the connection
|
||||
appears to still be alive (timeout expired with no CLOSE received).
|
||||
"""
|
||||
try:
|
||||
msg = await asyncio.wait_for(ws.receive(), timeout=wait_s)
|
||||
return msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR)
|
||||
except asyncio.TimeoutError:
|
||||
return False
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Single-round generator
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _stream_round(
|
||||
ws: aiohttp.ClientWebSocketResponse,
|
||||
prompt: str,
|
||||
*,
|
||||
aspect_ratio: str,
|
||||
enable_nsfw: bool,
|
||||
enable_pro: bool,
|
||||
needed: int,
|
||||
stream_timeout_s: float,
|
||||
round_timeout_s: float,
|
||||
inter_round_wait_s: float,
|
||||
) -> AsyncGenerator[dict[str, Any], None]:
|
||||
"""Drive one round of image generation on an already-open WS.
|
||||
|
||||
Sends reset + prompt, then processes frames until all slots are completed
|
||||
or the WS closes. Always yields a ``{type: "_meta", ws_closed: bool}``
|
||||
sentinel as the very last item so the caller knows whether to reconnect.
|
||||
"""
|
||||
request_id = str(uuid.uuid4())
|
||||
try:
|
||||
await ws.send_json(build_reset_message())
|
||||
await ws.send_json(build_request_message(
|
||||
request_id, prompt, aspect_ratio, enable_nsfw, enable_pro,
|
||||
))
|
||||
except Exception as exc:
|
||||
yield {"type": "error", "error_code": "send_failed", "error": str(exc)}
|
||||
yield {"type": "_meta", "ws_closed": True}
|
||||
return
|
||||
|
||||
slots: dict[str, _Slot] = {}
|
||||
round_completed: int = 0
|
||||
round_start = time.monotonic()
|
||||
|
||||
while True:
|
||||
elapsed = time.monotonic() - round_start
|
||||
if elapsed >= round_timeout_s:
|
||||
logger.warning("Imagine round timeout after {:.1f}s", elapsed)
|
||||
for slot in slots.values():
|
||||
if not slot.done:
|
||||
if slot.last_blob:
|
||||
yield _final_event(slot)
|
||||
else:
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": "slot_incomplete",
|
||||
"error": f"slot {slot.image_id[:8]} timed out",
|
||||
}
|
||||
yield {"type": "_meta", "ws_closed": False}
|
||||
return
|
||||
|
||||
recv_timeout = min(stream_timeout_s, round_timeout_s - elapsed)
|
||||
try:
|
||||
ws_msg = await asyncio.wait_for(ws.receive(), timeout=recv_timeout)
|
||||
except asyncio.TimeoutError:
|
||||
# No frame arrived — check if all known slots are already done.
|
||||
if slots and all(s.done for s in slots.values()):
|
||||
ws_closed = await _probe_ws_closed(ws, inter_round_wait_s)
|
||||
yield {"type": "_meta", "ws_closed": ws_closed}
|
||||
return
|
||||
continue
|
||||
|
||||
# ── TEXT frames ──────────────────────────────────────────────────────
|
||||
if ws_msg.type == aiohttp.WSMsgType.TEXT:
|
||||
try:
|
||||
msg = orjson.loads(ws_msg.data)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
msg_type = msg.get("type")
|
||||
|
||||
# JSON control frames (start_stage / completed)
|
||||
if msg_type == "json":
|
||||
parsed = parse_json_frame(msg)
|
||||
if parsed is None:
|
||||
continue
|
||||
|
||||
if parsed["status"] == "start_stage":
|
||||
iid = parsed["image_id"]
|
||||
slots[iid] = _Slot(
|
||||
image_id = iid,
|
||||
order = parsed["order"],
|
||||
width = parsed["width"],
|
||||
height = parsed["height"],
|
||||
)
|
||||
logger.debug(
|
||||
"Imagine slot {} start order={} {}×{}",
|
||||
iid[:8], parsed["order"], parsed["width"], parsed["height"],
|
||||
)
|
||||
yield {
|
||||
"type": "progress",
|
||||
"image_id": iid,
|
||||
"order": parsed["order"],
|
||||
"progress": 10,
|
||||
}
|
||||
|
||||
elif parsed["status"] == "completed":
|
||||
iid = parsed["image_id"]
|
||||
slot = slots.get(iid)
|
||||
if slot is None or slot.done:
|
||||
continue
|
||||
|
||||
slot.done = True
|
||||
|
||||
if parsed["moderated"]:
|
||||
logger.warning("Imagine slot {} moderated", iid[:8])
|
||||
yield {"type": "moderated", "image_id": iid, "order": slot.order}
|
||||
else:
|
||||
logger.debug("Imagine slot {} completed order={}", iid[:8], slot.order)
|
||||
yield _final_event(slot, r_rated=parsed["r_rated"])
|
||||
round_completed += 1
|
||||
|
||||
all_done = slots and all(s.done for s in slots.values())
|
||||
if all_done:
|
||||
ws_closed = await _probe_ws_closed(ws, inter_round_wait_s)
|
||||
yield {"type": "_meta", "ws_closed": ws_closed}
|
||||
return
|
||||
|
||||
if round_completed >= needed:
|
||||
# Have enough this round; leave remaining slots in flight.
|
||||
yield {"type": "_meta", "ws_closed": False}
|
||||
return
|
||||
|
||||
# Image blob frames (intermediate previews)
|
||||
elif msg_type == "image":
|
||||
url = msg.get("url", "")
|
||||
blob = msg.get("blob", "")
|
||||
iid, _ext = parse_image_url(url)
|
||||
slot = slots.get(iid)
|
||||
if slot and not slot.done:
|
||||
slot.last_blob = blob
|
||||
slot.last_url = url
|
||||
progress = msg.get("percentage_complete")
|
||||
try:
|
||||
parsed_progress = int(float(progress)) if progress is not None else 50
|
||||
except (TypeError, ValueError):
|
||||
parsed_progress = 50
|
||||
parsed_progress = max(10, min(99, parsed_progress))
|
||||
if parsed_progress > slot.progress:
|
||||
slot.progress = parsed_progress
|
||||
yield {
|
||||
"type": "progress",
|
||||
"image_id": iid,
|
||||
"order": slot.order,
|
||||
"progress": parsed_progress,
|
||||
}
|
||||
|
||||
# Server-side error
|
||||
elif msg_type == "error":
|
||||
err_code = msg.get("err_code") or "upstream_error"
|
||||
err_msg = msg.get("err_msg") or str(msg)
|
||||
logger.warning("Imagine WS server error: {} {}", err_code, err_msg)
|
||||
yield {"type": "error", "error_code": err_code, "error": err_msg}
|
||||
yield {"type": "_meta", "ws_closed": True}
|
||||
return
|
||||
|
||||
# ── WS closed / error ────────────────────────────────────────────────
|
||||
elif ws_msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
|
||||
# Yield best-effort finals for any slots that received a blob but
|
||||
# never got a completed frame.
|
||||
for slot in slots.values():
|
||||
if not slot.done:
|
||||
if slot.last_blob:
|
||||
logger.debug(
|
||||
"Imagine WS closed: yielding best-effort final for slot {}",
|
||||
slot.image_id[:8],
|
||||
)
|
||||
yield _final_event(slot)
|
||||
else:
|
||||
logger.warning(
|
||||
"Imagine WS closed: slot {} had no blob, skipping",
|
||||
slot.image_id[:8],
|
||||
)
|
||||
yield {"type": "_meta", "ws_closed": True}
|
||||
return
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def stream_images(
|
||||
token: str,
|
||||
prompt: str,
|
||||
@@ -39,179 +281,91 @@ async def stream_images(
|
||||
aspect_ratio: str = "2:3",
|
||||
n: int = 1,
|
||||
enable_nsfw: bool = True,
|
||||
enable_pro: bool = False,
|
||||
) -> AsyncGenerator[dict[str, Any], None]:
|
||||
"""Stream image events from the Imagine WebSocket endpoint.
|
||||
"""Stream image events, collecting *n* final images.
|
||||
|
||||
Yields dicts with keys: type, image_id, ext, stage, blob, blob_size, url, is_final
|
||||
(or type='error' on failure).
|
||||
Reuses a single WS connection across multiple rounds when the server keeps
|
||||
the connection open. Reconnects transparently if the server closes it.
|
||||
|
||||
Yields:
|
||||
``{type: "image", is_final: True, ...}`` — final image per slot
|
||||
``{type: "moderated", ...}`` — censored slot
|
||||
``{type: "error", ...}`` — fatal error (stops iteration)
|
||||
"""
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("image.timeout", 120.0)
|
||||
stream_timeout_s = cfg.get_float("image.stream_timeout", 10.0)
|
||||
final_timeout_s = cfg.get_float("image.final_timeout", 30.0)
|
||||
blocked_grace_s = min(max(cfg.get_float("image.blocked_grace_seconds", 10.0), 1.0), final_timeout_s)
|
||||
final_min_bytes = cfg.get_int("image.final_min_bytes", 50_000)
|
||||
medium_min_bytes = cfg.get_int("image.medium_min_bytes", 5_000)
|
||||
max_retries = max(1, cfg.get_int("image.max_retries", 1))
|
||||
parallel_ok = cfg.get_bool("image.blocked_parallel_enabled", True)
|
||||
cfg = get_config()
|
||||
timeout_s = cfg.get_float("image.timeout", 120.0)
|
||||
stream_timeout_s = cfg.get_float("image.stream_timeout", 10.0)
|
||||
inter_round_wait_s = _INTER_ROUND_WAIT_S
|
||||
|
||||
async def _once() -> list[dict[str, Any]]:
|
||||
items: list[dict[str, Any]] = []
|
||||
async for ev in _stream_once(
|
||||
token, prompt,
|
||||
aspect_ratio = aspect_ratio,
|
||||
n = n,
|
||||
enable_nsfw = enable_nsfw,
|
||||
timeout_s = timeout_s,
|
||||
stream_timeout_s = stream_timeout_s,
|
||||
final_timeout_s = final_timeout_s,
|
||||
blocked_grace_s = blocked_grace_s,
|
||||
final_min_bytes = final_min_bytes,
|
||||
medium_min_bytes = medium_min_bytes,
|
||||
):
|
||||
items.append(ev)
|
||||
return items
|
||||
collected = 0
|
||||
|
||||
while collected < n:
|
||||
needed = n - collected
|
||||
|
||||
# ── Establish connection ──────────────────────────────────────────────
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET)
|
||||
headers = build_ws_headers(token=token, lease=lease)
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
items = await _once()
|
||||
for ev in items:
|
||||
yield ev
|
||||
return
|
||||
except _BlockedError:
|
||||
remaining = max_retries - attempt - 1
|
||||
if remaining > 0 and parallel_ok:
|
||||
logger.warning("Imagine blocked; launching {} parallel retries", remaining)
|
||||
tasks = [asyncio.create_task(_once()) for _ in range(remaining)]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for result in results:
|
||||
if isinstance(result, Exception):
|
||||
continue
|
||||
if any(ev.get("is_final") for ev in result if isinstance(ev, dict)):
|
||||
for ev in result:
|
||||
yield ev
|
||||
return
|
||||
yield {"type": "error", "error_code": "blocked", "error": "blocked_no_final_image"}
|
||||
return
|
||||
if attempt + 1 < max_retries:
|
||||
logger.warning("Imagine blocked, retry {}/{}", attempt + 1, max_retries)
|
||||
continue
|
||||
yield {"type": "error", "error_code": "blocked", "error": "blocked_no_final_image"}
|
||||
return
|
||||
conn = await _client.connect(
|
||||
WS_IMAGINE_URL,
|
||||
headers = headers,
|
||||
timeout = timeout_s,
|
||||
ws_kwargs = {"heartbeat": 20, "receive_timeout": stream_timeout_s},
|
||||
lease = lease,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Imagine stream error: {}", exc)
|
||||
yield {"type": "error", "error_code": "stream_error", "error": str(exc)}
|
||||
status = getattr(exc, "status", None)
|
||||
logger.error("Imagine WS connect failed: {}", exc)
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": "rate_limit_exceeded" if status == 429 else "connection_failed",
|
||||
"error": str(exc),
|
||||
}
|
||||
return
|
||||
|
||||
# ── Run rounds on this connection ─────────────────────────────────────
|
||||
try:
|
||||
async with conn as ws:
|
||||
while collected < n:
|
||||
needed = n - collected
|
||||
async for ev in _stream_round(
|
||||
ws, prompt,
|
||||
aspect_ratio = aspect_ratio,
|
||||
enable_nsfw = enable_nsfw,
|
||||
enable_pro = enable_pro,
|
||||
needed = needed,
|
||||
stream_timeout_s = stream_timeout_s,
|
||||
round_timeout_s = timeout_s,
|
||||
inter_round_wait_s = inter_round_wait_s,
|
||||
):
|
||||
if ev["type"] == "_meta":
|
||||
ws_closed = ev["ws_closed"]
|
||||
break # exit inner for-loop; handle ws_closed below
|
||||
if ev.get("is_final"):
|
||||
collected += 1
|
||||
yield ev
|
||||
if ev["type"] == "error":
|
||||
return
|
||||
else:
|
||||
# _stream_round exhausted without a _meta — shouldn't happen
|
||||
ws_closed = True
|
||||
|
||||
async def _stream_once(
|
||||
token: str,
|
||||
prompt: str,
|
||||
*,
|
||||
aspect_ratio: str,
|
||||
n: int,
|
||||
enable_nsfw: bool,
|
||||
timeout_s: float,
|
||||
stream_timeout_s: float,
|
||||
final_timeout_s: float,
|
||||
blocked_grace_s: float,
|
||||
final_min_bytes: int,
|
||||
medium_min_bytes: int,
|
||||
) -> AsyncGenerator[dict[str, Any], None]:
|
||||
request_id = str(uuid.uuid4())
|
||||
proxy = await get_proxy_runtime()
|
||||
lease = await proxy.acquire(
|
||||
scope = ProxyScope.APP,
|
||||
kind = RequestKind.WEBSOCKET,
|
||||
)
|
||||
headers = build_ws_headers(token=token, lease=lease)
|
||||
if ws_closed or collected >= n:
|
||||
break # exit inner while; reconnect or finish
|
||||
|
||||
try:
|
||||
conn = await _client.connect(
|
||||
WS_IMAGINE_URL,
|
||||
headers = headers,
|
||||
timeout = timeout_s,
|
||||
ws_kwargs = {"heartbeat": 20, "receive_timeout": stream_timeout_s},
|
||||
lease = lease,
|
||||
)
|
||||
except Exception as exc:
|
||||
status = getattr(exc, "status", None)
|
||||
logger.error("Imagine WebSocket connect failed: {}", exc)
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": "rate_limit_exceeded" if status == 429 else "connection_failed",
|
||||
"error": str(exc),
|
||||
}
|
||||
return
|
||||
except aiohttp.ClientError as exc:
|
||||
logger.error("Imagine WS connection error: {}", exc)
|
||||
yield {"type": "error", "error_code": "connection_failed", "error": str(exc)}
|
||||
return
|
||||
|
||||
try:
|
||||
async with conn as ws:
|
||||
await ws.send_json(build_request_message(request_id, prompt, aspect_ratio, enable_nsfw))
|
||||
logger.info("Imagine request sent: prompt={!r:.50} ratio={}", prompt, aspect_ratio)
|
||||
if collected >= n:
|
||||
return
|
||||
|
||||
final_ids: set[str] = set()
|
||||
completed: int = 0
|
||||
start = time.monotonic()
|
||||
last_activity = start
|
||||
medium_received_at: float | None = None
|
||||
|
||||
while time.monotonic() - start < timeout_s:
|
||||
try:
|
||||
ws_msg = await asyncio.wait_for(ws.receive(), timeout=5.0)
|
||||
except asyncio.TimeoutError:
|
||||
now = time.monotonic()
|
||||
if medium_received_at and completed == 0 and now - medium_received_at > blocked_grace_s:
|
||||
logger.warning("Imagine blocked: medium received but no final in {:.1f}s", blocked_grace_s)
|
||||
raise _BlockedError()
|
||||
if completed > 0 and now - last_activity > 10.0:
|
||||
break
|
||||
continue
|
||||
|
||||
if ws_msg.type == aiohttp.WSMsgType.TEXT:
|
||||
last_activity = time.monotonic()
|
||||
try:
|
||||
msg = orjson.loads(ws_msg.data)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
msg_type = msg.get("type")
|
||||
if msg_type == "image":
|
||||
info = classify_image(
|
||||
msg.get("url", ""), msg.get("blob", ""),
|
||||
final_min_bytes = final_min_bytes,
|
||||
medium_min_bytes = medium_min_bytes,
|
||||
)
|
||||
if not info:
|
||||
continue
|
||||
if info["stage"] == "medium" and medium_received_at is None:
|
||||
medium_received_at = time.monotonic()
|
||||
if info["is_final"] and info["image_id"] not in final_ids:
|
||||
final_ids.add(info["image_id"])
|
||||
completed += 1
|
||||
yield info
|
||||
|
||||
elif msg_type == "error":
|
||||
logger.warning("Imagine WS error: {} {}", msg.get("err_code"), msg.get("err_msg"))
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": msg.get("err_code", ""),
|
||||
"error": msg.get("err_msg", ""),
|
||||
}
|
||||
return
|
||||
|
||||
if completed >= n:
|
||||
break
|
||||
|
||||
if medium_received_at and completed == 0 and time.monotonic() - medium_received_at > final_timeout_s:
|
||||
logger.warning("Imagine final-timeout: no final image in {:.1f}s", final_timeout_s)
|
||||
raise _BlockedError()
|
||||
|
||||
elif ws_msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
|
||||
yield {"type": "error", "error_code": "ws_closed", "error": str(ws_msg.type)}
|
||||
return
|
||||
|
||||
except aiohttp.ClientError as exc:
|
||||
yield {"type": "error", "error_code": "connection_failed", "error": str(exc)}
|
||||
# Server closed the connection but we still need more images → reconnect.
|
||||
logger.info("Imagine reconnecting for {}/{} remaining images", n - collected, n)
|
||||
|
||||
|
||||
__all__ = ["stream_images"]
|
||||
@@ -5,8 +5,6 @@
|
||||
``WebSocketConnection`` that the products layer can read/write.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import orjson
|
||||
|
||||
@@ -3,10 +3,6 @@
|
||||
All three endpoints are simple JSON POST calls with proxy lifecycle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
import orjson
|
||||
|
||||
from app.platform.logging.logger import logger
|
||||
@@ -85,6 +81,7 @@ async def create_media_post(
|
||||
media_type: str,
|
||||
media_url: str = "",
|
||||
prompt: str = "",
|
||||
referer: str = "https://grok.com/imagine",
|
||||
) -> dict:
|
||||
"""POST /rest/media/post/create — create a media post."""
|
||||
payload = build_media_post_payload(
|
||||
@@ -95,6 +92,7 @@ async def create_media_post(
|
||||
return await _post_with_proxy(
|
||||
MEDIA_POST_URL, token, payload,
|
||||
label = "create_media_post",
|
||||
referer = referer,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""WebSocket transport with proxy and SOCKS support."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
from typing import Any, Awaitable, Callable, Mapping, Optional
|
||||
from urllib.parse import urlparse
|
||||
@@ -108,7 +106,8 @@ class WebSocketClient:
|
||||
|
||||
try:
|
||||
extra: dict[str, Any] = dict(ws_kwargs or {})
|
||||
skip_ssl = cfg.get_bool("proxy.skip_proxy_ssl_verify", False) and bool(proxy_url)
|
||||
skip_ssl = cfg.get_bool("proxy.egress.skip_ssl_verify",
|
||||
cfg.get_bool("proxy.skip_proxy_ssl_verify", False)) and bool(proxy_url)
|
||||
|
||||
if skip_ssl and urlparse(proxy_url).scheme.lower() == "https":
|
||||
proxy_ssl = ssl.create_default_context()
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Reverse pipeline data types — ReversePlan, ReverseLeaseSet, ReverseResult."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import IntEnum, auto
|
||||
from typing import Any
|
||||
@@ -43,15 +41,15 @@ class TransportKind(IntEnum):
|
||||
@dataclass(slots=True)
|
||||
class ReversePlan:
|
||||
"""Describes how a single upstream call should be executed."""
|
||||
endpoint: str # full URL
|
||||
transport_kind: TransportKind
|
||||
pool_id: int # 0=basic, 1=super
|
||||
mode_id: int # 0=auto, 1=fast, 2=expert
|
||||
timeout_s: float = 120.0
|
||||
content_type: str = "application/json"
|
||||
origin: str = "https://grok.com"
|
||||
referer: str = "https://grok.com/"
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
endpoint: str # full URL
|
||||
transport_kind: TransportKind
|
||||
pool_candidates: tuple[int, ...] # ordered pool IDs to try (e.g. (0,1,2))
|
||||
mode_id: int # 0=auto, 1=fast, 2=expert, 3=heavy
|
||||
timeout_s: float = 120.0
|
||||
content_type: str = "application/json"
|
||||
origin: str = "https://grok.com"
|
||||
referer: str = "https://grok.com/"
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
||||
@@ -4,8 +4,6 @@ These mirror the control-plane enums but use IntEnum exclusively so they
|
||||
can be used directly as array indices with zero overhead.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
@@ -18,6 +16,7 @@ class ModeId(IntEnum):
|
||||
class PoolId(IntEnum):
|
||||
BASIC = 0
|
||||
SUPER = 1
|
||||
HEAVY = 2
|
||||
|
||||
|
||||
class StatusId(IntEnum):
|
||||
@@ -32,6 +31,7 @@ class StatusId(IntEnum):
|
||||
POOL_STR_TO_ID: dict[str, int] = {
|
||||
"basic": int(PoolId.BASIC),
|
||||
"super": int(PoolId.SUPER),
|
||||
"heavy": int(PoolId.HEAVY),
|
||||
}
|
||||
|
||||
STATUS_STR_TO_ID: dict[str, int] = {
|
||||
@@ -41,7 +41,7 @@ STATUS_STR_TO_ID: dict[str, int] = {
|
||||
"disabled": int(StatusId.DISABLED),
|
||||
}
|
||||
|
||||
ALL_MODE_IDS: tuple[int, ...] = (int(ModeId.AUTO), int(ModeId.FAST), int(ModeId.EXPERT))
|
||||
ALL_MODE_IDS: tuple[int, ...] = (int(ModeId.AUTO), int(ModeId.FAST), int(ModeId.EXPERT), 3)
|
||||
|
||||
__all__ = [
|
||||
"ModeId", "PoolId", "StatusId",
|
||||
|
||||
+10
-5
@@ -4,8 +4,6 @@ Start with:
|
||||
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
@@ -20,6 +18,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from app.platform.logging.logger import logger, setup_logging, reload_logging
|
||||
from app.platform.config.snapshot import config as _config
|
||||
from app.platform.errors import AppError
|
||||
from app.platform.meta import get_project_version
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Early logging setup (before config is loaded)
|
||||
@@ -44,10 +43,14 @@ async def lifespan(app: FastAPI):
|
||||
)
|
||||
|
||||
# 2. Initialise account repository and bootstrap runtime table.
|
||||
from app.control.account.backends.factory import create_repository
|
||||
from app.control.account.backends.factory import create_repository, describe_repository_target
|
||||
from app.control.account.runtime import set_refresh_service
|
||||
from app.control.account.scheduler import get_account_refresh_scheduler
|
||||
from app.dataplane.account import get_account_directory
|
||||
|
||||
storage_backend, storage_target = describe_repository_target()
|
||||
logger.info("Account storage: backend={} target={}", storage_backend, storage_target)
|
||||
|
||||
repo = create_repository()
|
||||
await repo.initialize()
|
||||
directory = await get_account_directory(repo)
|
||||
@@ -64,6 +67,7 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
# Expose refresh service for fire-and-forget post-call quota sync.
|
||||
app.state.refresh_service = refresh_svc
|
||||
set_refresh_service(refresh_svc)
|
||||
|
||||
# 4. Initialise proxy directory.
|
||||
from app.control.proxy import get_proxy_directory
|
||||
@@ -77,6 +81,7 @@ async def lifespan(app: FastAPI):
|
||||
# -----------
|
||||
logger.info("Grok2API shutting down.")
|
||||
scheduler.stop()
|
||||
set_refresh_service(None)
|
||||
await repo.close()
|
||||
|
||||
|
||||
@@ -87,7 +92,7 @@ async def lifespan(app: FastAPI):
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(
|
||||
title = "Grok2API",
|
||||
version = "2.0.0",
|
||||
version = get_project_version(),
|
||||
description = "OpenAI-compatible API gateway for Grok",
|
||||
lifespan = lifespan,
|
||||
)
|
||||
@@ -120,7 +125,7 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
|
||||
# Routers.
|
||||
from app.products.web.routes import router as web_router
|
||||
from app.products.web import router as web_router
|
||||
from app.products.openai.router import router as openai_router
|
||||
|
||||
app.include_router(web_router)
|
||||
|
||||
@@ -6,8 +6,6 @@ v1 schema (``data/account/v1/accounts.db``):
|
||||
v2 schema: current ``LocalAccountRepository`` (per-mode quota columns).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Migration runner — import legacy token storage into the new account domain."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
"""API-key authentication dependencies for FastAPI routes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
|
||||
from fastapi import Header, HTTPException, status
|
||||
from fastapi import Header, HTTPException, Query, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.platform.config.snapshot import get_config
|
||||
@@ -76,13 +74,18 @@ async def verify_api_key(
|
||||
|
||||
async def verify_admin_key(
|
||||
authorization: str | None = Header(default=None),
|
||||
app_key: str | None = Query(default=None),
|
||||
) -> None:
|
||||
"""Validate Bearer token against ``app.app_key`` (admin access)."""
|
||||
"""Validate Bearer token against ``app.app_key`` (admin access).
|
||||
|
||||
Accepts either ``Authorization: Bearer <key>`` header or ``?app_key=<key>``
|
||||
query parameter (the latter is needed for EventSource which cannot send headers).
|
||||
"""
|
||||
key = get_admin_key()
|
||||
if not key:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Admin key is not configured.")
|
||||
|
||||
token = _extract_bearer(authorization)
|
||||
token = _extract_bearer(authorization) or app_key
|
||||
if token is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing authentication token.")
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""TOML configuration loader with environment-variable override support."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Typed configuration snapshot — built once at startup, read-only at runtime."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -9,6 +7,15 @@ from typing import Any
|
||||
from .loader import get_nested, load_config
|
||||
|
||||
_BASE_DIR = Path(__file__).resolve().parents[3] # project root
|
||||
_DATA_DIR = _BASE_DIR / "data"
|
||||
|
||||
|
||||
def _resolve_defaults_path() -> Path:
|
||||
return _BASE_DIR / "config.defaults.toml"
|
||||
|
||||
|
||||
def _resolve_user_path() -> Path:
|
||||
return _DATA_DIR / "config.toml"
|
||||
|
||||
|
||||
class ConfigSnapshot:
|
||||
@@ -30,8 +37,10 @@ class ConfigSnapshot:
|
||||
) -> None:
|
||||
"""Load configuration files. Idempotent — subsequent calls reload."""
|
||||
async with self._lock:
|
||||
dp = defaults_path or (_BASE_DIR / "config.defaults.toml")
|
||||
up = user_path or (_BASE_DIR / "config.toml")
|
||||
dp = defaults_path or _resolve_defaults_path()
|
||||
up = user_path or _resolve_user_path()
|
||||
if not dp.exists():
|
||||
raise RuntimeError(f"Missing required defaults config: {dp}")
|
||||
self._data = await asyncio.to_thread(load_config, dp, up)
|
||||
self._loaded = True
|
||||
|
||||
@@ -86,12 +95,13 @@ class ConfigSnapshot:
|
||||
from .loader import _deep_merge
|
||||
self._data = _deep_merge(self._data, patch)
|
||||
# Persist to user config file.
|
||||
user_path = _BASE_DIR / "config.toml"
|
||||
user_path = _resolve_user_path()
|
||||
await asyncio.to_thread(self._write_toml, user_path, self._data)
|
||||
|
||||
@staticmethod
|
||||
def _write_toml(path: Path, data: dict[str, Any]) -> None:
|
||||
"""Write config dict to TOML file."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
import tomli_w
|
||||
with open(path, "wb") as fh:
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Platform-level exception hierarchy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user