4 Commits
Author SHA1 Message Date
3970260761 8c2ce3dcb9 fix: 公众号保活续期与可观测 (v2.2.1)
- 保活追加带 token 的 /cgi-bin/home 续期请求(we-mp-rss/hive-mp 同源做法)
- 服务端未续期时本地延长临期会话 Cookie 到 7 天(仅在线验证通过后)
- 新增保活运行记录 + 在线页显示会话有效期/上次保活时间/运行记录
- 桥接新增 mpState / mpKeepAlive 方法
- 修复保活锁与 syncing 状态崩溃残留导致保活永久卡死
2026-11-10 22:37:50 +08:00
3970260761 35284395b3 feat: 主界面停靠浏览器右侧 Side Panel (v2.2.0)
- 点扩展图标直接打开/收起右侧停靠栏(sidePanel),常驻随浏览器窗口走
- manifest: default_popup 移除,新增 side_panel + sidePanel 权限
- background: setPanelBehavior(openPanelOnActionClick) + onClicked 手动开栏兜底
- 首页「窗口」按钮仅在气泡上下文 self-close,侧栏里不再误关
2026-11-10 21:27:21 +08:00
3970260761 38f5c400d6 feat: 独立窗口固定停靠屏幕右侧 (v2.1.5)
- 窗口按钮打开的 popup 窗口贴屏幕右缘、占满可用高度、宽 440
- top=0 起始,排除任务栏高度(availHeight)
2026-11-10 21:09:09 +08:00
3970260761 704bfa1c8a feat: 设置内联到首页,删除谢谢支持横幅 (v2.1.4)
- 设置内容(同步桥接/悬浮按钮/自建站点/历史入口)从抽屉移出,直接铺在首页
- 删除首页「谢谢支持」分享横幅与 GitHub/分享文案
- 顶栏移除「设置」按钮,设置抽屉组件一并删除
2026-11-10 20:27:55 +08:00
11 changed files with 602 additions and 403 deletions

No files matched your search

+21
View File
@@ -1,5 +1,26 @@
# Changelog
## v2.2.0 (2026-10-23)
- ✨ **主界面停靠浏览器右侧(Side Panel)**:点扩展图标直接在浏览器右缘打开/收起侧栏,常驻停靠、随浏览器窗口走,可拖拽调宽
- 移除旧的气泡弹窗形态(default_popup → side_panel);保留「窗口」按钮用于桌面级右侧独立窗口
- 兼容:侧栏上下文中「窗口」按钮不再误关自己
---
## v2.1.5 (2026-10-23)
- ✨ 「窗口」按钮打开的独立窗口**固定停靠屏幕右侧**:贴右缘、占满可用高度(排除任务栏)、宽 440
---
## v2.1.4 (2026-10-23)
- ✨ 设置内容全部**移出抽屉、内联到首页**(同步桥接状态/Token/地址、悬浮按钮、自建站点、历史入口直接可见)
- 🗑️ 删除首页「谢谢支持」分享横幅(含分享/GitHub 文案);顶栏「设置」按钮与设置抽屉一并移除
---
## v2.1.3 (2026-10-23)
- 🆕 新增「窗口」入口:扩展可在**独立窗口**中打开并常驻保持(不随点击外部关闭,适合长期盯同步桥接/公众号在线状态)
+19
View File
@@ -129,6 +129,25 @@ export function parseMpAuth(html: string): MpAuthInfo | null {
}
}
/** 公众号会话关键 Cookie(按重要性排序,与社区保活工具 hive-mp 同源的取法) */
export const MP_SESSION_COOKIE_NAMES = ['slave_sid', 'slave_user', 'bizuin', 'uin', 'pass_ticket'] as const
/**
* 取公众号会话的过期时间(秒级时间戳,与 chrome.cookies.expirationDate 同单位)。
* 会话是否即将到期只看这些关键 Cookie,统计类 Cookie 不参与。
*/
export function mpSessionExpiry(
cookies: Array<{ name: string; expirationDate?: number }>,
): number | null {
for (const name of MP_SESSION_COOKIE_NAMES) {
const c = cookies.find((x) => x.name === name)
if (c && typeof c.expirationDate === 'number' && c.expirationDate > 0) {
return c.expirationDate
}
}
return null
}
/**
* 按 Cookie 规范拼装 Cookie 请求头
* 只包含对目标 URL 生效(domain/path 匹配)的 Cookie
+8 -5
View File
@@ -2,15 +2,17 @@
"manifest_version": 3,
"name": "文章同步助手",
"description": "一键同步文章到知乎、头条、掘金等 20+ 平台,支持公众号多账号保持在线",
"version": "2.1.3",
"version": "2.2.1",
"icons": {
"16": "assets/icon-16.png",
"48": "assets/icon-48.png",
"128": "assets/icon-128.png"
},
"action": {
"default_icon": "assets/icon-48.png",
"default_popup": "src/popup/index.html"
"default_icon": "assets/icon-48.png"
},
"side_panel": {
"default_path": "src/popup/index.html"
},
"permissions": [
"storage",
@@ -22,7 +24,8 @@
"tabs",
"alarms",
"contextMenus",
"downloads"
"downloads",
"sidePanel"
],
"host_permissions": [
"http://*/*",
@@ -96,4 +99,4 @@
]
}
]
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@wechatsync/extension",
"version": "2.1.3",
"version": "2.2.1",
"private": true,
"description": "微信公众号同步助手 Chrome 扩展",
"type": "module",
@@ -40,4 +40,4 @@
"vite": "^5.0.10",
"vitest": "^2.0.0"
}
}
}
@@ -1147,6 +1147,25 @@ function getCmsIcon(type: string): string {
}
}
/**
* 扩展主界面停靠浏览器右侧(sidePanel)
* - 点扩展图标直接在浏览器右缘打开/收起侧栏(常驻停靠,随浏览器窗口走)
* - setPanelBehavior 不可用时回退:图标点击手动开侧栏
*/
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch(() => {
chrome.action.onClicked.addListener(async (tab) => {
if (!tab.id) return
try {
await chrome.sidePanel.setOptions({ tabId: tab.id, enabled: true })
await chrome.sidePanel.open({ tabId: tab.id })
} catch {
/* 忽略:无侧栏权限的老环境 */
}
})
})
/**
* 处理右键菜单点击
*/
+183 -8
View File
@@ -15,6 +15,8 @@ import {
MP_TARGET_KEY,
MP_DEFAULT_INTERVAL,
MP_HOME_URL,
mpSessionExpiry,
MP_SESSION_COOKIE_NAMES,
parseMpAuth,
readMpCookies,
withMpAccountCookies,
@@ -43,6 +45,41 @@ const MIN_RUN_INTERVAL = 30 * 1000
const REQUEST_GAP = 400
/** 连续失败多少次判定为离线 */
const OFFLINE_AFTER_FAILS = 3
/** 保活运行记录(storage.local,供界面与远程诊断查看) */
const MP_RUN_HISTORY_KEY = 'mpKeepAliveHistory'
const MAX_RUN_HISTORY = 40
/** 会话 Cookie 剩余有效期不足该秒数时触发本地延长(48 小时) */
const EXTEND_THRESHOLD_SEC = 48 * 3600
/** 本地延长后的目标有效期(7 天) */
const EXTEND_TO_SEC = 7 * 24 * 3600
/** 同步状态超过该毫秒数仍为 syncing 视为崩溃残留,不再阻止保活 */
const SYNC_STALE_MS = 10 * 60 * 1000
/** 保活锁超过该毫秒数视为残留锁(崩溃恢复) */
const LOCK_STALE_MS = 5 * 60 * 1000
/** 单次保活运行记录 */
export interface MpRunRecord {
at: number
id: string
status: 'online' | 'expired' | 'offline' | 'error' | 'skipped'
note?: string
/** 保活前的会话过期时间(秒级时间戳) */
expiryBefore?: number | null
/** 保活后的会话过期时间(秒级时间戳) */
expiryAfter?: number | null
}
async function recordRun(rec: Omit<MpRunRecord, 'at'> & { at?: number }): Promise<void> {
try {
const { at, ...rest } = rec
const stored = await chrome.storage.local.get(MP_RUN_HISTORY_KEY)
const list = (stored[MP_RUN_HISTORY_KEY] as MpRunRecord[] | undefined) || []
list.unshift({ ...rest, at: at ?? Date.now() })
await chrome.storage.local.set({ [MP_RUN_HISTORY_KEY]: list.slice(0, MAX_RUN_HISTORY) })
} catch (error) {
logger.warn('写入保活记录失败:', error)
}
}
/** 返回给 popup 的账号摘要(不带 Cookie,体积小) */
export interface MpAccountSummary {
@@ -58,6 +95,8 @@ export interface MpAccountSummary {
lastOnlineAt?: number
failCount: number
note?: string
/** 会话过期时间(秒级时间戳) */
sessionExpiry?: number | null
cookieCount: number
createdAt: number
}
@@ -75,7 +114,8 @@ function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function summarize(account: MpAccount): MpAccountSummary {
function summarize(account: MpAccount, jar?: MpCookie[]): MpAccountSummary {
const live = account.isCurrent && jar ? jar : account.cookies
return {
id: account.id,
userName: account.userName,
@@ -89,6 +129,7 @@ function summarize(account: MpAccount): MpAccountSummary {
lastOnlineAt: account.lastOnlineAt,
failCount: account.failCount,
note: account.note,
sessionExpiry: mpSessionExpiry(live),
cookieCount: account.cookies?.length || 0,
createdAt: account.createdAt,
}
@@ -111,14 +152,21 @@ export async function getMpState(): Promise<{
accounts: MpAccountSummary[]
targetId: string
alarmPeriodMinutes: number | null
lastRunAt: number | null
history: MpRunRecord[]
}> {
const list = await loadAccounts()
const stored = await chrome.storage.local.get(MP_TARGET_KEY)
const stored = await chrome.storage.local.get([MP_TARGET_KEY, MP_RUN_HISTORY_KEY])
const session = await chrome.storage.session.get([MP_LAST_RUN_KEY])
const alarms = await chrome.alarms.get(MP_KEEPALIVE_ALARM)
const jar = await readMpCookies(runtime)
const history = (stored[MP_RUN_HISTORY_KEY] as MpRunRecord[] | undefined) || []
return {
accounts: list.map(summarize),
accounts: list.map((a) => summarize(a, jar)),
targetId: (stored[MP_TARGET_KEY] as string) || 'current',
alarmPeriodMinutes: alarms?.periodInMinutes ?? null,
lastRunAt: (session[MP_LAST_RUN_KEY] as number | undefined) ?? null,
history: history.slice(0, 12),
}
}
@@ -317,6 +365,7 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
const now = Date.now()
const isCurrent = jar.length > 0 && isAccountCurrentSession(account, jar)
if (account.isCurrent !== isCurrent) account.isCurrent = isCurrent
const expiryBefore = mpSessionExpiry(isCurrent ? jar : account.cookies)
try {
let html: string
@@ -349,6 +398,7 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.failCount += 1
account.note = '登录态已过期,需要重新扫码登录'
logger.warn(`[${account.nickName || account.userName}] 登录态已过期`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
if (account.userName && auth.userName && auth.userName !== account.userName) {
@@ -356,9 +406,49 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.failCount += 1
account.note = `返回了其他账号(${auth.nickName || auth.userName}),登录态异常`
logger.warn(`[${account.nickName}] ${account.note}`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
// ★ 续期请求:带 token 访问后台首页(社区验证的会话活跃端点,we-mp-rss / hive-mp 同源做法)。
// 根路径只做在线判定,这个请求让服务端会话持续活跃。
let renewNote: string | undefined
try {
const renewUrl = `https://mp.weixin.qq.com/cgi-bin/home?token=${encodeURIComponent(auth.token)}&lang=zh_CN`
const fetchRenewAuth = async (): Promise<ReturnType<typeof parseMpAuth>> => {
const res = await runtime.fetch(renewUrl, { method: 'GET' })
return parseMpAuth(await res.text())
}
const renewAuth = isCurrent
? await fetchRenewAuth()
: await withMpAccountCookies(runtime, account.cookies, fetchRenewAuth, {
onCookiesRefreshed: (cookies) => {
account.cookies = cookies
},
})
if (
renewAuth &&
account.userName &&
renewAuth.userName &&
renewAuth.userName !== account.userName
) {
account.status = 'expired'
account.failCount += 1
account.note = `续期请求返回了其他账号(${renewAuth.nickName || renewAuth.userName}),登录态异常`
logger.warn(`[${account.nickName}] ${account.note}`)
await recordRun({ id: account.id, status: 'expired', note: account.note, expiryBefore })
return
}
if (renewAuth) {
account.token = renewAuth.token
account.ticket = renewAuth.ticket || account.ticket
account.svrTime = renewAuth.svrTime
}
} catch (renewError) {
renewNote = `续期请求失败: ${(renewError as Error).message}`
logger.warn(renewNote)
}
account.status = 'online'
account.failCount = 0
account.note = undefined
@@ -369,7 +459,30 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.svrTime = auth.svrTime
account.nickName = auth.nickName || account.nickName
account.avatar = auth.avatar || account.avatar
logger.info(`[${account.nickName || account.userName}] 保活成功`)
// ★ 读取续期后的会话过期时间;服务端没续就本地延长临期 Cookie(仅当前登录账号的实时 Cookie 可改)
const afterJar = isCurrent ? await readMpCookies(runtime) : account.cookies
let expiryAfter = mpSessionExpiry(afterJar)
const extended = await extendCurrentMpSessionCookies(account, isCurrent, expiryAfter)
if (extended) {
expiryAfter = extended
renewNote = renewNote
? `${renewNote};已本地延长会话有效期`
: '服务端未延长,已本地延长会话有效期'
}
logger.info(
`[${account.nickName || account.userName}] 保活成功` +
(renewNote ? `(${renewNote})` : '') +
(expiryAfter ? `,会话有效期至 ${new Date(expiryAfter * 1000).toLocaleString()}` : ''),
)
await recordRun({
id: account.id,
status: 'online',
note: renewNote,
expiryBefore,
expiryAfter,
})
} catch (error) {
account.failCount += 1
account.lastCheckAt = now
@@ -378,9 +491,66 @@ async function keepAliveOne(account: MpAccount, jar: MpCookie[]): Promise<void>
account.status = 'offline'
}
logger.warn(`[${account.nickName || account.userName}] 保活失败:`, error)
await recordRun({
id: account.id,
status: account.failCount >= OFFLINE_AFTER_FAILS ? 'offline' : 'error',
note: account.note,
expiryBefore,
})
}
}
/**
* 本地兜底续期:服务端没有通过 Set-Cookie 延长有效期时,把 48 小时内到期的
* 会话 Cookie(slave_sid 等)直接改写为 7 天后。只在本次在线验证通过后调用,
* 且只处理浏览器当前登录账号的实时 Cookie(其他账号走快照注入,客户端有效期不参与请求)。
*
* @returns 成功延长后的最新过期时间(秒),未延长返回 null
*/
async function extendCurrentMpSessionCookies(
account: MpAccount,
isCurrent: boolean,
expirySec: number | null,
): Promise<number | null> {
if (!isCurrent) return null
if (!expirySec) return null
if (!account.status || account.status !== 'online') return null
const remaining = expirySec - Date.now() / 1000
if (remaining > EXTEND_THRESHOLD_SEC) return null
try {
const list = await chrome.cookies.getAll({ domain: 'mp.weixin.qq.com' })
const target = Math.floor(Date.now() / 1000) + EXTEND_TO_SEC
let touched = false
for (const c of list) {
if (!(MP_SESSION_COOKIE_NAMES as readonly string[]).includes(c.name)) continue
if (!c.expirationDate || c.expirationDate - Date.now() / 1000 > EXTEND_THRESHOLD_SEC) continue
const set = await chrome.cookies.set({
url: `https://mp.weixin.qq.com${c.path || '/'}`,
name: c.name,
value: c.value,
path: c.path || '/',
secure: c.secure,
httpOnly: c.httpOnly,
sameSite: c.sameSite,
expirationDate: target,
storeId: c.storeId,
...(c.hostOnly ? {} : { domain: c.domain }),
})
if (set) touched = true
}
if (!touched) return null
const fresh = await chrome.cookies.getAll({ domain: 'mp.weixin.qq.com' })
const actual = mpSessionExpiry(fresh)
if (actual && actual > expirySec) {
logger.info(`会话 Cookie 有效期已本地延长至 ${new Date(actual * 1000).toLocaleString()}`)
return actual
}
} catch (error) {
logger.warn('本地延长会话有效期失败:', error)
}
return null
}
/**
* 对所有启用的账号执行一次保活
* @param force 忽略节流与"同步进行中"保护
@@ -389,20 +559,25 @@ export async function keepAliveMpAccounts(force = false): Promise<MpKeepAliveRes
const lock = await chrome.storage.session.get([MP_LOCK_KEY, MP_LAST_RUN_KEY])
const now = Date.now()
if (!force) {
if (lock[MP_LOCK_KEY]) {
const lockedAt = typeof lock[MP_LOCK_KEY] === 'number' ? (lock[MP_LOCK_KEY] as number) : null
if (lockedAt && now - lockedAt < LOCK_STALE_MS) {
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '保活任务进行中' }
}
if (lock[MP_LAST_RUN_KEY] && now - (lock[MP_LAST_RUN_KEY] as number) < MIN_RUN_INTERVAL) {
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '刚保活过,跳过' }
}
// 同步进行中跳过(避免与发布请求的 Cookie 注入规则互相干扰)
// 同步进行中跳过(避免与发布请求的 Cookie 注入规则互相干扰);
// 超过 SYNC_STALE_MS 仍为 syncing 视为崩溃残留,不再阻止保活
const sync = await chrome.storage.local.get('activeSyncState')
if (sync.activeSyncState?.status === 'syncing') {
const syncState = sync.activeSyncState as { status?: string; startTime?: number } | undefined
if (syncState?.status === 'syncing' && now - (syncState.startTime || 0) < SYNC_STALE_MS) {
await recordRun({ id: '*', status: 'skipped', note: '正在同步,稍后重试' })
return { total: 0, online: 0, expired: 0, offline: 0, skipped: true, message: '正在同步,稍后重试' }
}
}
await chrome.storage.session.set({ [MP_LOCK_KEY]: true })
// 锁值带时间戳:崩溃残留的旧锁超过 LOCK_STALE_MS 会被忽略,不会永久卡死保活
await chrome.storage.session.set({ [MP_LOCK_KEY]: now })
try {
const list = await refreshMpCurrentFlags()
const targets = list.filter((a) => a.enabled)
+11
View File
@@ -9,6 +9,7 @@ import {
import { markdownToHtml } from '@wechatsync/core'
import { createLogger } from '../lib/logger'
import { performSync } from '../background/sync-service'
import { getMpState, keepAliveMpAccounts } from '../lib/mp-keepalive'
const logger = createLogger('MCPClient')
@@ -505,6 +506,16 @@ class McpClient {
return await this.performImageUpload(imageData, upload.mimeType, upload.platform)
}
case 'mpState': {
// 公众号保活状态 + 运行记录(供 MCP / 远程诊断读取)
return await getMpState()
}
case 'mpKeepAlive': {
// 立即执行一轮公众号保活
return await keepAliveMpAccounts(true)
}
default:
throw new Error(`Unknown method: ${method}`)
}
@@ -1,317 +0,0 @@
import { useState, useEffect, useRef } from 'react'
import { X, Plug, PlugZap, Plus, Trash2, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { trackFeatureDiscovery } from '../../lib/analytics'
interface SettingsDrawerProps {
open: boolean
onClose: () => void
}
interface McpStatus {
enabled: boolean
connected: boolean
token?: string
serverUrl?: string
}
interface CMSAccount {
id: string
name: string
type: string
url: string
}
export function SettingsDrawer({ open, onClose }: SettingsDrawerProps) {
const [mcpStatus, setMcpStatus] = useState<McpStatus>({ enabled: true, connected: false })
const [cmsAccounts, setCmsAccounts] = useState<CMSAccount[]>([])
const [loading, setLoading] = useState(false)
const [floatingButtonEnabled, setFloatingButtonEnabled] = useState(false)
const [serverUrlInput, setServerUrlInput] = useState('')
const serverUrlTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
// 获取状态
useEffect(() => {
if (!open) return
// MCP 状态
chrome.runtime.sendMessage({ type: 'MCP_STATUS' }, (response) => {
if (response && !response.error) {
setMcpStatus({
enabled: response.enabled ?? false,
connected: response.connected ?? false,
token: response.token,
serverUrl: response.serverUrl,
})
setServerUrlInput(response.serverUrl || '')
}
})
// CMS 账户
chrome.storage.local.get('cmsAccounts', (result) => {
setCmsAccounts(result.cmsAccounts || [])
})
// 悬浮按钮设置
chrome.storage.local.get('floatingButtonEnabled', (result) => {
setFloatingButtonEnabled(result.floatingButtonEnabled ?? false)
})
}, [open])
// MCP 状态轮询 + 通知 background 加速重连
useEffect(() => {
if (!open || !mcpStatus.enabled) return
// 通知 background:用户正在关注,加速重连
chrome.runtime.sendMessage({ type: 'MCP_WATCH_START' })
const interval = setInterval(() => {
chrome.runtime.sendMessage({ type: 'MCP_STATUS' }, (response) => {
if (response && !response.error) {
setMcpStatus(prev => ({ ...prev, connected: response.connected ?? false }))
}
})
}, 3000)
return () => {
clearInterval(interval)
// 设置页关闭,恢复正常重连策略
chrome.runtime.sendMessage({ type: 'MCP_WATCH_STOP' })
}
}, [open, mcpStatus.enabled])
// 同步桥接锁定为「始终连接」:点击只会确保开启,无法关闭
const toggleMcp = async () => {
setLoading(true)
// 追踪 MCP 功能发现
trackFeatureDiscovery('mcp', 'settings').catch(() => {})
chrome.runtime.sendMessage({ type: 'MCP_ENABLE' }, (response) => {
setLoading(false)
if (response?.success) {
setMcpStatus(prev => ({
...prev,
enabled: true,
token: response.token ?? prev.token, // 保存返回的 token
}))
}
})
}
// 服务器地址变更(防抖 800ms)
const handleServerUrlChange = (value: string) => {
setServerUrlInput(value)
if (serverUrlTimer.current) {
clearTimeout(serverUrlTimer.current)
}
serverUrlTimer.current = setTimeout(() => {
chrome.runtime.sendMessage({
type: 'MCP_SET_SERVER_URL',
payload: { url: value.trim() },
})
setMcpStatus(prev => ({ ...prev, serverUrl: value.trim() }))
}, 800)
}
// 切换悬浮按钮
const toggleFloatingButton = () => {
const next = !floatingButtonEnabled
setFloatingButtonEnabled(next)
chrome.storage.local.set({ floatingButtonEnabled: next })
}
// 删除 CMS 账户
const deleteCmsAccount = async (id: string) => {
// 直接从 storage 读取最新数据,避免多窗口操作时覆盖
const storage = await chrome.storage.local.get('cmsAccounts')
const accounts: CMSAccount[] = storage.cmsAccounts || []
const updated = accounts.filter(a => a.id !== id)
await chrome.storage.local.set({ cmsAccounts: updated })
await chrome.storage.local.remove(`cms_pwd_${id}`)
setCmsAccounts(updated)
}
if (!open) return null
return (
<>
{/* 遮罩 */}
<div
className="fixed inset-0 bg-black/50 z-40"
onClick={onClose}
/>
{/* 抽屉 */}
<div className={cn(
'fixed inset-y-0 right-0 w-80 bg-background z-50 shadow-xl',
'transform transition-transform duration-200',
open ? 'translate-x-0' : 'translate-x-full'
)}>
{/* 头部 */}
<div className="flex items-center justify-between p-4 border-b">
<h2 className="font-semibold">设置</h2>
<button
onClick={onClose}
className="p-1 rounded hover:bg-muted"
>
<X className="w-5 h-5" />
</button>
</div>
{/* 内容 */}
<div className="p-4 space-y-6 overflow-y-auto h-[calc(100%-57px)]">
{/* 同步桥接设置 */}
<div className="space-y-3">
<h3 className="text-sm font-medium text-muted-foreground">同步桥接</h3>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center gap-2">
{mcpStatus.connected ? (
<PlugZap className="w-5 h-5 text-green-500" />
) : (
<Plug className="w-5 h-5 text-muted-foreground" />
)}
<div>
<p className="text-sm font-medium">CLI / MCP 连接</p>
<p className="text-xs text-muted-foreground">
{mcpStatus.enabled
? mcpStatus.connected
? '已连接'
: '等待连接...'
: '未启用'}
</p>
</div>
</div>
<button
onClick={toggleMcp}
disabled={loading}
title="始终连接(已锁定,不可关闭)"
className={cn(
'relative w-11 h-6 rounded-full transition-colors cursor-default',
'bg-primary opacity-100',
loading && 'opacity-50'
)}
>
<span
className={cn(
'absolute top-1 w-4 h-4 rounded-full bg-white transition-transform',
'translate-x-6'
)}
/>
</button>
</div>
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
供 CLI 和 MCP Server 通过 WebSocket 桥接同步文章 —— 始终连接,已锁定不可关闭
</p>
{mcpStatus.token && (
<div className="p-2 bg-muted/50 rounded text-xs">
<p className="text-muted-foreground mb-1">Token:</p>
<code className="block bg-background p-1.5 rounded break-all select-all">
{mcpStatus.token}
</code>
</div>
)}
<div className="p-2 bg-muted/50 rounded text-xs">
<p className="text-muted-foreground mb-1">服务器地址 (留空使用本地默认):</p>
<input
type="text"
value={serverUrlInput}
onChange={(e) => handleServerUrlChange(e.target.value)}
placeholder="ws://192.168.68.19:9600"
className="w-full bg-background p-1.5 rounded border border-border text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
</div>
</div>
{/* 悬浮同步按钮 */}
<div className="space-y-3">
<h3 className="text-sm font-medium text-muted-foreground">网页功能</h3>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div>
<p className="text-sm font-medium">悬浮同步按钮</p>
<p className="text-xs text-muted-foreground">在网页右下角显示快捷同步按钮</p>
</div>
<button
onClick={toggleFloatingButton}
className={cn(
'relative w-11 h-6 rounded-full transition-colors',
floatingButtonEnabled ? 'bg-primary' : 'bg-muted-foreground/30',
)}
>
<span
className={cn(
'absolute top-1 w-4 h-4 rounded-full bg-white transition-transform',
floatingButtonEnabled ? 'translate-x-6' : 'translate-x-1'
)}
/>
</button>
</div>
</div>
{/* CMS 账户 */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground">自建站点</h3>
<button
onClick={() => {
onClose()
window.location.hash = '/add-cms'
}}
className="flex items-center gap-1 text-xs text-primary hover:underline"
>
<Plus className="w-3 h-3" />
添加
</button>
</div>
{cmsAccounts.length === 0 ? (
<p className="text-xs text-muted-foreground text-center py-4">
暂无自建站点
</p>
) : (
<div className="space-y-2">
{cmsAccounts.map(account => (
<div
key={account.id}
className="flex items-center justify-between p-2 bg-muted/50 rounded-lg"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{account.name}</p>
<p className="text-xs text-muted-foreground truncate">{account.url}</p>
</div>
<button
onClick={() => deleteCmsAccount(account.id)}
className="p-1 text-muted-foreground hover:text-destructive"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
</div>
)}
</div>
{/* 历史记录 */}
<div className="space-y-3">
<button
onClick={() => {
onClose()
window.location.hash = '/history'
}}
className="flex items-center justify-between w-full p-3 bg-muted/50 rounded-lg hover:bg-muted"
>
<span className="text-sm font-medium">查看全部历史</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</button>
</div>
</div>
</div>
</>
)
}
@@ -0,0 +1,264 @@
import { useState, useEffect, useRef } from 'react'
import { Plug, PlugZap, Plus, Trash2, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { trackFeatureDiscovery } from '../../lib/analytics'
interface McpStatus {
enabled: boolean
connected: boolean
token?: string
serverUrl?: string
}
interface CMSAccount {
id: string
name: string
type: string
url: string
}
/**
* 设置面板(内联版)—— 从原设置抽屉移出,直接展示在首页上。
* 同步桥接锁定为始终连接,不可关闭。
*/
export function SettingsPanel() {
const [mcpStatus, setMcpStatus] = useState<McpStatus>({ enabled: true, connected: false })
const [cmsAccounts, setCmsAccounts] = useState<CMSAccount[]>([])
const [loading, setLoading] = useState(false)
const [floatingButtonEnabled, setFloatingButtonEnabled] = useState(false)
const [serverUrlInput, setServerUrlInput] = useState('')
const serverUrlTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
// 获取状态(面板常驻,挂载即加载)
useEffect(() => {
// MCP 状态
chrome.runtime.sendMessage({ type: 'MCP_STATUS' }, (response) => {
if (response && !response.error) {
setMcpStatus({
enabled: response.enabled ?? false,
connected: response.connected ?? false,
token: response.token,
serverUrl: response.serverUrl,
})
setServerUrlInput(response.serverUrl || '')
}
})
// CMS 账户
chrome.storage.local.get('cmsAccounts', (result) => {
setCmsAccounts(result.cmsAccounts || [])
})
// 悬浮按钮设置
chrome.storage.local.get('floatingButtonEnabled', (result) => {
setFloatingButtonEnabled(result.floatingButtonEnabled ?? false)
})
}, [])
// MCP 状态轮询 + 通知 background 加速重连
useEffect(() => {
// 通知 background:用户正在关注,加速重连
chrome.runtime.sendMessage({ type: 'MCP_WATCH_START' })
const interval = setInterval(() => {
chrome.runtime.sendMessage({ type: 'MCP_STATUS' }, (response) => {
if (response && !response.error) {
setMcpStatus(prev => ({ ...prev, connected: response.connected ?? false }))
}
})
}, 3000)
return () => {
clearInterval(interval)
// 面板卸载,恢复正常重连策略
chrome.runtime.sendMessage({ type: 'MCP_WATCH_STOP' })
}
}, [])
// 桥接始终连接:点击只确保开启,不会关闭
const toggleMcp = async () => {
if (loading) return
setLoading(true)
try {
chrome.runtime.sendMessage({ type: 'MCP_ENABLE' }, () => {
setMcpStatus(prev => ({ ...prev, enabled: true }))
})
} finally {
setLoading(false)
}
}
// 服务器地址输入(防抖保存)
const handleServerUrlChange = (value: string) => {
setServerUrlInput(value)
trackFeatureDiscovery('mcp_server_url_input', 'home_panel')
if (serverUrlTimer.current) clearTimeout(serverUrlTimer.current)
serverUrlTimer.current = setTimeout(() => {
chrome.storage.local.set({ mcpServerUrl: value }, () => {
chrome.runtime.sendMessage({ type: 'MCP_SET_SERVER_URL', serverUrl: value })
})
}, 600)
}
// 悬浮按钮开关
const toggleFloatingButton = () => {
const next = !floatingButtonEnabled
setFloatingButtonEnabled(next)
chrome.storage.local.set({ floatingButtonEnabled: next })
}
// 删除 CMS 账户
const deleteCmsAccount = (id: string) => {
const next = cmsAccounts.filter(a => a.id !== id)
setCmsAccounts(next)
chrome.storage.local.set({ cmsAccounts: next })
}
return (
<div className="px-4 pt-3 space-y-4">
{/* 同步桥接设置 */}
<div className="space-y-3">
<h3 className="text-sm font-medium text-muted-foreground">同步桥接</h3>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div className="flex items-center gap-2">
{mcpStatus.connected ? (
<PlugZap className="w-5 h-5 text-green-500" />
) : (
<Plug className="w-5 h-5 text-muted-foreground" />
)}
<div>
<p className="text-sm font-medium">CLI / MCP 连接</p>
<p className="text-xs text-muted-foreground">
{mcpStatus.enabled
? mcpStatus.connected
? '已连接'
: '等待连接...'
: '未启用'}
</p>
</div>
</div>
<button
onClick={toggleMcp}
disabled={loading}
title="始终连接(已锁定,不可关闭)"
className={cn(
'relative w-11 h-6 rounded-full transition-colors cursor-default',
'bg-primary opacity-100',
loading && 'opacity-50'
)}
>
<span
className={cn(
'absolute top-1 w-4 h-4 rounded-full bg-white transition-transform',
'translate-x-6'
)}
/>
</button>
</div>
<div className="space-y-2">
<p className="text-xs text-muted-foreground">
供 CLI 和 MCP Server 通过 WebSocket 桥接同步文章 —— 始终连接,已锁定不可关闭
</p>
{mcpStatus.token && (
<div className="p-2 bg-muted/50 rounded text-xs">
<p className="text-muted-foreground mb-1">Token:</p>
<code className="block bg-background p-1.5 rounded break-all select-all">
{mcpStatus.token}
</code>
</div>
)}
<div className="p-2 bg-muted/50 rounded text-xs">
<p className="text-muted-foreground mb-1">服务器地址 (留空使用本地默认):</p>
<input
type="text"
value={serverUrlInput}
onChange={(e) => handleServerUrlChange(e.target.value)}
placeholder="ws://192.168.68.19:9600"
className="w-full bg-background p-1.5 rounded border border-border text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
</div>
</div>
{/* 悬浮同步按钮 */}
<div className="space-y-3">
<h3 className="text-sm font-medium text-muted-foreground">网页功能</h3>
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
<div>
<p className="text-sm font-medium">悬浮同步按钮</p>
<p className="text-xs text-muted-foreground">在网页右下角显示快捷同步按钮</p>
</div>
<button
onClick={toggleFloatingButton}
className={cn(
'relative w-11 h-6 rounded-full transition-colors',
floatingButtonEnabled ? 'bg-primary' : 'bg-muted-foreground/30',
)}
>
<span
className={cn(
'absolute top-1 w-4 h-4 rounded-full bg-white transition-transform',
floatingButtonEnabled ? 'translate-x-6' : 'translate-x-1'
)}
/>
</button>
</div>
</div>
{/* CMS 账户 */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground">自建站点</h3>
<button
onClick={() => { window.location.hash = '/add-cms' }}
className="flex items-center gap-1 text-xs text-primary hover:underline"
>
<Plus className="w-3 h-3" />
添加
</button>
</div>
{cmsAccounts.length === 0 ? (
<p className="text-xs text-muted-foreground text-center py-4">
暂无自建站点
</p>
) : (
<div className="space-y-2">
{cmsAccounts.map(account => (
<div
key={account.id}
className="flex items-center justify-between p-2 bg-muted/50 rounded-lg"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{account.name}</p>
<p className="text-xs text-muted-foreground truncate">{account.url}</p>
</div>
<button
onClick={() => deleteCmsAccount(account.id)}
className="p-1 text-muted-foreground hover:text-destructive"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
</div>
)}
</div>
{/* 历史记录 */}
<div className="space-y-3">
<button
onClick={() => { window.location.hash = '/history' }}
className="flex items-center justify-between w-full p-3 bg-muted/50 rounded-lg hover:bg-muted"
>
<span className="text-sm font-medium">查看全部历史</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</button>
</div>
</div>
)
}
+23 -68
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Settings, Plus, Clock, X, Download, Info, Wifi, Maximize2 } from 'lucide-react'
import { Plus, Clock, X, Download, Info, Wifi, Maximize2 } from 'lucide-react'
import { useSyncStore } from '../stores/sync'
import { SettingsDrawer } from '../components/SettingsDrawer'
import { SettingsPanel } from '../components/SettingsPanel'
import { SyncDialog } from '@/components/sync-dialog'
import type { Platform as DialogPlatform } from '@/components/sync-dialog'
import { cn } from '@/lib/utils'
import { trackPageView, trackFeatureDiscovery } from '../../lib/analytics'
import { trackPageView } from '../../lib/analytics'
import { createLogger } from '../../lib/logger'
import { getCachedUpdateInfo, dismissUpdate, type UpdateCheckResult } from '../../lib/version-check'
@@ -36,14 +36,12 @@ export function HomeNew() {
checkRateLimit,
} = useSyncStore()
const [settingsOpen, setSettingsOpen] = useState(false)
const [rateLimitWarning, setRateLimitWarning] = useState<string | null>(null)
const [allPlatforms, setAllPlatforms] = useState<DialogPlatform[]>([])
const [updateInfo, setUpdateInfo] = useState<UpdateCheckResult | null>(null)
const [floatingEnabled, setFloatingEnabled] = useState(false)
const [isFirstSync, setIsFirstSync] = useState(false)
const [showShareTip, setShowShareTip] = useState(false)
// Load data
useEffect(() => {
@@ -62,12 +60,9 @@ export function HomeNew() {
} catch {}
loadAllPlatforms()
loadArticle()
chrome.storage.local.get(['floatingButtonEnabled', 'syncHistory', 'dismissedShareTip'], (r) => {
chrome.storage.local.get(['floatingButtonEnabled', 'syncHistory'], (r) => {
setFloatingEnabled(r.floatingButtonEnabled ?? false)
setIsFirstSync(!r.syncHistory || r.syncHistory.length === 0)
if (!r.dismissedShareTip) {
setShowShareTip(true)
}
})
const cached = await getCachedUpdateInfo()
if (cached?.hasUpdate && cached.info) {
@@ -107,14 +102,27 @@ export function HomeNew() {
}
// 在独立窗口打开扩展(popup 点外部会自动关闭,独立窗口可常驻保持打开)
// 固定停靠屏幕右侧:贴右缘、占满可用高度(排除任务栏),宽度 440 便于阅读
const handleOpenInWindow = async () => {
const width = 440
const height = screen.availHeight
const left = Math.max(0, screen.availWidth - width)
await chrome.windows.create({
url: chrome.runtime.getURL('src/popup/index.html'),
type: 'popup',
width: 420,
height: 720,
width,
height,
left,
top: 0,
focused: true,
})
window.close()
// 仅在扩展气泡上下文才关自己;侧栏(sidePanel)里 window.close 无效
try {
const ctx: any = await (chrome.runtime as any).getContext?.()
if (ctx?.contextType === 'POPUP') window.close()
} catch {
/* 忽略 */
}
}
// Start sync with rate-limit check
@@ -170,21 +178,11 @@ export function HomeNew() {
<button
onClick={handleOpenInWindow}
className="flex flex-col items-center gap-0.5 px-2 py-1 rounded-lg hover:bg-muted transition-colors"
title="在独立窗口打开(常驻保持,不随点击关闭)"
title="在右侧独立窗口打开(贴屏幕右缘常驻,不随点击关闭)"
>
<Maximize2 className="w-3.5 h-3.5" />
<span className="text-[10px] text-muted-foreground leading-none">窗口</span>
</button>
<button
onClick={() => {
setSettingsOpen(true)
trackFeatureDiscovery('settings', 'header_icon').catch(() => {})
}}
className="flex flex-col items-center gap-0.5 px-2 py-1 rounded-lg hover:bg-muted transition-colors"
>
<Settings className="w-3.5 h-3.5" />
<span className="text-[10px] text-muted-foreground leading-none">设置</span>
</button>
</nav>
</header>
@@ -228,48 +226,8 @@ export function HomeNew() {
</div>
)}
{/* Share / welcome banner (first time only) */}
{showShareTip && (
<div className="px-4 pt-3">
<div className="bg-muted/50 rounded-lg p-3 text-sm relative">
<button
onClick={() => {
setShowShareTip(false)
chrome.storage.local.set({ dismissedShareTip: true })
}}
className="absolute top-2 right-2 text-muted-foreground hover:text-foreground"
>
<X className="w-4 h-4" />
</button>
<p className="font-medium mb-1.5">谢谢支持!</p>
<p className="text-xs text-muted-foreground leading-relaxed">
如果觉得本工具不错,还请分享给你的朋友!
<br />
如果你是开发者,欢迎参与进来{' '}
<a
href="https://github.com/wechatsync/Wechatsync"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
GitHub
</a>
</p>
<hr className="my-2 border-border" />
<p className="text-xs text-muted-foreground text-right">
by{' '}
<a
href="https://fun0.netlify.app/about/?utm_source=wechatsync"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
fun
</a>
</p>
</div>
</div>
)}
{/* 设置(已从抽屉移出,直接内联在首页) */}
<SettingsPanel />
{/* SyncDialog — the unified sync flow */}
<SyncDialog
@@ -316,9 +274,6 @@ export function HomeNew() {
</div>
)}
{/* Settings drawer */}
<SettingsDrawer open={settingsOpen} onClose={() => setSettingsOpen(false)} />
{/* Rate limit warning (non-blocking toast) */}
{rateLimitWarning && (
<div className="fixed top-2 left-2 right-2 z-50 animate-in fade-in slide-in-from-top-2 duration-200">
@@ -18,24 +18,38 @@ const logger = createLogger('MpOnline')
interface MpAccountSummary {
id: string
userName: string
nickName: string
avatar: string
nickName?: string
avatar?: string
enabled: boolean
isCurrent: boolean
status: MpAccountStatus
intervalMinutes: number
intervalMinutes?: number
lastCheckAt?: number
lastOnlineAt?: number
failCount: number
note?: string
/** 会话过期时间(秒级时间戳) */
sessionExpiry?: number | null
cookieCount: number
createdAt: number
}
/** 保活运行记录 */
interface MpRunRecord {
at: number
id: string
status: 'online' | 'expired' | 'offline' | 'error' | 'skipped'
note?: string
expiryBefore?: number | null
expiryAfter?: number | null
}
interface MpState {
accounts: MpAccountSummary[]
targetId: string
alarmPeriodMinutes: number | null
lastRunAt?: number | null
history?: MpRunRecord[]
}
const STATUS_META: Record<MpAccountStatus, { label: string; className: string }> = {
@@ -45,6 +59,14 @@ const STATUS_META: Record<MpAccountStatus, { label: string; className: string }>
unknown: { label: '未检测', className: 'bg-muted text-muted-foreground' },
}
const RUN_STATUS_META: Record<MpRunRecord['status'], string> = {
online: '在线',
expired: '已过期',
offline: '离线',
error: '异常',
skipped: '跳过',
}
function formatTime(ts?: number): string {
if (!ts) return '—'
const d = new Date(ts)
@@ -168,6 +190,7 @@ export function MpOnlinePage() {
})
const accounts = state?.accounts || []
const history = state?.history || []
const onlineCount = accounts.filter((a) => a.status === 'online').length
return (
@@ -197,6 +220,7 @@ export function MpOnlinePage() {
同时保存多个公众号的登录态,后台定时"保活"防止掉线;
保活只用各账号自己的 Cookie,<b>不会影响浏览器当前登录的公众号</b>。
{state?.alarmPeriodMinutes ? ` 当前每 ${state.alarmPeriodMinutes} 分钟自动保活一次。` : ' 有账号开启保活后会自动定时执行。'}
{state?.lastRunAt ? ` 上次自动保活 ${formatTime(state.lastRunAt)}。` : ''}
</div>
{/* 添加 */}
@@ -268,6 +292,7 @@ export function MpOnlinePage() {
</div>
<div className="text-[11px] text-muted-foreground truncate">
{account.userName} · 上次在线 {formatTime(account.lastOnlineAt)}
{account.sessionExpiry ? ` · 会话至 ${formatTime(account.sessionExpiry * 1000)}` : ''}
</div>
</div>
<label className="flex items-center gap-1 text-[11px] text-muted-foreground cursor-pointer">
@@ -337,6 +362,30 @@ export function MpOnlinePage() {
)
})}
{/* 保活运行记录 */}
{history.length > 0 && (
<div className="rounded-lg border p-2.5 space-y-1">
<div className="text-xs text-muted-foreground">保活运行记录(最近 {history.length} 条)</div>
{history.map((h) => (
<div key={`${h.at}-${h.id}`} className="flex items-baseline justify-between gap-2 text-[11px]">
<span className="text-muted-foreground shrink-0">
{formatTime(h.at)} · {RUN_STATUS_META[h.status] || h.status}
</span>
<span className="truncate text-right">
{h.expiryAfter
? `会话至 ${formatTime(h.expiryAfter * 1000)}${
h.expiryBefore && h.expiryAfter > h.expiryBefore ? '(已续期)' : ''
}`
: h.expiryBefore
? `会话至 ${formatTime(h.expiryBefore * 1000)}`
: ''}
{h.note ? ` · ${h.note}` : ''}
</span>
</div>
))}
</div>
)}
{/* 汇总 */}
{accounts.length > 0 && (
<div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">