feat: 提交详情能看 diff,也能丢给 AI 审这一次改动。文件检查可单独排除路径,TODO 只认大写,避免把 todo 表和模块当成待办标记。

热力图按容器宽度铺满一年,不再横向滚动。托盘右键换成可换皮肤的弹层;更新下载显示进度,退出后再由脚本拉起安装器,避免还占着 exe。
This commit is contained in:
李琦
2026-08-19 15:46:03 +08:00
parent 1694397245
commit 7c4109f687
38 changed files with 2618 additions and 129 deletions

View File

@@ -1 +1 @@
bcd40faf16720fe7180c537d7deb93f9
cf71ba1d3af30612c61ba8aa4e42baf4

View File

@@ -1 +1 @@
caf892d1dc4259ca637eae8b231784f9
e2b9b9c981c8af0ab85227959989ae5f

View File

@@ -3,7 +3,6 @@ package main
// admin.go 云端管理员id=1运营后台TOTP/stepup、统计、用户/团队、发版。
import (
"bytes"
"encoding/json"
"errors"
"io"
@@ -253,38 +252,59 @@ func (a *App) AdminUploadRelease(version, channel, changelog, filePath string) (
}
defer f.Close()
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
_ = w.WriteField("version", strings.TrimSpace(version))
_ = w.WriteField("channel", strings.TrimSpace(channel))
_ = w.WriteField("changelog", changelog)
part, e := w.CreateFormFile("file", filepath.Base(filePath))
if e != nil {
return nil, e
}
if _, e = io.Copy(part, f); e != nil {
return nil, errors.New("SAVE_FAILED")
}
_ = w.Close()
base := a.apiBaseURL()
if base == "" {
return nil, errors.New("SYNC_NOT_CONFIGURED")
}
req, e := http.NewRequest(http.MethodPost, base+"/api/v1/admin/releases", &buf)
pr, pw := io.Pipe()
w := multipart.NewWriter(pw)
go func() {
var copyErr error
defer func() {
_ = w.Close()
if copyErr != nil {
_ = pw.CloseWithError(copyErr)
} else {
_ = pw.Close()
}
}()
if e := w.WriteField("version", strings.TrimSpace(version)); e != nil {
copyErr = e
return
}
if e := w.WriteField("channel", strings.TrimSpace(channel)); e != nil {
copyErr = e
return
}
if e := w.WriteField("changelog", changelog); e != nil {
copyErr = e
return
}
part, e := w.CreateFormFile("file", filepath.Base(filePath))
if e != nil {
copyErr = e
return
}
if _, e = io.Copy(part, f); e != nil {
copyErr = errors.New("SAVE_FAILED")
}
}()
req, e := http.NewRequest(http.MethodPost, base+"/api/v1/admin/releases", pr)
if e != nil {
_ = pw.Close()
return nil, errors.New("SYNC_OFFLINE")
}
req.Header.Set("Content-Type", w.FormDataContentType())
tok := strings.TrimSpace(a.store.Meta("sync_access_token"))
if tok == "" {
_ = pw.Close()
return nil, errors.New("SYNC_NOT_LOGGED_IN")
}
req.Header.Set("Authorization", "Bearer "+tok)
for k, v := range headers {
req.Header.Set(k, v)
}
client := &http.Client{Timeout: 10 * time.Minute}
client := &http.Client{Timeout: 20 * time.Minute}
resp, e := client.Do(req)
if e != nil {
return nil, errors.New("SYNC_OFFLINE")

62
ai.go
View File

@@ -11,6 +11,7 @@ import (
"strings"
"time"
"view/service"
"view/service/ai"
)
@@ -145,6 +146,49 @@ type aiStreamEvent struct {
// SendAIMessage 发送一条用户消息并启动流式回复。
// conversationID 为 0 时自动创建会话scenario: chat | project | git | todo | ticket。
func (a *App) SendAIMessage(conversationID, projectID int64, scenario, content string) (AIConversation, error) {
return a.startAIChat(conversationID, projectID, scenario, content, "", "")
}
// SendAIDiffMessage 针对某次提交的 diff 发起 AI 分析;后续同会话追问仍带上该 diff。
func (a *App) SendAIDiffMessage(conversationID, projectID int64, hash, content string) (AIConversation, error) {
hash = strings.TrimSpace(hash)
if hash == "" {
return AIConversation{}, errors.New("GIT_REF_NOT_FOUND")
}
if e := a.ready(); e != nil {
return AIConversation{}, e
}
if projectID <= 0 && conversationID > 0 {
convs, _ := a.store.ListAIConversations(0)
for _, c := range convs {
if c.ID == conversationID {
projectID = c.ProjectID
break
}
}
}
p, e := a.store.GetProject(projectID)
if e != nil {
return AIConversation{}, e
}
d, e := (GitAnalyzer{}).CommitDetail(a.ctx, p.Path, hash)
if e != nil {
return AIConversation{}, e
}
title := strings.TrimSpace(d.Message)
if title == "" {
title = content
}
if r := []rune(title); len(r) > 36 {
title = string(r[:36]) + "…"
}
if !strings.HasPrefix(strings.ToLower(title), "diff") {
title = "Diff: " + title
}
return a.startAIChat(conversationID, projectID, "diff", content, service.FormatCommitDiffForAI(d, 0), title)
}
func (a *App) startAIChat(conversationID, projectID int64, scenario, content, extraSystem, title string) (AIConversation, error) {
if e := a.ready(); e != nil {
return AIConversation{}, e
}
@@ -166,7 +210,9 @@ func (a *App) SendAIMessage(conversationID, projectID int64, scenario, content s
var conv AIConversation
if conversationID == 0 {
title := content
if strings.TrimSpace(title) == "" {
title = content
}
if r := []rune(title); len(r) > 40 {
title = string(r[:40]) + "…"
}
@@ -197,9 +243,19 @@ func (a *App) SendAIMessage(conversationID, projectID int64, scenario, content s
a.aiStreams[conv.ID] = cancel
a.mu.Unlock()
// 组装消息:场景系统提示词 + 最近历史 + 本条用户消息。
sys := a.buildAIContext(projectID, scenario, st.Locale)
if extraSystem != "" {
sys = strings.TrimRight(sys, "\n") + "\n\n" + extraSystem
if scenario == "diff" {
if st.Locale == "en" {
sys += "\nTask: Review this commit's diff. Cover intent, risks, missing tests, and brief improvements. Use only the diff above; do not invent changes.\n"
} else {
sys += "\n任务审查这次提交的 diff说明改动意图、潜在风险、遗漏测试并给出简要改进建议。只依据上面的 diff不要编造未出现的改动。\n"
}
}
}
history, _ := a.store.ListAIMessages(conv.ID)
msgs := []ai.Message{{Role: "system", Content: a.buildAIContext(projectID, scenario, st.Locale)}}
msgs := []ai.Message{{Role: "system", Content: sys}}
if len(history) > 20 {
history = history[len(history)-20:]
}

33
app.go
View File

@@ -335,7 +335,8 @@ func (a *App) RefreshProjectInsights(id int64) (ProjectInsights, error) {
return ProjectInsights{}, e
}
git, _ := a.store.GitStats(id)
x, e := (service.InsightService{}).Analyze(a.ctx, p, structure, git)
excludes, _ := a.store.InsightExcludes(id)
x, e := (service.InsightService{}).Analyze(a.ctx, p, structure, git, excludes)
if e != nil {
a.store.Log("error", "项目检查", "深度检查失败", p.Name+" | "+e.Error())
return x, e
@@ -438,12 +439,35 @@ func (a *App) DeleteRule(id int64) error {
return a.store.DeleteRule(id)
}
// GetProjectRules 项目专属排除规则(不含全局)。
// GetProjectRules 项目专属排除规则(不含全局、不含检查专用排除)。
func (a *App) GetProjectRules(projectID int64) ([]ExclusionRule, error) {
if e := a.ready(); e != nil {
return nil, e
}
return a.store.ProjectRules(projectID)
all, e := a.store.ProjectRules(projectID)
if e != nil {
return nil, e
}
return withoutRuleCategory(all, "insight"), nil
}
// GetInsightExcludes 文件检查专用排除(不影响行数统计)。
func (a *App) GetInsightExcludes(projectID int64) ([]ExclusionRule, error) {
if e := a.ready(); e != nil {
return nil, e
}
return a.store.InsightExcludes(projectID)
}
// AddInsightExclude 添加仅对文件检查生效的排除路径。
func (a *App) AddInsightExclude(projectID int64, pattern string) (ExclusionRule, error) {
if e := a.ready(); e != nil {
return ExclusionRule{}, e
}
if projectID <= 0 {
return ExclusionRule{}, errors.New("PROJECT_REQUIRED")
}
return a.store.AddProjectRule(projectID, pattern, "insight")
}
// AddProjectRule 给某项目添加专属排除规则。
@@ -454,6 +478,9 @@ func (a *App) AddProjectRule(projectID int64, pattern, category string) (Exclusi
if projectID <= 0 {
return ExclusionRule{}, errors.New("PROJECT_REQUIRED")
}
if category == "insight" {
category = "custom"
}
return a.store.AddProjectRule(projectID, pattern, category)
}
func (a *App) GetLogs(level string) ([]LogEntry, error) {

View File

@@ -620,9 +620,28 @@ func (s *Store) ProjectRules(projectID int64) ([]ExclusionRule, error) {
return s.queryRules(`SELECT id,pattern,category,builtin,project_id FROM exclusion_rules WHERE project_id=? ORDER BY category,pattern`, projectID)
}
// RulesForProject 扫描用:全局规则 + 项目专属规则叠加。
// RulesForProject 扫描用:全局规则 + 项目专属规则叠加(不含检查专用排除)
func (s *Store) RulesForProject(projectID int64) ([]ExclusionRule, error) {
return s.queryRules(`SELECT id,pattern,category,builtin,project_id FROM exclusion_rules WHERE project_id IN (0,?) ORDER BY project_id,category,builtin DESC,pattern`, projectID)
all, e := s.queryRules(`SELECT id,pattern,category,builtin,project_id FROM exclusion_rules WHERE project_id IN (0,?) ORDER BY project_id,category,builtin DESC,pattern`, projectID)
if e != nil {
return nil, e
}
return withoutRuleCategory(all, "insight"), nil
}
// InsightExcludes 仅用于文件检查的项目排除规则,不影响行数统计。
func (s *Store) InsightExcludes(projectID int64) ([]ExclusionRule, error) {
return s.queryRules(`SELECT id,pattern,category,builtin,project_id FROM exclusion_rules WHERE project_id=? AND category='insight' ORDER BY pattern`, projectID)
}
func withoutRuleCategory(rules []ExclusionRule, category string) []ExclusionRule {
out := []ExclusionRule{}
for _, r := range rules {
if r.Category != category {
out = append(out, r)
}
}
return out
}
func (s *Store) queryRules(q string, args ...any) ([]ExclusionRule, error) {
@@ -659,6 +678,9 @@ func (s *Store) AddProjectRule(projectID int64, pattern, category string) (Exclu
}
r, e := s.db.Exec(`INSERT INTO exclusion_rules(pattern,category,builtin,project_id) VALUES(?,?,0,?)`, pattern, category, projectID)
if e != nil {
if strings.Contains(strings.ToLower(e.Error()), "unique") {
return ExclusionRule{}, errors.New("PATTERN_EXISTS")
}
return ExclusionRule{}, e
}
id, _ := r.LastInsertId()
@@ -788,7 +810,7 @@ func (s *Store) LogCategories() ([]string, error) {
}
func (s *Store) Settings() (AppSettings, error) {
x := AppSettings{DatabasePath: s.path, Theme: "dark", Locale: "zh-CN", GitScope: "current", AutoRefresh: true, GlassOpacity: 55, LoadingStyle: "fullscreen-orbit",
MinimizeToTray: true, AutoUpdateMode: "daily", AutoUpdateInterval: 1, AutoUpdateTime: "09:00", AIProvider: "spark", ImageMode: "base64", ProjectSyncMode: "auto"}
MinimizeToTray: true, TrayMenuStyle: "native", AutoUpdateMode: "daily", AutoUpdateInterval: 1, AutoUpdateTime: "09:00", AIProvider: "spark", ImageMode: "base64", ProjectSyncMode: "auto"}
r, e := s.db.Query(`SELECT key,value FROM settings`)
if e != nil {
return x, e
@@ -816,6 +838,10 @@ func (s *Store) Settings() (AppSettings, error) {
}
case "minimizeToTray":
x.MinimizeToTray = v == "true"
case "trayMenuStyle":
if validTrayMenuStyle(v) {
x.TrayMenuStyle = normalizeTrayMenuStyle(v)
}
case "autoUpdateEnabled":
x.AutoUpdateEnabled = v == "true"
case "autoUpdateMode":
@@ -865,6 +891,11 @@ func (s *Store) SaveSettings(x AppSettings) error {
if !validLoadingStyle(x.LoadingStyle) {
x.LoadingStyle = "fullscreen-orbit"
}
if !validTrayMenuStyle(x.TrayMenuStyle) {
x.TrayMenuStyle = "native"
} else {
x.TrayMenuStyle = normalizeTrayMenuStyle(x.TrayMenuStyle)
}
if x.AutoUpdateInterval < 1 || x.AutoUpdateInterval > 720 {
x.AutoUpdateInterval = 1
}
@@ -884,7 +915,7 @@ func (s *Store) SaveSettings(x AppSettings) error {
x.ProjectSyncMode = "auto"
}
vals := map[string]string{"theme": x.Theme, "locale": x.Locale, "gitScope": x.GitScope, "autoRefresh": fmt.Sprint(x.AutoRefresh), "glassOpacity": strconv.Itoa(x.GlassOpacity), "loadingStyle": x.LoadingStyle, "loadingStyleSet": "true",
"minimizeToTray": fmt.Sprint(x.MinimizeToTray), "autoUpdateEnabled": fmt.Sprint(x.AutoUpdateEnabled), "autoUpdateMode": x.AutoUpdateMode, "autoUpdateInterval": strconv.Itoa(x.AutoUpdateInterval), "autoUpdateTime": x.AutoUpdateTime,
"minimizeToTray": fmt.Sprint(x.MinimizeToTray), "trayMenuStyle": x.TrayMenuStyle, "autoUpdateEnabled": fmt.Sprint(x.AutoUpdateEnabled), "autoUpdateMode": x.AutoUpdateMode, "autoUpdateInterval": strconv.Itoa(x.AutoUpdateInterval), "autoUpdateTime": x.AutoUpdateTime,
"aiProvider": x.AIProvider, "sparkKey": x.SparkKey, "deepSeekKey": x.DeepSeekKey, "syncApiKeys": fmt.Sprint(x.SyncAPIKeys),
"avatarMode": x.AvatarMode, "avatarValue": x.AvatarValue, "imageMode": x.ImageMode, "projectSyncMode": x.ProjectSyncMode}
if x.AvatarMode != "base64" && x.AvatarMode != "url" && x.AvatarMode != "path" {
@@ -933,6 +964,26 @@ func validLoadingStyle(v string) bool {
return false
}
}
func validTrayMenuStyle(v string) bool {
switch v {
case "native", "liquid", "glass", "compact", "minimal", "status", "neon":
return true
default:
return false
}
}
func normalizeTrayMenuStyle(v string) string {
if v == "minimal" {
return "compact"
}
if !validTrayMenuStyle(v) {
return "native"
}
return v
}
func (s *Store) ClearData(mode string, projectID int64) error {
tx, e := s.db.Begin()
if e != nil {

View File

@@ -255,6 +255,56 @@ func TestLoadingStylePersistsAndValidates(t *testing.T) {
}
}
func TestTrayMenuStylePersistsAndValidates(t *testing.T) {
s, e := OpenStore(filepath.Join(t.TempDir(), "settings.db"))
if e != nil {
t.Fatal(e)
}
defer s.db.Close()
if e = s.SaveSettings(AppSettings{Theme: "dark", Locale: "zh-CN", GitScope: "current", AutoRefresh: true, GlassOpacity: 55, TrayMenuStyle: "glass"}); e != nil {
t.Fatal(e)
}
got, e := s.Settings()
if e != nil {
t.Fatal(e)
}
if got.TrayMenuStyle != "glass" {
t.Fatalf("trayMenuStyle=%q", got.TrayMenuStyle)
}
if e = s.SaveSettings(AppSettings{GlassOpacity: 55, TrayMenuStyle: "fancy"}); e != nil {
t.Fatal(e)
}
got, e = s.Settings()
if e != nil {
t.Fatal(e)
}
if got.TrayMenuStyle != "native" {
t.Fatalf("invalid trayMenuStyle did not reset: %q", got.TrayMenuStyle)
}
if e = s.SaveSettings(AppSettings{GlassOpacity: 55, TrayMenuStyle: "minimal"}); e != nil {
t.Fatal(e)
}
got, e = s.Settings()
if e != nil {
t.Fatal(e)
}
if got.TrayMenuStyle != "compact" {
t.Fatalf("minimal alias=%q", got.TrayMenuStyle)
}
for _, style := range []string{"native", "liquid", "glass", "compact", "status", "neon"} {
if e = s.SaveSettings(AppSettings{GlassOpacity: 55, TrayMenuStyle: style}); e != nil {
t.Fatal(e)
}
got, e = s.Settings()
if e != nil {
t.Fatal(e)
}
if got.TrayMenuStyle != style {
t.Fatalf("trayMenuStyle=%q want %q", got.TrayMenuStyle, style)
}
}
}
func TestMigrateSkippedWhenVersionCurrent(t *testing.T) {
db := filepath.Join(t.TempDir(), "versioned.db")
s, e := OpenStore(db)

763
frontend/public/tray.html Normal file
View File

@@ -0,0 +1,763 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=300, initial-scale=1" />
<title>Tray</title>
<style>
:root {
--bg: #141b26;
--panel: #19212b;
--text: #f4f5f8;
--muted: #929bac;
--line: rgba(255,255,255,.08);
--hover: rgba(255,255,255,.07);
--accent: #6ee7ff;
--violet: #7367f5;
--ok: #43c996;
--warn: #e7bd35;
--danger: #f05e68;
}
html, body {
margin: 0;
width: 300px;
height: 348px;
overflow: hidden;
background: var(--bg);
color: var(--text);
font: 650 12px/1.35 "Segoe UI Variable", "Segoe UI", Nunito, sans-serif;
-webkit-font-smoothing: antialiased;
text-rendering: geometricPrecision;
user-select: none;
}
html[data-theme=light] {
--bg: #eef1f6;
--panel: #fff;
--text: #111827;
--muted: #526071;
--line: rgba(15,23,42,.08);
--hover: rgba(15,23,42,.05);
}
#app {
box-sizing: border-box;
width: 300px;
height: 348px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
}
button {
border: 0;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
text-align: left;
}
.head {
display: flex;
align-items: center;
gap: 8px;
min-height: 28px;
padding: 0 8px;
flex: none;
}
.head b {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 12px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--muted);
box-shadow: 0 0 0 3px rgba(146,155,172,.14);
flex: none;
}
.st-online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(67,201,150,.16); }
.st-offline .dot { background: var(--warn); box-shadow: 0 0 0 3px rgba(231,189,53,.14); }
.st-error .dot { background: var(--danger); box-shadow: 0 0 0 3px rgba(240,94,104,.14); }
.st-syncing .dot { background: #4f9df5; box-shadow: 0 0 0 3px rgba(79,157,245,.14); }
.badge {
min-width: 18px;
height: 18px;
padding: 0 6px;
border-radius: 999px;
background: rgba(115,103,245,.16);
color: #c4bfff;
font-size: 10px;
font-weight: 700;
font-variant-numeric: tabular-nums;
display: grid;
place-items: center;
}
.badge.due { background: rgba(231,189,53,.16); color: var(--warn); }
.item {
position: relative;
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
color: inherit;
transition: background .16s ease, color .16s ease;
}
.item:hover { background: var(--hover); }
.item:focus-visible { outline: 2px solid var(--violet); outline-offset: -2px; }
.item i {
width: 16px;
height: 16px;
flex: none;
color: var(--muted);
display: grid;
place-items: center;
}
.item i svg { width: 15px; height: 15px; display: block; }
.item span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.item.on { background: rgba(115,103,245,.12); }
.item.on i { color: #c4bfff; }
.item.danger, .item.danger i { color: var(--danger); }
.sec {
margin: 2px 4px 0;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: .4px;
}
.projects { display: flex; flex-wrap: wrap; gap: 4px; }
.chip {
max-width: 100%;
padding: 4px 8px;
border-radius: 999px;
background: var(--hover);
font-size: 11px;
}
html.skin-liquid, body.skin-liquid {
background:
radial-gradient(140px 90px at 8% -10%, rgba(255,255,255,.18), transparent 70%),
linear-gradient(180deg, #3a4252, #252b38);
}
.skin-liquid #app { gap: 8px; }
.skin-liquid .head {
height: 32px;
border-radius: 999px;
background: rgba(255,255,255,.1);
}
.skin-liquid .tiles {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
flex: 1;
min-height: 0;
}
.skin-liquid .tile {
height: auto;
min-height: 64px;
padding: 10px 12px;
border-radius: 16px;
background: rgba(255,255,255,.08);
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
}
.skin-liquid .tile i {
width: 28px;
height: 28px;
border-radius: 9px;
background: rgba(255,255,255,.1);
color: #e8eef8;
}
.skin-liquid .tile i svg { width: 16px; height: 16px; }
.skin-liquid .tile span { font-size: 12px; }
.skin-liquid .dock {
display: flex;
justify-content: space-between;
gap: 6px;
}
.skin-liquid .dock .item {
flex: 1;
height: 36px;
justify-content: center;
border-radius: 12px;
background: rgba(255,255,255,.07);
}
.skin-liquid .dock .item span { display: none; }
.skin-liquid .foot {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 6px;
margin-top: auto;
}
.skin-liquid .foot .item {
height: 30px;
justify-content: center;
border-radius: 999px;
font-size: 11px;
}
html.skin-glass, body.skin-glass {
background:
radial-gradient(180px 120px at 100% 0%, rgba(115,103,245,.18), transparent 60%),
linear-gradient(180deg, #2a3342, #171d27);
}
.skin-glass #app { padding: 10px; gap: 8px; }
.skin-glass .head {
height: 36px;
padding: 0 12px;
border-radius: 10px;
background: rgba(255,255,255,.06);
}
.skin-glass .head b { font-size: 13px; font-weight: 700; }
.skin-glass .qs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.skin-glass .qs-tile {
height: 56px;
padding: 0 12px;
border-radius: 12px;
background: rgba(25,33,43,.82);
box-shadow: inset 0 1px 0 rgba(255,255,255,.06);
}
.skin-glass .qs-tile i {
width: 28px;
height: 28px;
border-radius: 8px;
background: rgba(115,103,245,.2);
color: #c4bfff;
}
.skin-glass .qs-tile i svg { width: 16px; height: 16px; }
.skin-glass .qs-tile span { font-size: 13px; font-weight: 700; }
.skin-glass .qs-tile:hover { background: rgba(36,46,60,.95); }
.skin-glass .sys {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 6px;
padding: 6px;
border-radius: 12px;
background: rgba(25,33,43,.7);
}
.skin-glass .sys .item {
height: 36px;
justify-content: center;
border-radius: 8px;
}
.skin-glass .sys .item span { display: none; }
.skin-glass .sys .item i { width: 18px; height: 18px; color: #c5cbe0; }
.skin-glass .sys .item:hover { background: rgba(255,255,255,.08); }
.skin-glass .quit {
height: 32px;
justify-content: center;
border-radius: 10px;
color: #f05e68;
background: rgba(240,94,104,.08);
}
html.skin-compact, body.skin-compact { background: #11151c; }
.skin-compact #app { padding: 10px 8px 8px; gap: 6px; }
.skin-compact .head { min-height: 20px; padding: 0 6px; }
.skin-compact .head b { font-size: 11px; color: var(--muted); font-weight: 600; }
.skin-compact .pad {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px 2px;
}
.skin-compact .item {
flex-direction: column;
justify-content: center;
gap: 6px;
height: 76px;
border-radius: 10px;
font-size: 10px;
font-weight: 700;
letter-spacing: .2px;
text-align: center;
}
.skin-compact .item i {
width: 36px;
height: 36px;
border-radius: 12px;
background: #1b2230;
color: #d5dbeb;
}
.skin-compact .item i svg { width: 18px; height: 18px; }
.skin-compact .item:hover { background: transparent; }
.skin-compact .item:hover i { background: #252e40; }
.skin-compact .quit {
height: 24px;
justify-content: center;
color: var(--muted);
font-size: 11px;
font-weight: 600;
}
.skin-compact .quit i { display: none; }
html.skin-status, body.skin-status { background: #19212b; }
.skin-status #app { padding: 10px; gap: 8px; }
.skin-status .hero { display: flex; flex-direction: column; gap: 8px; flex: none; }
.skin-status .hero-user {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
height: 24px;
padding: 0 2px;
border-radius: 6px;
}
.skin-status .hero-user:hover { background: var(--hover); }
.skin-status .hero-user:focus-visible { outline: 2px solid var(--violet); outline-offset: 1px; }
.skin-status .hero-user b {
min-width: 0;
font-size: 13px;
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.skin-status .metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.skin-status .metric {
display: flex;
align-items: baseline;
gap: 8px;
height: 40px;
padding: 0 12px;
border-radius: 10px;
background: #222b38;
transition: background .16s ease;
}
.skin-status .metric:hover { background: #2a3546; }
.skin-status .metric:focus-visible { outline: 2px solid var(--violet); outline-offset: 1px; }
.skin-status .metric strong {
font-size: 18px;
font-weight: 750;
font-variant-numeric: tabular-nums;
color: #c4bfff;
line-height: 1;
}
.skin-status .metric.due strong { color: #e7bd35; }
.skin-status .metric.empty strong { color: #6b7384; }
.skin-status .metric span { font-size: 11px; color: var(--muted); }
.skin-status .focus,
.skin-status .open { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; flex: none; }
.skin-status .focus .item,
.skin-status .work .item,
.skin-status .open .item {
height: 48px;
padding: 0 12px;
border-radius: 10px;
background: #222b38;
font-size: 13px;
font-weight: 700;
}
.skin-status .focus .item i { width: 18px; height: 18px; color: #c4bfff; }
.skin-status .focus .item i svg { width: 17px; height: 17px; }
.skin-status .work {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 6px;
flex: 1;
min-height: 0;
}
.skin-status .work .item { height: auto; min-height: 0; font-size: 12px; font-weight: 650; }
.skin-status .work .item i { color: #b8c0d4; }
.skin-status .open .item {
height: 34px;
background: rgba(255,255,255,.04);
font-size: 12px;
font-weight: 650;
}
.skin-status .item:hover { background: #2a3546; }
.skin-status .open .item:hover { background: rgba(255,255,255,.08); }
.skin-status .item.on { background: rgba(115,103,245,.14); }
.skin-status .item.on i { color: #c4bfff; }
.skin-status .projects { padding: 0 2px; }
.skin-status .foot { display: flex; flex-direction: column; gap: 4px; flex: none; }
.skin-status .sys { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
.skin-status .sys .item {
height: 32px;
justify-content: center;
gap: 5px;
border-radius: 8px;
font-size: 10px;
font-weight: 650;
color: var(--muted);
}
.skin-status .sys .item i { color: #929bac; }
.skin-status .sys .item:hover { background: #222b38; color: var(--text); }
.skin-status .quit {
height: 26px;
justify-content: center;
border-radius: 8px;
color: #f05e68;
font-size: 12px;
}
.skin-status .quit:hover { background: rgba(240,94,104,.1); }
html.skin-neon, body.skin-neon { background: #151b24; }
.skin-neon #app { padding: 0; gap: 0; }
.skin-neon .head {
height: 40px;
padding: 0 12px;
border-bottom: 1px solid #303949;
background: #151b24;
}
.skin-neon .head b { font-size: 13px; font-weight: 700; color: #f4f5f8; }
.skin-neon .split {
display: grid;
grid-template-columns: 56px 1fr;
min-height: 0;
flex: 1;
}
.skin-neon .rail {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
border-right: 1px solid #303949;
background: #121820;
}
.skin-neon .rail .item {
flex: 1;
justify-content: center;
border-radius: 10px;
border: 0;
background: transparent;
}
.skin-neon .rail .item span {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0,0,0,0);
}
.skin-neon .rail .item i { width: 18px; height: 18px; color: #929bac; }
.skin-neon .rail .item i svg { width: 18px; height: 18px; }
.skin-neon .rail .item:hover,
.skin-neon .rail .item.on { background: #252e40; }
.skin-neon .rail .item:hover i,
.skin-neon .rail .item.on i { color: #c4bfff; }
.skin-neon .side {
display: flex;
flex-direction: column;
min-width: 0;
padding: 4px 8px 6px;
}
.skin-neon .sec {
margin: 4px 8px 0;
height: 14px;
line-height: 14px;
color: #929bac;
font-size: 10px;
font-weight: 700;
letter-spacing: .08em;
}
.skin-neon .list { display: flex; flex-direction: column; gap: 1px; }
.skin-neon .list .item {
height: 28px;
padding: 0 10px;
border-radius: 8px;
border-bottom: 0;
}
.skin-neon .list .item i { color: #929bac; }
.skin-neon .item:hover { background: rgba(255,255,255,.06); }
.skin-neon .item.on { background: rgba(115,103,245,.12); box-shadow: none; }
.skin-neon .item.on i { color: #c4bfff; }
.skin-neon .quit {
height: 28px;
margin-top: auto;
justify-content: flex-start;
padding: 0 10px;
border-top: 1px solid #303949;
border-radius: 0;
color: #f05e68;
}
.skin-neon .quit i { color: inherit; }
.skin-neon .quit:hover { background: rgba(240,94,104,.1); }
html[data-theme=light].skin-liquid, html[data-theme=light] body.skin-liquid {
background: linear-gradient(180deg, #f7f8fb, #e7ebf2);
color: #0f172a;
}
html[data-theme=light] .skin-liquid .tile,
html[data-theme=light] .skin-liquid .dock .item,
html[data-theme=light] .skin-liquid .head { background: rgba(255,255,255,.72); }
html[data-theme=light].skin-glass, html[data-theme=light] body.skin-glass {
background: linear-gradient(180deg, #f3f5f8, #e4e8ef);
color: #111827;
}
html[data-theme=light] .skin-glass .head,
html[data-theme=light] .skin-glass .qs-tile,
html[data-theme=light] .skin-glass .sys { background: rgba(255,255,255,.86); }
html[data-theme=light] .skin-glass .qs-tile i { background: rgba(115,103,245,.12); color: #7367f5; }
html[data-theme=light].skin-compact, html[data-theme=light] body.skin-compact { background: #f4f6fa; color: #111827; }
html[data-theme=light] .skin-compact .item i { background: #fff; color: #3b4556; }
html[data-theme=light].skin-status, html[data-theme=light] body.skin-status { background: #fff; color: #111827; }
html[data-theme=light] .skin-status .metric,
html[data-theme=light] .skin-status .focus .item,
html[data-theme=light] .skin-status .work .item { background: #f3f5f8; }
html[data-theme=light] .skin-status .metric:hover,
html[data-theme=light] .skin-status .item:hover { background: #e8edf4; }
html[data-theme=light] .skin-status .open .item { background: #f6f7fa; }
html[data-theme=light] .skin-status .open .item:hover { background: #e8edf4; }
html[data-theme=light] .skin-status .metric strong { color: #6557e8; }
html[data-theme=light] .skin-status .metric.due strong { color: #9a7b12; }
html[data-theme=light] .skin-status .metric.empty strong { color: #8a93a3; }
html[data-theme=light] .skin-status .focus .item i { color: #6557e8; }
html[data-theme=light] .skin-status .work .item i,
html[data-theme=light] .skin-status .sys .item i { color: #526071; }
html[data-theme=light] .skin-status .item.on { background: rgba(101,87,232,.1); }
html[data-theme=light] .skin-status .item.on i { color: #6557e8; }
html[data-theme=light] .skin-status .sys .item:hover { background: #f3f5f8; }
html[data-theme=light] .skin-status .quit { color: #dc3d4a; }
html[data-theme=light] .skin-status .quit:hover { background: rgba(220,61,74,.08); }
@media (prefers-reduced-motion: reduce) {
.item { transition: none; }
}
html[data-theme=light] .badge { color: #4c3fd4; background: rgba(101,87,232,.12); }
html[data-theme=light].skin-neon, html[data-theme=light] body.skin-neon { background: #fff; color: #111827; }
html[data-theme=light] .skin-neon .head,
html[data-theme=light] .skin-neon .rail { background: #f6f7fa; border-color: #dce1ea; }
html[data-theme=light] .skin-neon .head b { color: #111827; }
html[data-theme=light] .skin-neon .rail .item i,
html[data-theme=light] .skin-neon .list .item i { color: #526071; }
html[data-theme=light] .skin-neon .rail .item:hover,
html[data-theme=light] .skin-neon .rail .item.on { background: #edf0f6; }
html[data-theme=light] .skin-neon .item.on { background: rgba(101,87,232,.1); }
html[data-theme=light] .skin-neon .quit { border-top-color: #dce1ea; }
</style>
</head>
<body>
<div id="app"></div>
<script type="module">
const { Call, Events } = await import('/wails/runtime.js')
const call = (name, ...args) => Call.ByName('main.App.' + name, ...args)
const app = document.getElementById('app')
let state = { style: 'status', theme: 'dark', locale: 'zh-CN', status: 'signedOut', statusLabel: '未登录', unread: 0, todayDue: 0, autostart: false, projects: [], hasMoreProjects: false }
let projectsOpen = false
let lastSkin = ''
let lastLocale = ''
const zh = {
show: '主窗口', pad: '启动台', today: '今日', todos: '待办', tickets: '工单',
messages: '消息', ai: 'AI 分析', projects: '项目', sync: '同步', batch: '统计',
auto: '自启', restart: '重启', quit: '退出', all: '全部…', work: '事务', system: '系统',
signedOut: '未登录', unreadShort: '未读', dueShort: '到期'
}
const en = {
show: 'Window', pad: 'Launchpad', today: 'Today', todos: 'Todos', tickets: 'Tickets',
messages: 'Inbox', ai: 'AI', projects: 'Projects', sync: 'Sync', batch: 'Analyze',
auto: 'Startup', restart: 'Restart', quit: 'Quit', all: 'All…', work: 'Work', system: 'System',
signedOut: 'Signed out', unreadShort: 'Unread', dueShort: 'Due'
}
const labels = { ...zh }
const icons = {
show: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>',
pad: '<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="6" r="1.7"/><circle cx="12" cy="6" r="1.7"/><circle cx="18" cy="6" r="1.7"/><circle cx="6" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="18" cy="12" r="1.7"/><circle cx="6" cy="18" r="1.7"/><circle cx="12" cy="18" r="1.7"/><circle cx="18" cy="18" r="1.7"/></svg>',
today: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/><path d="m9 16 2 2 4-4"/></svg>',
todos: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 6h13M8 12h13M8 18h13"/><path d="m3 6 1 1 2-2M3 12l1 1 2-2M3 18l1 1 2-2"/></svg>',
tickets: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2M13 17v2M13 11v2"/></svg>',
messages: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 19a2 2 0 0 0 4 0"/></svg>',
ai: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3l1.6 4.8L18 9.4l-4.4 1.6L12 16l-1.6-4.8L6 9.4l4.4-1.6Z"/><path d="M19 15l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7Z"/></svg>',
projects: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',
sync: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-2.6-6.4"/><path d="M21 3v6h-6"/></svg>',
batch: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="M7 16v-5M12 16V8M17 16v-9"/></svg>',
auto: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6 9 17l-5-5"/></svg>',
restart: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="6" height="6" rx="1"/><path d="M4 12a8 8 0 1 0 2.2-5.5"/><path d="M4 4v5h5"/></svg>',
quit: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v10"/><path d="M18.4 6.6a8 8 0 1 1-12.8 0"/></svg>'
}
function skinName() {
const s = state.style === 'minimal' ? 'compact' : (state.style || 'status')
return s === 'native' ? 'status' : s
}
function esc(v) {
return String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}
function cls(key) {
const on = (key === 'projects' && projectsOpen) || (key === 'auto' && state.autostart) ? ' on' : ''
const danger = key === 'quit' ? ' danger' : ''
return `item${on}${danger}`
}
function btn(key, extra) {
const extraAttr = extra ? ` data-extra="${extra}"` : ''
return `<button type="button" class="${cls(key)}${extra ? ' ' + extra : ''}" data-act="${key}" data-key="${key}" title="${esc(labels[key])}"${extraAttr}><i>${icons[key]}</i><span>${esc(labels[key])}</span></button>`
}
function head() {
const badges = (state.unread ? `<em class="badge" data-badge="unread">${esc(state.unread)}</em>` : '<em class="badge" data-badge="unread" hidden></em>') +
(state.todayDue ? `<em class="badge due" data-badge="due">${esc(state.todayDue)}</em>` : '<em class="badge due" data-badge="due" hidden></em>')
return `<header class="head" data-act="sync"><i class="dot"></i><b data-status>${esc(state.statusLabel || labels.signedOut)}</b>${badges}</header>`
}
function projectBlock() {
if (!projectsOpen || !state.projects?.length) return ''
return `<div class="projects" data-projects>${state.projects.map(p =>
`<button type="button" class="chip" data-act="project" data-arg="${esc(p.id)}">${esc(p.name)}</button>`
).join('')}${state.hasMoreProjects ? `<button type="button" class="chip" data-act="nav" data-arg="/projects">${esc(labels.all)}</button>` : ''}</div>`
}
function renderLiquid() {
return head() +
`<div class="tiles">${['show', 'pad', 'today', 'todos'].map(k => btn(k, 'tile')).join('')}</div>` +
`<div class="dock">${['tickets', 'messages', 'ai', 'projects', 'sync'].map(k => btn(k)).join('')}</div>` +
projectBlock() +
`<div class="foot">${['auto', 'restart', 'quit'].map(k => btn(k)).join('')}</div>`
}
function renderGlass() {
return head() +
`<div class="qs">${['today', 'todos', 'tickets', 'messages', 'ai', 'projects'].map(k => btn(k, 'qs-tile')).join('')}</div>` +
`<div class="sys">${['show', 'pad', 'sync', 'batch', 'auto', 'restart'].map(k => btn(k)).join('')}</div>` +
projectBlock() +
btn('quit', 'quit')
}
function renderCompact() {
return head() +
`<div class="pad">${['show', 'pad', 'today', 'todos', 'tickets', 'messages', 'ai', 'projects', 'sync', 'batch', 'auto', 'restart'].map(k => btn(k)).join('')}</div>` +
projectBlock() +
btn('quit', 'quit')
}
function renderStatus() {
const unread = Number(state.unread) || 0
const due = Number(state.todayDue) || 0
return `<section class="hero">` +
`<button type="button" class="hero-user" data-act="sync"><i class="dot" aria-hidden="true"></i><b data-status>${esc(state.statusLabel || labels.signedOut)}</b></button>` +
`<div class="metrics">` +
`<button type="button" class="metric${unread ? '' : ' empty'}" data-act="messages"><strong data-badge="unread">${unread}</strong><span>${esc(labels.unreadShort)}</span></button>` +
`<button type="button" class="metric due${due ? '' : ' empty'}" data-act="today"><strong data-badge="due">${due}</strong><span>${esc(labels.dueShort)}</span></button>` +
`</div>` +
`</section>` +
`<div class="focus">${btn('today', 'focus')}${btn('todos', 'focus')}</div>` +
`<div class="work">${['tickets', 'messages', 'ai', 'projects'].map(k => btn(k, 'work')).join('')}</div>` +
projectBlock() +
`<div class="open">${btn('show', 'open')}${btn('pad', 'open')}</div>` +
`<div class="foot">` +
`<div class="sys">${['sync', 'batch', 'auto', 'restart'].map(k => btn(k, 'sys')).join('')}</div>` +
btn('quit', 'quit') +
`</div>`
}
function renderNeon() {
return head() +
`<div class="split">` +
`<div class="rail">${['show', 'pad', 'today', 'todos'].map(k => btn(k)).join('')}</div>` +
`<div class="side">` +
`<div class="sec">${esc(labels.work)}</div>` +
`<div class="list">${['tickets', 'messages', 'ai', 'projects'].map(k => btn(k)).join('')}</div>` +
`<div class="sec">${esc(labels.system)}</div>` +
`<div class="list">${['sync', 'batch', 'auto', 'restart'].map(k => btn(k)).join('')}</div>` +
projectBlock() +
btn('quit', 'quit') +
`</div>` +
`</div>`
}
function applyChrome() {
const skin = skinName()
document.documentElement.dataset.theme = state.theme === 'light' ? 'light' : 'dark'
document.documentElement.lang = state.locale === 'en' ? 'en' : 'zh-CN'
const clsName = 'skin-' + skin + ' st-' + (state.status || 'signedOut')
document.documentElement.className = clsName
document.body.className = clsName
}
function render() {
const skin = skinName()
applyChrome()
lastSkin = skin
lastLocale = state.locale || ''
const html = {
liquid: renderLiquid,
glass: renderGlass,
compact: renderCompact,
neon: renderNeon
}[skin] || renderStatus
app.innerHTML = html()
}
function patch() {
applyChrome()
const label = app.querySelector('[data-status]')
if (label) label.textContent = state.statusLabel || labels.signedOut
const unread = app.querySelector('[data-badge=unread]')
if (unread) {
const metric = unread.closest('.metric')
unread.textContent = String(state.unread || 0)
if (metric) {
unread.hidden = false
metric.classList.toggle('empty', !state.unread)
} else {
unread.hidden = !state.unread
}
}
const due = app.querySelector('[data-badge=due]')
if (due) {
const metric = due.closest('.metric')
due.textContent = String(state.todayDue || 0)
if (metric) {
due.hidden = false
metric.classList.toggle('empty', !state.todayDue)
} else {
due.hidden = !state.todayDue
}
}
app.querySelectorAll('[data-key]').forEach(el => {
el.className = cls(el.dataset.key) + (el.dataset.extra ? ' ' + el.dataset.extra : '')
})
}
function applyLocale() {
Object.assign(labels, state.locale === 'en' ? en : zh)
}
async function sync(full) {
try {
const next = await call('GetTrayMenuState')
state = { ...state, ...next, projects: next.projects || [] }
applyLocale()
const skin = skinName()
if (full || skin !== lastSkin || (state.locale || '') !== lastLocale) render()
else patch()
} catch {}
}
async function act(action, arg) {
if (action === 'projects') { projectsOpen = !projectsOpen; render(); return }
const map = { show: ['show', ''], pad: ['nav', '/launchpad'], today: ['nav', '/today'], todos: ['nav', '/todos'], tickets: ['nav', '/tickets'], messages: ['nav', '/messages'], ai: ['nav', '/ai'], sync: ['sync', ''], batch: ['batch', ''], auto: ['autostart', ''], restart: ['restart', ''], quit: ['quit', ''], project: ['project', arg], nav: ['nav', arg] }
const pair = map[action]
if (!pair) return
try {
await call('TrayMenuAction', pair[0], String(pair[1] || ''))
if (pair[0] === 'autostart') await sync(false)
} catch {}
}
app.addEventListener('click', ev => {
const btn = ev.target.closest('[data-act]')
if (!btn) return
act(btn.dataset.act, btn.dataset.arg || '')
})
Events.On('tray:refresh', () => sync(false))
Events.On('tray:shown', () => { sync(false) })
await sync(true)
try { await call('TrayPopupReady') } catch {}
</script>
</body>
</html>

View File

@@ -19,6 +19,7 @@ import TeamSwitcher from './components/TeamSwitcher.vue'
import TitleBar from './components/TitleBar.vue'
import CloudClaimModal from './components/CloudClaimModal.vue'
import { call, isNative, on } from './api'
import TrayPopup from './views/TrayPopup.vue'
const route = useRoute()
const router = useRouter()
@@ -30,7 +31,25 @@ const aboutOpen = ref(false)
const exitOpen = ref(false)
const updateInfo = ref(null)
const updateBusy = ref(false)
const updateProgress = ref({ received: 0, total: 0 })
const appVersion = ref('1.0.0')
const updatePercent = computed(() => {
const total = Number(updateProgress.value.total) || 0
const received = Number(updateProgress.value.received) || 0
if (total <= 0) return 0
return Math.min(100, Math.round(received / total * 100))
})
function fmtSize(n) {
n = Number(n) || 0
if (n < 1024) return `${n} B`
if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`
return `${(n / 1048576).toFixed(1)} MB`
}
function errText(e) {
const code = String(e).split(':')[0].trim()
const key = 'errors.' + code
return t(key) !== key ? t(key) : String(e)
}
const displayedTask = ref(null)
let off
let offMenus = []
@@ -41,6 +60,7 @@ const visibleTask = computed(() => activeTask.value || displayedTask.value)
const activeTaskProject = computed(() => visibleTask.value?.params?.project || store.projects.find(p => p.id === visibleTask.value?.projectId)?.name || '')
const loadingStyle = computed(() => store.settings.loadingStyle === 'fullscreen' ? 'fullscreen-orbit' : (store.settings.loadingStyle || 'fullscreen-orbit'))
const useFullscreenLoading = computed(() => loadingStyle.value !== 'bar')
const isTrayWindow = document.documentElement.classList.contains('tray-window')
async function updateSetting(key, value) {
const next = await store.saveSettings({ [key]: value })
@@ -220,6 +240,14 @@ function onGlobalKey(e) {
}
}
onMounted(async () => {
if (isTrayWindow) {
document.documentElement.classList.add('tray-window')
try {
store.applyAppearance(await call('GetSettings'))
locale.value = store.settings.locale || 'zh-CN'
} catch { /* 托盘弹层只需要外观,失败时沿用本地缓存 */ }
return
}
addEventListener('keydown', onGlobalKey)
addEventListener('click', onFlyoutAway)
if (!native) return
@@ -241,6 +269,9 @@ onMounted(async () => {
on('menu:set', p => p?.key && updateSetting(p.key, p.value)),
on('app:update-available', p => {
if (p && !p.upToDate && !p.skipped) updateInfo.value = p
}),
on('app:update-progress', p => {
if (p) updateProgress.value = { received: Number(p.received) || 0, total: Number(p.total) || 0 }
})
]
await store.boot()
@@ -248,15 +279,18 @@ onMounted(async () => {
try { appVersion.value = await call('GetAppVersion') } catch { /* keep fallback */ }
})
async function installUpdate() {
if (updateBusy.value) return
updateBusy.value = true
updateProgress.value = { received: 0, total: Number(updateInfo.value?.sizeBytes) || 0 }
try {
await call('DownloadAndInstallUpdate')
} catch (e) {
store.showToast({ type: 'error', text: String(e) })
store.showToast({ type: 'error', text: errText(e) })
updateBusy.value = false
}
}
async function skipUpdate() {
if (updateBusy.value) return
try { await call('SkipAppUpdate', updateInfo.value?.latest || '') } catch {}
updateInfo.value = null
}
@@ -285,7 +319,8 @@ watch(activeTask, task => {
</script>
<template>
<BrowserBlocked v-if="!native" />
<TrayPopup v-if="isTrayWindow" />
<BrowserBlocked v-else-if="!native" />
<template v-else>
<TitleBar :app-version="appVersion" :shortcuts="pinnedShortcuts" @about="aboutOpen = true" @manage-shortcuts="shortcutPicker = true" />
<DatabaseSetup v-if="store.bootstrap.state !== 'ready' && store.bootstrap.state !== 'loading'" :status="store.bootstrap" class="with-titlebar" />
@@ -382,10 +417,15 @@ watch(activeTask, task => {
<section class="modal exit-modal" @click.stop>
<header class="modal-head">
<h2>{{ t('appUpdateTitle') }}</h2>
<button type="button" class="nm-close" :title="t('close')" @click="skipUpdate"><X /></button>
<button type="button" class="nm-close" :title="t('close')" :disabled="updateBusy" @click="skipUpdate"><X /></button>
</header>
<p class="exit-hint">{{ t('appUpdateBody', { current: updateInfo.current, latest: updateInfo.latest }) }}</p>
<pre v-if="updateInfo.changelog" style="white-space:pre-wrap;font-size:.85rem;opacity:.8;max-height:160px;overflow:auto">{{ updateInfo.changelog }}</pre>
<p class="exit-hint">{{ t('appUpdateHint') }}</p>
<template v-if="updateBusy">
<p class="exit-hint">{{ updateProgress.total > 0 ? t('appUpdateProgress', { received: fmtSize(updateProgress.received), total: fmtSize(updateProgress.total), percent: updatePercent }) : t('appUpdateDownloading') }}</p>
<div class="update-dl-bar" role="progressbar" :aria-valuenow="updatePercent" aria-valuemin="0" aria-valuemax="100"><i :style="{ width: updatePercent + '%' }"/></div>
</template>
<div class="exit-actions">
<button type="button" class="btn secondary" :disabled="updateBusy" @click="skipUpdate">{{ t('appUpdateSkip') }}</button>
<button type="button" class="btn primary" :disabled="updateBusy" @click="installUpdate">{{ updateBusy ? t('appUpdateDownloading') : t('appUpdateInstall') }}</button>

View File

@@ -1,4 +1,80 @@
<script setup>
import{Copy,X,FileCode2}from'lucide-vue-next';import{useI18n}from'vue-i18n'
defineProps({detail:Object,loading:Boolean});const emit=defineEmits(['close']),{t}=useI18n();async function copy(v){await navigator.clipboard.writeText(v)}
</script><template><div class="drawer-mask" @click.self="emit('close')"><aside class="commit-drawer"><header><div><small>{{t('commitDetail')}}</small><h2>{{detail?.message||'...'}}</h2></div><button @click="emit('close')"><X/></button></header><div v-if="loading" class="empty">Loading...</div><template v-else-if="detail"><div class="commit-meta"><code>{{detail.hash}}</code><button :title="t('copyHash')" @click="copy(detail.hash)"><Copy/></button><span>{{detail.author}} · {{detail.email}}</span><time>{{detail.date}}</time><b class="positive">+{{detail.added}}</b><b class="negative">-{{detail.deleted}}</b></div><h3>{{t('filesChanged')}} ({{detail.files?.length||0}})</h3><div class="change-file" v-for="f in detail.files" :key="f.path"><FileCode2/><span>{{f.path}}</span><small>{{f.status}}</small><b class="positive">+{{f.added}}</b><b class="negative">-{{f.deleted}}</b></div></template></aside></div></template>
import { ref, watch } from 'vue'
import { Copy, X, FileCode2, Sparkles } from 'lucide-vue-next'
import { useI18n } from 'vue-i18n'
const props = defineProps({ detail: Object, loading: Boolean })
const emit = defineEmits(['close', 'analyze'])
const { t } = useI18n()
const open = ref('')
watch(() => [props.detail?.hash, props.detail?.files?.length], () => {
const files = props.detail?.files || []
const first = files.find(f => f.patch || f.binary)
open.value = first?.path || ''
})
async function copy(v) {
await navigator.clipboard.writeText(v)
}
function toggle(file) {
open.value = open.value === file.path ? '' : file.path
}
function diffLines(patch) {
return String(patch || '').split('\n').map(text => {
let kind = 'ctx'
if (text.startsWith('+++') || text.startsWith('---') || text.startsWith('@@')) kind = 'meta'
else if (text.startsWith('+')) kind = 'add'
else if (text.startsWith('-')) kind = 'del'
return { kind, text: text || ' ' }
})
}
</script>
<template>
<div class="drawer-mask" @click.self="emit('close')">
<aside class="commit-drawer">
<header>
<div>
<small>{{ t('commitDetail') }}</small>
<h2>{{ detail?.message || '...' }}</h2>
</div>
<div class="commit-drawer-acts">
<button type="button" class="commit-drawer-ai" :disabled="!detail?.hash || loading" :title="t('aiAnalyzeDiff')" @click="emit('analyze', detail)">
<Sparkles />{{ t('aiAnalyzeDiff') }}
</button>
<button type="button" @click="emit('close')"><X /></button>
</div>
</header>
<div v-if="loading" class="empty">Loading...</div>
<template v-else-if="detail">
<div class="commit-meta">
<code>{{ detail.hash }}</code>
<button type="button" :title="t('copyHash')" @click="copy(detail.hash)"><Copy /></button>
<span>{{ detail.author }} · {{ detail.email }}</span>
<time>{{ detail.date }}</time>
<b class="positive">+{{ detail.added }}</b>
<b class="negative">-{{ detail.deleted }}</b>
</div>
<h3>{{ t('filesChanged') }} ({{ detail.files?.length || 0 }})</h3>
<template v-for="f in detail.files" :key="f.path">
<button type="button" class="change-file" :class="{ open: open === f.path }" @click="toggle(f)">
<FileCode2 />
<span>{{ f.path }}</span>
<small>{{ f.status }}</small>
<b class="positive">+{{ f.added }}</b>
<b class="negative">-{{ f.deleted }}</b>
</button>
<template v-if="open === f.path">
<p v-if="f.binary" class="commit-diff-note">{{ t('binaryFile') }}</p>
<p v-else-if="!f.patch" class="commit-diff-note">{{ t('noDiff') }}</p>
<pre v-else class="commit-diff"><span v-for="(line, i) in diffLines(f.patch)" :key="i" :class="line.kind">{{ line.text }}</span></pre>
<p v-if="f.truncated" class="commit-diff-note">{{ t('diffTruncated') }}</p>
</template>
</template>
</template>
</aside>
</div>
</template>

View File

@@ -1,12 +1,36 @@
<script setup>
import { computed, ref } from 'vue'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps({ days: { type: Array, default: () => [] }, selected: String })
const emit = defineEmits(['select'])
const { locale } = useI18n()
const { locale, t } = useI18n()
const root = ref(null)
const hover = ref(null)
const weekMs = 7 * 24 * 60 * 60 * 1000
const cell = ref(13)
const gap = ref(3)
let ro
function ymd(d) {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
const zhMonths = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
const enMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
function monthText(m) {
return locale.value === 'zh-CN' ? zhMonths[m] : enMonths[m]
}
const weekdays = computed(() => [
t('weekdays.sun'),
t('weekdays.mon'),
t('weekdays.tue'),
t('weekdays.wed'),
t('weekdays.thu'),
t('weekdays.fri'),
t('weekdays.sat'),
])
const matrix = computed(() => {
const end = new Date()
@@ -16,50 +40,98 @@ const matrix = computed(() => {
start.setDate(start.getDate() - start.getDay())
const counts = new Map(props.days.map(x => [x.date, x]))
const cells = []
let week = 0
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
const date = d.toISOString().slice(0, 10)
const date = ymd(d)
const day = counts.get(date)
const count = Number(day?.count || 0)
cells.push({ date, count, added: Number(day?.added || 0), deleted: Number(day?.deleted || 0), week: Math.floor((d - start) / weekMs), dow: d.getDay(), level: Math.min(4, count === 0 ? 0 : count < 2 ? 1 : count < 5 ? 2 : count < 10 ? 3 : 4) })
cells.push({ date, count, added: Number(day?.added || 0), deleted: Number(day?.deleted || 0), week, dow: d.getDay(), level: Math.min(4, count === 0 ? 0 : count < 2 ? 1 : count < 5 ? 2 : count < 10 ? 3 : 4) })
if (d.getDay() === 6) week++
}
const weeks = Math.max(1, ...cells.map(x => x.week + 1))
const labels = []
let lastMonth = -1
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 7)) {
const m = d.getMonth()
if (m !== lastMonth) {
labels.push({ week: Math.floor((d - start) / weekMs), text: d.toLocaleString(locale.value === 'zh-CN' ? 'zh-CN' : 'en', { month: 'short' }) })
lastMonth = m
for (const item of cells) {
const m = Number(item.date.slice(5, 7)) - 1
if (m === lastMonth) continue
const prev = labels[labels.length - 1]
if (prev && prev.week === item.week) {
prev.text = monthText(m)
} else {
if (prev) prev.span = Math.max(1, item.week - prev.week)
labels.push({ week: item.week, span: 1, text: monthText(m) })
}
lastMonth = m
}
return { cells, labels, weeks: Math.max(53, ...cells.map(x => x.week + 1)) }
if (labels.length) labels[labels.length - 1].span = Math.max(1, weeks - labels[labels.length - 1].week)
return { cells, labels, weeks }
})
function pick(cell) {
if (!cell.date) return
emit('select', cell.date === props.selected ? '' : cell.date)
const monthLabels = computed(() => {
const unit = cell.value + gap.value
const total = matrix.value.weeks * unit - gap.value
return matrix.value.labels.map((m, i, arr) => {
const next = arr[i + 1]
let left = m.week * unit
let width = Math.max(24, (next ? next.week * unit : total) - left)
if (left + width > total) {
width = Math.min(width, total)
left = Math.max(0, total - width)
}
return { week: m.week, text: m.text, left, width }
})
})
function fit() {
const el = root.value
if (!el) return
const weeks = matrix.value.weeks || 53
const avail = Math.max(0, el.clientWidth - 34)
const nextGap = avail < 720 ? 2 : 3
const nextCell = Math.floor((avail - (weeks - 1) * nextGap) / weeks)
gap.value = nextGap
cell.value = Math.max(4, Math.min(14, nextCell > 0 ? nextCell : 4))
}
function pick(item) {
if (!item.date) return
emit('select', item.date === props.selected ? '' : item.date)
}
onMounted(() => {
fit()
ro = new ResizeObserver(fit)
if (root.value) ro.observe(root.value)
})
onUnmounted(() => ro?.disconnect())
watch(() => matrix.value.weeks, fit)
</script>
<template>
<div class="heat-grid-wrap" :style="{ '--weeks': matrix.weeks }">
<div ref="root" class="heat-grid-wrap" :style="{ '--weeks': matrix.weeks, '--cell': cell + 'px', '--gap': gap + 'px' }">
<div class="heat-months">
<span v-for="m in matrix.labels" :key="m.week + m.text" :style="{ gridColumnStart: m.week + 1 }">{{ m.text }}</span>
<span v-for="m in monthLabels" :key="m.week + m.text" :style="{ left: m.left + 'px', width: m.width + 'px' }">{{ m.text }}</span>
</div>
<div class="heat-body">
<div class="heat-weekdays"><span>S</span><span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span>S</span></div>
<div class="heat-weekdays"><span v-for="(d, i) in weekdays" :key="i">{{ d }}</span></div>
<div class="heat-grid">
<button
v-for="cell in matrix.cells"
:key="cell.date"
v-for="item in matrix.cells"
:key="item.date"
type="button"
class="heat-cell"
:class="['l' + cell.level, { selected: cell.date === props.selected }]"
:style="{ gridColumnStart: cell.week + 1, gridRowStart: cell.dow + 1 }"
@mouseenter="hover = cell"
:class="['l' + item.level, { selected: item.date === selected }]"
:style="{ gridColumnStart: item.week + 1, gridRowStart: item.dow + 1 }"
:title="item.date"
@mouseenter="hover = item"
@mouseleave="hover = null"
@click="pick(cell)"
@click="pick(item)"
/>
</div>
<div v-if="hover" class="heat-tooltip">{{ hover.date }} · {{ hover.count }} {{ locale === 'zh-CN' ? '次提交' : 'commits' }}<template v-if="hover.count"> · <b class="positive">+{{ hover.added }}</b> <b class="negative">-{{ hover.deleted }}</b></template></div>
</div>
<p class="heat-tip">
<template v-if="hover">{{ hover.date }} · {{ hover.count }} {{ t('commitsUnit') }}<template v-if="hover.count"> · <b class="positive">+{{ hover.added }}</b> <b class="negative">-{{ hover.deleted }}</b></template></template>
<template v-else>{{ t('heatHint') }}</template>
</p>
</div>
</template>

View File

@@ -13,7 +13,8 @@ import { useAppStore } from '../store'
const props = defineProps({
projectId: { type: Number, required: true },
projectName: { type: String, default: '' },
ask: { type: String, default: '' } // 打开时自动发送的问题
ask: { type: String, default: '' }, // 打开时自动发送的问题
diffHash: { type: String, default: '' } // 非空时按提交 diff 场景提问
})
const emit = defineEmits(['close'])
const router = useRouter()
@@ -27,6 +28,7 @@ const input = ref('')
const streamingId = ref(0)
const streamText = ref('')
const streamError = ref('')
const diffConvId = ref(0)
const listEl = ref(null)
const streamBuf = {}
let offStream = null
@@ -74,7 +76,11 @@ async function send(text, scen) {
if (!content || streaming.value) return
streamError.value = ''
try {
const conv = await call('SendAIMessage', activeId.value, props.projectId, scen || 'chat', content)
const useDiff = !!props.diffHash && (!activeId.value || activeId.value === diffConvId.value)
const conv = useDiff
? await call('SendAIDiffMessage', activeId.value, props.projectId, props.diffHash, content)
: await call('SendAIMessage', activeId.value, props.projectId, scen || 'chat', content)
if (useDiff) diffConvId.value = conv.id
if (!activeId.value) {
activeId.value = conv.id
await loadConversations()

View File

@@ -1,4 +1,4 @@
*{scrollbar-width:thin;scrollbar-color:rgba(145,136,255,.55) transparent}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:rgba(145,136,255,.38);border:2px solid transparent;background-clip:padding-box;border-radius:8px}::-webkit-scrollbar-thumb:hover{background:rgba(145,136,255,.7);border:2px solid transparent;background-clip:padding-box}
.wsl-picker{display:flex;gap:8px;margin:12px 24px 0}.wsl-picker select{flex:1;background:var(--glass-soft);border:1px solid var(--border);border-radius:7px;color:var(--text);padding:0 10px}.icon-actions button:disabled{opacity:.5;cursor:not-allowed}
.page{overflow-x:clip}.project-title>div:first-child{min-width:0;flex:1;overflow:hidden}.project-title p{max-width:100%!important}.icon-actions{flex:none;flex-shrink:0}.project-card{min-width:0}
.git-context{display:flex;align-items:center;gap:18px;margin:-8px 0 18px;padding:11px 15px;border:1px solid var(--glass-border);border-radius:7px;background:var(--glass-soft);color:var(--muted)}.git-context span{display:flex;align-items:center;gap:7px}.git-context svg{width:17px;color:#9188ff}.git-context b{color:var(--text)}.heat-panel{height:255px}.heat-panel .chart{height:185px}.branch.interactive{position:relative;padding-right:52px;cursor:pointer;transition:border-color .2s,background .2s}.branch.interactive:hover,.branch.interactive.selected{background:rgba(123,115,255,.12);outline:1px solid rgba(145,136,255,.35)}.checkout-btn{position:absolute;right:12px;top:20px;width:32px;height:32px;border:0;border-radius:6px;background:rgba(123,115,255,.15);color:#9188ff;display:grid;place-items:center;cursor:pointer}.checkout-btn svg{width:16px}.commit{width:100%;border:0;color:var(--text);text-align:left;cursor:pointer}.commit:hover{outline:1px solid rgba(145,136,255,.3)}.git-trend{position:relative}.git-trend>.segments{position:absolute;right:0;top:-38px;z-index:2}.git-trend .chart{height:280px}.drawer-mask{position:fixed;inset:0;z-index:60;background:rgba(0,0,0,.55);backdrop-filter:blur(5px);display:flex;justify-content:flex-end;animation:overlay-in .2s}.commit-drawer{width:min(620px,90vw);height:100%;overflow:auto;background:var(--glass-strong);border-left:1px solid var(--glass-border);box-shadow:-20px 0 50px rgba(0,0,0,.3);padding:26px;animation:drawer-in .3s cubic-bezier(.16,1,.3,1)}.commit-drawer header{display:flex;justify-content:space-between;gap:20px;border-bottom:1px solid var(--border);padding-bottom:18px}.commit-drawer header small{color:var(--muted)}.commit-drawer h2{margin:7px 0 0;font-size:20px}.commit-drawer header button,.commit-meta button{border:0;background:var(--glass-soft);color:var(--text);width:34px;height:34px;border-radius:6px;display:grid;place-items:center;cursor:pointer}.commit-drawer svg{width:17px}.commit-meta{display:grid;grid-template-columns:1fr auto auto auto;gap:10px;align-items:center;margin:20px 0;padding:15px;background:var(--glass-soft);border-radius:7px}.commit-meta code{min-width:0;overflow:hidden;text-overflow:ellipsis}.commit-meta span,.commit-meta time{grid-column:1/3;color:var(--muted)}.change-file{display:grid;grid-template-columns:22px 1fr auto auto auto;gap:10px;align-items:center;padding:11px;border-bottom:1px solid var(--border)}.change-file span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.change-file small{color:var(--muted)}@keyframes drawer-in{from{transform:translateX(100%)}to{transform:none}}@media(prefers-reduced-motion:reduce){.commit-drawer{animation:none}}
.git-context{display:flex;align-items:center;gap:18px;margin:-8px 0 18px;padding:11px 15px;border:1px solid var(--glass-border);border-radius:7px;background:var(--glass-soft);color:var(--muted)}.git-context span{display:flex;align-items:center;gap:7px}.git-context svg{width:17px;color:#9188ff}.git-context b{color:var(--text)}.heat-panel{height:auto;overflow:hidden}.heat-panel .chart{height:185px}.git-split .structure-scroll-panel{max-height:none;overflow:visible}.branch.interactive{position:relative;padding-right:52px;cursor:pointer;transition:border-color .2s,background .2s}.branch.interactive:hover,.branch.interactive.selected{background:rgba(123,115,255,.12);outline:1px solid rgba(145,136,255,.35)}.checkout-btn{position:absolute;right:12px;top:20px;width:32px;height:32px;border:0;border-radius:6px;background:rgba(123,115,255,.15);color:#9188ff;display:grid;place-items:center;cursor:pointer}.checkout-btn svg{width:16px}.commit{width:100%;border:0;color:var(--text);text-align:left;cursor:pointer}.commit:hover{outline:1px solid rgba(145,136,255,.3)}.git-trend{position:relative}.git-trend>.segments{position:absolute;right:0;top:-38px;z-index:2}.git-trend .chart{height:280px}.drawer-mask{position:fixed;inset:0;z-index:60;background:rgba(0,0,0,.55);backdrop-filter:blur(5px);display:flex;justify-content:flex-end;animation:overlay-in .2s}.commit-drawer{width:min(820px,92vw);height:100%;overflow:auto;scrollbar-width:none;background:var(--glass-strong);border-left:1px solid var(--glass-border);box-shadow:-20px 0 50px rgba(0,0,0,.3);padding:26px;animation:drawer-in .3s cubic-bezier(.16,1,.3,1)}.commit-drawer::-webkit-scrollbar{display:none}.commit-drawer header{display:flex;justify-content:space-between;gap:20px;border-bottom:1px solid var(--border);padding-bottom:18px}.commit-drawer header small{color:var(--muted)}.commit-drawer h2{margin:7px 0 0;font-size:20px}.commit-drawer header button,.commit-meta button{border:0;background:var(--glass-soft);color:var(--text);width:34px;height:34px;border-radius:6px;display:grid;place-items:center;cursor:pointer}.commit-drawer-acts{display:flex;align-items:center;gap:8px;flex:none}.commit-drawer-ai{width:auto!important;padding:0 12px;display:inline-flex!important;align-items:center;gap:6px;font:inherit;font-size:12.5px;white-space:nowrap}.commit-drawer-ai:disabled{opacity:.45;cursor:not-allowed}.commit-drawer svg{width:17px}.commit-meta{display:grid;grid-template-columns:1fr auto auto auto;gap:10px;align-items:center;margin:20px 0;padding:15px;background:var(--glass-soft);border-radius:7px}.commit-meta code{min-width:0;overflow:hidden;text-overflow:ellipsis}.commit-meta span,.commit-meta time{grid-column:1/3;color:var(--muted)}.change-file{width:100%;display:grid;grid-template-columns:22px 1fr auto auto auto;gap:10px;align-items:center;padding:11px;border:0;border-bottom:1px solid var(--border);background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}.change-file:hover,.change-file.open{background:rgba(123,115,255,.08)}.change-file span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.change-file small{color:var(--muted)}.commit-diff{margin:0 0 12px;padding:10px 12px;border-radius:8px;background:#121820;overflow:hidden;font:12px/1.55 ui-monospace,Consolas,monospace;white-space:pre-wrap;word-break:break-all}.commit-diff span{display:block}.commit-diff .add{color:#55dfa1}.commit-diff .del{color:#ff8a95}.commit-diff .meta{color:#8fb2ff}.commit-diff .ctx{color:#9aa3b5}.commit-diff-note{margin:0 0 12px;padding:0 12px;color:var(--muted);font-size:12px}html[data-theme=light] .commit-diff{background:#f4f6fa}html[data-theme=light] .commit-diff .ctx{color:#3b4556}@keyframes drawer-in{from{transform:translateX(100%)}to{transform:none}}@media(prefers-reduced-motion:reduce){.commit-drawer{animation:none}}

View File

@@ -31,6 +31,9 @@ import './runtime.css'
import './git.css'
import './polish.css'
const isTrayWindow = new URLSearchParams(location.search).get('tray') === '1' || location.hash.startsWith('#/tray')
if (isTrayWindow) document.documentElement.classList.add('tray-window')
const zh = {
app: '年糕崽崽 PMS',
dashboard: '仪表盘',
@@ -480,6 +483,10 @@ const zh = {
commitDetail: '提交详情',
copyHash: '复制哈希',
filesChanged: '变更文件',
heatHint: '悬停查看提交次数,点击按日筛选',
binaryFile: '二进制文件,无法显示文本 diff',
noDiff: '没有可显示的文本变更',
diffTruncated: 'Diff 过长,已截断',
clearFilter: '清除筛选',
selectedDate: '已筛选 {date}',
day: '日',
@@ -517,6 +524,10 @@ const zh = {
allTypes: '全部类型',
noIssues: '暂无风险项',
insightDone: '深度检查完成',
insightExcludeTitle: '检查排除',
insightExcludeHint: '排除的文件或目录不参与 TODO、长文件等检查不影响行数统计。支持 vendor、src/todo、*.generated.go。',
insightExcludePh: '文件或目录,如 vendor、src/todo、*.pb.go',
insightExcludeEmpty: '未设置检查排除,将检查统计到的全部源码文件',
severity: { high: '高风险', medium: '中风险', low: '低风险' },
quickSettings: '快捷设置',
language: '语言',
@@ -573,6 +584,8 @@ const zh = {
aiPromptGit: '请分析这个项目的 Git 贡献情况:贡献者结构、活跃度和热点文件风险。',
aiPromptTodo: '请分析这个项目的待办事项:优先级是否合理、有哪些逾期风险、建议的执行顺序。',
aiPromptTicket: '请从需求管理角度分析这个项目的工单:排期合理性、类型分布和处理顺序建议。',
aiAnalyzeDiff: 'AI 分析本次 diff',
aiPromptDiff: '请审查这次提交的 diff改动意图、潜在风险、遗漏的测试以及简要改进建议。',
aiWelcome: '选择项目后可使用快捷分析,也可以直接提问',
aiAskPlaceholder: '输入问题Enter 发送Shift+Enter 换行',
aiSend: '发送',
@@ -637,6 +650,40 @@ const zh = {
loadingStyleMatrixDesc: '绿色数字雨倾泻而下',
loadingStyleBar: '底部进度条',
loadingStyleBarDesc: '保留当前页面,只显示底部进度',
trayMenuStyle: '托盘菜单样式',
trayStyleNative: '系统原生',
trayStyleNativeDesc: 'Windows 标准右键列表',
trayStyleLiquid: '液态玻璃',
trayStyleLiquidDesc: '控制中心:大块入口 + 底栏',
trayStyleGlass: '亚克力面板',
trayStyleGlassDesc: 'Win11 飞出:事务 / 系统分组',
trayStyleCompact: '紧凑列表',
trayStyleCompactDesc: '三列图标短字,高度最低',
trayStyleMinimal: '紧凑列表',
trayStyleMinimalDesc: '三列图标短字,高度最低',
trayStyleStatus: '状态卡片',
trayStyleStatusDesc: '看板:指标 + 分组入口',
trayStyleNeon: '暗色描边',
trayStyleNeonDesc: '左侧主操作,右侧短列表',
trayShow: '主窗口',
trayLaunchpad: '启动台',
traySync: '同步',
trayBatch: '批量统计全部项目',
trayBatchShort: '统计',
trayRestart: '重启',
trayQuit: '退出',
trayProjects: '项目',
trayAllProjects: '全部…',
trayTodos: '待办',
trayTickets: '工单',
trayMessages: '消息',
trayAutostart: '自启',
trayToday: '今日',
trayPending: '待推送 {n}',
trayUnread: '未读消息 {n}',
trayDueToday: '今日到期 {n}',
trayStatusSignedOut: '未登录',
aiHub: 'AI 分析',
sysIntegration: '系统集成',
onWindowClose: '关闭窗口时',
closeToTray: '最小化到系统托盘',
@@ -815,7 +862,7 @@ const zh = {
adminReleaseChangelog: '更新说明',
adminReleaseFile: '安装包',
adminReleaseDropTitle: '拖拽安装包到此处',
adminReleaseDropHint: '支持 .exe也可点击浏览选择',
adminReleaseDropHint: '请上传 NSIS 安装包package 产物 *-installer.exe不要上传裸 exe',
adminReleaseNeedExe: '请拖入或选择 .exe 安装包',
adminReleaseUpload: '上传',
adminReleasePublish: '设为最新',
@@ -838,6 +885,8 @@ const zh = {
appUpdateSkip: '稍后',
appUpdateInstall: '下载并安装',
appUpdateDownloading: '下载中…',
appUpdateHint: '下载完成后将退出并打开安装程序,请在向导中完成更新。',
appUpdateProgress: '已下载 {received} / {total}{percent}%',
checkAppUpdate: '检查软件更新',
aboutCheckUpdate: '检查更新',
aboutCheckingUpdate: '正在检查…',
@@ -1027,6 +1076,12 @@ const zh = {
VERSION_EXISTS: '该版本已存在',
FILE_TOO_LARGE: '文件过大',
SHA256_MISMATCH: '安装包校验失败',
SIZE_MISMATCH: '安装包大小与服务器不一致,请重试',
NOT_INSTALLER: '下载到的不是有效安装包,请检查网络或服务器地址',
DOWNLOAD_FAILED: '更新包下载失败,请检查网络后重试',
INSTALLER_START_FAILED: '无法启动安装程序',
ALREADY_LATEST: '已是最新版本',
SAVE_FAILED: '无法保存安装包',
NO_RELEASE: '暂无可用更新',
KIND_ICON_ADMIN_ONLY: '无权维护种类默认图标',
KIND_UNKNOWN: '未知的启动台种类',
@@ -1044,6 +1099,9 @@ const zh = {
FILE_PATH_INVALID: '非法文件路径',
FILE_READ_FAILED: '文件读取失败',
FILE_PATH_REQUIRED: '文件路径不能为空',
PATTERN_REQUIRED: '请输入排除规则',
PATTERN_EXISTS: '该排除规则已存在',
PROJECT_REQUIRED: '请先选择项目',
TODO_TITLE_REQUIRED: '请输入待办标题',
TODO_STATUS_INVALID: '无效的待办状态',
TICKET_TITLE_REQUIRED: '请输入工单标题',
@@ -1563,6 +1621,10 @@ const en = {
commitDetail: 'Commit details',
copyHash: 'Copy hash',
filesChanged: 'Changed files',
heatHint: 'Hover for counts, click to filter by day',
binaryFile: 'Binary file, no text diff',
noDiff: 'No text diff to show',
diffTruncated: 'Diff truncated',
clearFilter: 'Clear filter',
selectedDate: 'Filtered by {date}',
day: 'Day',
@@ -1600,6 +1662,10 @@ const en = {
allTypes: 'All types',
noIssues: 'No issues found',
insightDone: 'Inspection completed',
insightExcludeTitle: 'Check excludes',
insightExcludeHint: 'Excluded files or directories skip TODO and long-file checks, without changing line counts. Examples: vendor, src/todo, *.generated.go.',
insightExcludePh: 'File or directory, e.g. vendor, src/todo, *.pb.go',
insightExcludeEmpty: 'No check excludes. All scanned source files will be inspected.',
severity: { high: 'High', medium: 'Medium', low: 'Low' },
quickSettings: 'Quick settings',
language: 'Language',
@@ -1656,6 +1722,8 @@ const en = {
aiPromptGit: 'Analyze the Git contribution of this project: contributor structure, activity and hotspot risks.',
aiPromptTodo: 'Analyze the todos of this project: priority sanity, overdue risks and a suggested execution order.',
aiPromptTicket: 'Analyze the tickets of this project from a requirements perspective: scheduling, type distribution and handling order.',
aiAnalyzeDiff: 'Analyze this diff',
aiPromptDiff: 'Review this commit diff: intent, risks, missing tests, and brief improvement suggestions.',
aiWelcome: 'Pick a project for quick analysis, or just ask anything',
aiAskPlaceholder: 'Type a question. Enter to send, Shift+Enter for newline',
aiSend: 'Send',
@@ -1720,6 +1788,40 @@ const en = {
loadingStyleMatrixDesc: 'Green digital rain pouring down',
loadingStyleBar: 'Bottom progress bar',
loadingStyleBarDesc: 'Keep the page, show only a bottom bar',
trayMenuStyle: 'Tray menu style',
trayStyleNative: 'System native',
trayStyleNativeDesc: 'Windows context menu list',
trayStyleLiquid: 'Liquid glass',
trayStyleLiquidDesc: 'Control Center tiles with a footer',
trayStyleGlass: 'Acrylic panel',
trayStyleGlassDesc: 'Windows 11 flyout with Work / System groups',
trayStyleCompact: 'Compact list',
trayStyleCompactDesc: 'Three-column icons, lowest height',
trayStyleMinimal: 'Compact list',
trayStyleMinimalDesc: 'Three-column icons, lowest height',
trayStyleStatus: 'Status card',
trayStyleStatusDesc: 'Dashboard with metrics and grouped actions',
trayStyleNeon: 'Dark outline',
trayStyleNeonDesc: 'Primary rail on the left, short list on the right',
trayShow: 'Window',
trayLaunchpad: 'Launchpad',
traySync: 'Sync',
trayBatch: 'Analyze All Projects',
trayBatchShort: 'Analyze',
trayRestart: 'Restart',
trayQuit: 'Quit',
trayProjects: 'Projects',
trayAllProjects: 'All…',
trayTodos: 'Todos',
trayTickets: 'Tickets',
trayMessages: 'Inbox',
trayAutostart: 'Startup',
trayToday: 'Today',
trayPending: 'Pending {n}',
trayUnread: 'Unread {n}',
trayDueToday: 'Due today {n}',
trayStatusSignedOut: 'Signed out',
aiHub: 'AI Analysis',
sysIntegration: 'System integration',
onWindowClose: 'When closing the window',
closeToTray: 'Minimize to system tray',
@@ -1898,7 +2000,7 @@ const en = {
adminReleaseChangelog: 'Changelog',
adminReleaseFile: 'Installer',
adminReleaseDropTitle: 'Drop installer here',
adminReleaseDropHint: 'Accepts .exe; or click Browse',
adminReleaseDropHint: 'Upload the NSIS installer (*-installer.exe from package), not the raw app exe',
adminReleaseNeedExe: 'Please drop or pick an .exe installer',
adminReleaseUpload: 'Upload',
adminReleasePublish: 'Publish',
@@ -1921,6 +2023,8 @@ const en = {
appUpdateSkip: 'Later',
appUpdateInstall: 'Download & install',
appUpdateDownloading: 'Downloading…',
appUpdateHint: 'The app will quit and open the installer. Finish the wizard to update.',
appUpdateProgress: 'Downloaded {received} / {total} ({percent}%)',
checkAppUpdate: 'Check for updates',
aboutCheckUpdate: 'Check for updates',
aboutCheckingUpdate: 'Checking…',
@@ -2110,6 +2214,12 @@ const en = {
VERSION_EXISTS: 'Version already exists',
FILE_TOO_LARGE: 'File too large',
SHA256_MISMATCH: 'Installer checksum mismatch',
SIZE_MISMATCH: 'Installer size does not match the server; please retry',
NOT_INSTALLER: 'Downloaded file is not a valid installer; check the network or server URL',
DOWNLOAD_FAILED: 'Failed to download the update; check the network and retry',
INSTALLER_START_FAILED: 'Could not start the installer',
ALREADY_LATEST: 'Already up to date',
SAVE_FAILED: 'Could not save the installer',
NO_RELEASE: 'No release available',
KIND_ICON_ADMIN_ONLY: 'You do not have permission to manage kind icons',
KIND_UNKNOWN: 'Unknown launchpad kind',
@@ -2127,6 +2237,9 @@ const en = {
FILE_PATH_INVALID: 'Invalid file path',
FILE_READ_FAILED: 'Failed to read file',
FILE_PATH_REQUIRED: 'File path is required',
PATTERN_REQUIRED: 'Exclusion pattern is required',
PATTERN_EXISTS: 'This exclusion rule already exists',
PROJECT_REQUIRED: 'Select a project first',
TODO_TITLE_REQUIRED: 'Todo title is required',
TODO_STATUS_INVALID: 'Invalid todo status',
TICKET_TITLE_REQUIRED: 'Ticket title is required',
@@ -2226,7 +2339,8 @@ const router = createRouter({
{ path: '/team', component: TeamHome },
{ path: '/team/tasks', component: TeamTasks },
{ path: '/team/reports', component: TeamReports },
{ path: '/admin', component: Admin }
{ path: '/admin', component: Admin },
{ path: '/tray', component: { template: '<div/>' } }
]
})

View File

@@ -57,6 +57,9 @@ html{--topbar-h:0px}
.exit-modal .modal-head .nm-close:hover{background:var(--surface-3);color:var(--text)}
.exit-modal .modal-head .nm-close svg{width:16px;height:16px}
.exit-hint{margin:0;padding:0 20px 14px;color:var(--muted);font-size:13px}
.update-dl-bar{height:6px;margin:0 20px 14px;border-radius:999px;background:var(--surface-3);overflow:hidden}
.update-dl-bar>i{display:block;height:100%;width:0;border-radius:inherit;background:var(--primary);transition:width .2s ease}
.exit-modal .modal-head .nm-close:disabled{opacity:.4;cursor:not-allowed}
.exit-actions{display:flex;flex-direction:column;gap:10px;padding:0 20px 22px}
.exit-actions .btn{width:100%;justify-content:center}
.exit-actions .btn.danger{background:color-mix(in srgb,var(--red) 18%,var(--surface-2));border-color:rgba(240,94,104,.45);color:var(--red)}
@@ -305,6 +308,137 @@ html[data-theme=light] .lg-art{background:#141a2e}
.loading-style-card.fullscreen-matrix .loading-style-preview i{width:34px;height:34px;border-radius:4px;background:linear-gradient(180deg,transparent 0 10%,#a5ffcb 10% 19%,rgba(60,200,110,.5) 19% 72%,transparent 72%) 2px 0/3px 100% no-repeat,linear-gradient(180deg,transparent 0 36%,#a5ffcb 36% 45%,rgba(60,200,110,.45) 45% 96%,transparent 96%) 9px 0/3px 100% no-repeat,linear-gradient(180deg,#a5ffcb 0 8%,rgba(60,200,110,.5) 8% 52%,transparent 52%) 16px 0/3px 100% no-repeat,linear-gradient(180deg,transparent 0 22%,#a5ffcb 22% 31%,rgba(60,200,110,.45) 31% 84%,transparent 84%) 23px 0/3px 100% no-repeat,linear-gradient(180deg,transparent 0 52%,#a5ffcb 52% 60%,rgba(60,200,110,.4) 60% 100%) 30px 0/3px 100% no-repeat;box-shadow:0 0 14px rgba(90,230,140,.35)}
.loading-style-card.bar .loading-style-preview i{width:34px;height:8px;border-radius:999px;background:rgba(255,255,255,.1);overflow:hidden}
.loading-style-card.bar .loading-style-preview i::before{content:"";position:absolute;inset:0 38% 0 0;border-radius:inherit;background:linear-gradient(90deg,#6ee7ff,#53d6a2);box-shadow:0 0 12px rgba(110,231,255,.65)}
.tray-style-setting{display:grid;gap:12px;margin-top:18px;color:var(--text);font-weight:800}
.tray-style-setting>span{display:flex;align-items:center;gap:8px}
.tray-style-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(158px,1fr));gap:12px}
.tray-style-card{position:relative;min-height:176px;border:1px solid rgba(145,136,255,.2);border-radius:8px;background:linear-gradient(180deg,rgba(255,255,255,.055),rgba(255,255,255,.018)),var(--surface-2);color:var(--text);padding:12px;display:grid;grid-template-rows:96px auto 1fr;gap:8px;text-align:left;cursor:pointer;outline:none;overflow:hidden;transition:border-color .2s ease,background .2s ease,box-shadow .2s ease}
.tray-style-card:hover{border-color:rgba(110,231,255,.5);box-shadow:0 14px 30px rgba(0,0,0,.22)}
.tray-style-card:focus-visible{box-shadow:0 0 0 3px rgba(110,231,255,.18),0 14px 30px rgba(0,0,0,.22)}
.tray-style-card.active{border-color:rgba(110,231,255,.72);background:linear-gradient(180deg,rgba(110,231,255,.11),rgba(83,214,162,.045)),var(--surface-2);box-shadow:0 0 0 1px rgba(110,231,255,.16),0 18px 36px rgba(0,0,0,.24)}
.tray-style-card.active::after{content:"";position:absolute;right:10px;top:10px;width:9px;height:9px;border-radius:50%;background:#6ee7ff;box-shadow:0 0 14px rgba(110,231,255,.9);z-index:2}
.tray-style-card b{font-size:14px;line-height:1.25}
.tray-style-card small{color:var(--muted);font-weight:600;line-height:1.35}
.tray-style-preview{display:grid;place-items:center;border-radius:8px;border:1px solid rgba(255,255,255,.08);background:rgba(4,9,18,.48);overflow:hidden}
.tsp-menu{display:grid;gap:3px;width:86px;height:68px;padding:6px;box-sizing:border-box;background:#2b2b2b;border:1px solid #1a1a1a}
.tsp-menu i{display:block;min-height:0;border-radius:2px;background:rgba(255,255,255,.28)}
.tray-style-card.native .tray-style-preview{background:#1c1c1c}
.tray-style-card.native .tsp-menu{grid-template-columns:1fr;grid-template-rows:repeat(6,1fr);border-radius:0}
.tray-style-card.native .tsp-menu i:nth-child(n+7){display:none}
.tray-style-card.native .tsp-menu i:nth-child(3){height:1px;min-height:1px;background:rgba(255,255,255,.16);align-self:center}
.tray-style-card.liquid .tray-style-preview{background:linear-gradient(180deg,#3a4252,#252b38)}
.tray-style-card.liquid .tsp-menu{grid-template-columns:repeat(6,1fr);grid-template-rows:8px 1fr 1fr 7px 8px;gap:3px;padding:7px;border-radius:14px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.2)}
.tray-style-card.liquid .tsp-menu i{border-radius:6px;background:rgba(255,255,255,.34)}
.tray-style-card.liquid .tsp-menu i:nth-child(1){grid-column:1/-1;border-radius:999px}
.tray-style-card.liquid .tsp-menu i:nth-child(2),
.tray-style-card.liquid .tsp-menu i:nth-child(4){grid-column:1/4}
.tray-style-card.liquid .tsp-menu i:nth-child(3),
.tray-style-card.liquid .tsp-menu i:nth-child(5){grid-column:4/7}
.tray-style-card.liquid .tsp-menu i:nth-child(6){grid-column:1/-1;border-radius:8px;background:rgba(255,255,255,.18)}
.tray-style-card.liquid .tsp-menu i:nth-child(7){grid-column:1/3;border-radius:999px;background:rgba(255,255,255,.22)}
.tray-style-card.liquid .tsp-menu i:nth-child(8){grid-column:3/5;border-radius:999px;background:rgba(255,255,255,.22)}
.tray-style-card.liquid .tsp-menu i:nth-child(9){grid-column:5/7;border-radius:999px;background:rgba(255,255,255,.22)}
.tray-style-card.liquid .tsp-menu i:nth-child(10){display:none}
.tray-style-card.glass .tray-style-preview{background:linear-gradient(180deg,#2a3342,#171d27)}
.tray-style-card.glass .tsp-menu{grid-template-columns:1fr 1fr;grid-template-rows:7px 1fr 1fr 1fr 8px 6px;gap:3px;padding:6px;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08)}
.tray-style-card.glass .tsp-menu i{height:auto;border-radius:6px;background:rgba(25,33,43,.82)}
.tray-style-card.glass .tsp-menu i:nth-child(1){grid-column:1/-1;border-radius:8px;background:rgba(255,255,255,.08)}
.tray-style-card.glass .tsp-menu i:nth-child(8){grid-column:1/-1;border-radius:8px;background:rgba(25,33,43,.7)}
.tray-style-card.glass .tsp-menu i:nth-child(9),
.tray-style-card.glass .tsp-menu i:nth-child(10){display:none}
.tray-style-card.compact .tray-style-preview{background:#11151c}
.tray-style-card.compact .tsp-menu{grid-template-columns:repeat(4,1fr);grid-template-rows:repeat(3,1fr);gap:4px;padding:7px;border-radius:8px;background:#11151c;border:0}
.tray-style-card.compact .tsp-menu i{height:14px;width:14px;margin:auto;border-radius:5px;background:#1b2230}
.tray-style-card.compact .tsp-menu i:nth-child(n+13){display:none}
.tray-style-card.status .tray-style-preview{background:#19212b}
.tray-style-card.status .tsp-menu{grid-template-columns:repeat(4,1fr);grid-template-rows:8px 14px 1fr 1fr 1fr 8px;gap:3px;padding:6px;border-radius:10px;background:#19212b;border:1px solid #2a3a48;position:relative}
.tray-style-card.status .tsp-menu::before{content:"";position:absolute;left:10px;top:7px;width:6px;height:6px;border-radius:50%;background:#43c996}
.tray-style-card.status .tsp-menu i{height:auto;border-radius:5px;background:#222b38}
.tray-style-card.status .tsp-menu i:nth-child(1){grid-column:1/-1;background:transparent}
.tray-style-card.status .tsp-menu i:nth-child(2){grid-column:1/3}
.tray-style-card.status .tsp-menu i:nth-child(3){grid-column:3/5}
.tray-style-card.status .tsp-menu i:nth-child(4){grid-column:1/3}
.tray-style-card.status .tsp-menu i:nth-child(5){grid-column:3/5}
.tray-style-card.status .tsp-menu i:nth-child(10){grid-column:1/-1;border-radius:4px}
.tray-style-card.neon .tray-style-preview{background:#151b24}
.tray-style-card.neon .tsp-menu{grid-template-columns:14px 1fr;grid-template-rows:8px repeat(5,1fr);gap:2px;padding:5px;border-radius:8px;background:#151b24;border:1px solid #303949}
.tray-style-card.neon .tsp-menu i{height:auto;border-radius:4px;background:rgba(255,255,255,.06)}
.tray-style-card.neon .tsp-menu i:nth-child(1){grid-column:1/-1;background:rgba(255,255,255,.04)}
.tray-style-card.neon .tsp-menu i:nth-child(2),
.tray-style-card.neon .tsp-menu i:nth-child(3),
.tray-style-card.neon .tsp-menu i:nth-child(4),
.tray-style-card.neon .tsp-menu i:nth-child(5){grid-column:1;border:1px solid #303949;background:#121820}
.tray-style-card.neon .tsp-menu i:nth-child(n+6){grid-column:2}
.tray-style-card.neon .tsp-menu i:nth-child(10){background:rgba(240,94,104,.28)}
html[data-theme=light] .tray-style-preview{background:#e8edf4;border-color:rgba(15,23,42,.08)}
html[data-theme=light] .tray-style-card.native .tsp-menu{background:#f3f3f3;border-color:#d0d0d0}
html[data-theme=light] .tray-style-card.native .tsp-menu i{background:rgba(17,24,39,.35)}
html[data-theme=light] .tray-style-card.liquid .tsp-menu{background:rgba(255,255,255,.72);border-color:rgba(15,23,42,.08)}
html[data-theme=light] .tray-style-card.liquid .tsp-menu i{background:rgba(15,23,42,.16)}
html[data-theme=light] .tray-style-card.glass .tsp-menu{background:rgba(255,255,255,.5);border-color:rgba(15,23,42,.08)}
html[data-theme=light] .tray-style-card.glass .tsp-menu i{background:#fff}
html[data-theme=light] .tray-style-card.compact .tsp-menu{background:#f4f6fa}
html[data-theme=light] .tray-style-card.compact .tsp-menu i{background:#fff}
html[data-theme=light] .tray-style-card.status .tsp-menu{background:#fff;border-color:#d5dce8}
html[data-theme=light] .tray-style-card.status .tsp-menu i{background:#f3f5f8}
html[data-theme=light] .tray-style-card.neon .tsp-menu{background:#fff;border-color:#dce1ea}
html.tray-window,html.tray-window body,html.tray-window #app{min-width:0!important;max-width:100%!important;width:100%!important;height:100%!important;min-height:0!important;margin:0;overflow:hidden!important;background:transparent!important;scrollbar-width:none}
html.tray-window::-webkit-scrollbar,html.tray-window *::-webkit-scrollbar{display:none!important;width:0!important;height:0!important}
.tray-pop{--tray-hover:rgba(255,255,255,.08);box-sizing:border-box;width:268px;padding:6px;display:grid;gap:2px;color:var(--text);font-weight:650;user-select:none;overflow:hidden}
.tray-pop-head{display:flex;align-items:center;gap:6px;min-height:24px;padding:3px 8px;border-radius:6px;cursor:pointer}
.tray-pop-head:hover{background:var(--tray-hover)}
.tray-pop-head b{flex:1;min-width:0;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tray-dot{width:7px;height:7px;border-radius:50%;background:#929bac;flex:none}
.tray-pop.st-online .tray-dot{background:#43c996}
.tray-pop.st-offline .tray-dot{background:#e7bd35}
.tray-pop.st-error .tray-dot{background:#f05e68}
.tray-pop.st-syncing .tray-dot{background:#4f9df5}
.tray-pop-head em{min-width:16px;height:16px;padding:0 5px;border-radius:999px;background:rgba(110,231,255,.2);color:#6ee7ff;font-size:10px;font-style:normal;display:grid;place-items:center;cursor:pointer}
.tray-pop-head em.due{background:rgba(231,189,53,.22);color:#e7bd35}
.tray-pop button{border:0;background:transparent;color:inherit;cursor:pointer;font:inherit;font-weight:650}
.tray-sep{display:block;height:1px;margin:3px 6px;background:color-mix(in srgb,var(--border) 80%,transparent);border:0}
.tray-grid{display:grid;grid-template-columns:1fr 1fr;gap:1px}
.tray-pop:not(.dense) .tray-sep{display:none}
.tray-pop:not(.dense) .tray-grid{grid-template-columns:repeat(4,1fr);gap:3px}
.tray-grid button{display:flex;align-items:center;gap:6px;min-height:26px;padding:0 7px;border-radius:6px;font-size:12px;text-align:left}
.tray-grid button:hover{background:var(--tray-hover)}
.tray-pop:not(.dense) .tray-grid button{flex-direction:column;justify-content:center;gap:3px;min-height:46px;padding:6px 2px;border-radius:8px;background:var(--tray-hover);font-size:11px;text-align:center}
.tray-grid button svg{width:14px;height:14px;flex:none;color:var(--muted)}
.tray-grid button span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tray-grid button.on{background:var(--tray-hover);box-shadow:inset 0 0 0 1px rgba(110,231,255,.35)}
.tray-grid button.danger,.tray-grid button.danger svg{color:#f05e68}
.tray-projects{display:flex;flex-wrap:wrap;gap:4px;padding:4px 2px 2px}
.tray-projects button{max-width:100%;padding:3px 8px;border-radius:999px;background:var(--tray-hover);font-size:11px;font-weight:600}
.tray-pop.skin-liquid{width:268px;padding:7px;border-radius:14px;background:rgba(42,48,60,.58);border:1px solid rgba(255,255,255,.2);box-shadow:0 10px 24px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.22);backdrop-filter:blur(32px) saturate(170%);-webkit-backdrop-filter:blur(32px) saturate(170%)}
.tray-pop.skin-liquid .tray-pop-head{border-radius:999px}
.tray-pop.skin-liquid .tray-grid button{border-radius:8px}
.tray-pop.skin-liquid .tray-sep{background:rgba(255,255,255,.14)}
.tray-pop.skin-glass{width:264px;padding:6px;border-radius:8px;background:color-mix(in srgb,var(--surface) 92%,transparent);border:1px solid var(--border);box-shadow:0 10px 24px rgba(0,0,0,.28)}
.tray-pop.skin-glass .tray-pop-head,.tray-pop.skin-glass .tray-grid button{border-radius:4px}
.tray-pop.skin-compact{width:252px;padding:4px;gap:1px;border-radius:6px;background:var(--surface);border:1px solid var(--border)}
.tray-pop.skin-compact .tray-pop-head{min-height:20px;padding:1px 6px;border-radius:4px}
.tray-pop.skin-compact .tray-pop-head b{font-size:11px}
.tray-pop.skin-compact .tray-grid button{min-height:24px;padding:0 6px;border-radius:4px;font-size:11px}
.tray-pop.skin-compact .tray-grid button svg{width:13px;height:13px}
.tray-pop.skin-compact .tray-sep{margin:2px 4px}
.tray-pop.skin-status{width:276px;padding:0;gap:0;border-radius:12px;background:var(--surface);border:1px solid var(--border);box-shadow:0 12px 28px rgba(0,0,0,.3);overflow:hidden}
.tray-pop.skin-status .tray-pop-head{margin:0;padding:8px 10px;border-radius:0;background:var(--surface);box-shadow:inset 0 2px 0 #43c996}
.tray-pop.skin-status .tray-grid,.tray-pop.skin-status .tray-projects{padding:6px}
.tray-pop.skin-neon{width:264px;padding:6px;border-radius:8px;background:#151b24;border:1px solid var(--border);box-shadow:0 10px 24px rgba(0,0,0,.32)}
.tray-pop.skin-neon .tray-grid button:hover{background:rgba(255,255,255,.06)}
.tray-pop.skin-neon .tray-grid button.on{background:rgba(115,103,245,.12)}
.tray-pop.skin-neon .tray-sep{background:var(--border)}
html[data-theme=light] .tray-pop{--tray-hover:rgba(15,23,42,.06)}
html[data-theme=light] .tray-pop.skin-liquid{background:rgba(255,255,255,.62);color:#0f172a;border-color:rgba(255,255,255,.55)}
html[data-theme=light] .tray-pop.skin-glass,html[data-theme=light] .tray-pop.skin-compact,html[data-theme=light] .tray-pop.skin-status{background:#fff;color:#111827}
html[data-theme=light] .tray-pop.skin-neon{background:#fff;color:#111827}
html[data-theme=light] .tray-pop-head em{color:#0b7285;background:rgba(14,116,144,.12)}
.toast{transition:opacity .32s ease,transform .36s ease,filter .32s ease}
.toast.muted{opacity:.72;filter:saturate(.82)}
.toast.leaving{opacity:0;transform:translate(18px,-12px);pointer-events:none}
@@ -321,19 +455,20 @@ html[data-theme=light] .lg-art{background:#141a2e}
.detail-rules-badge{margin-left:2px;min-width:16px;height:16px;padding:0 5px;border-radius:999px;display:inline-grid;place-items:center;font-style:normal;font-size:10px;font-weight:800;line-height:1;color:#fff;background:linear-gradient(135deg,#7b73ff,#5b52d6)}
.detail-tabs{justify-self:start;width:max-content;max-width:100%;margin:0;padding:3px;background:rgba(255,255,255,.045);box-sizing:border-box}
.detail-tabs button{height:32px;padding:0 12px;font-size:12.5px;flex:none}
.heat-panel{height:auto;min-height:250px}
.heat-grid-wrap{--cell:13px;--gap:4px;position:relative;margin-top:12px;overflow-x:auto;padding-bottom:8px}
.heat-months{display:grid;grid-template-columns:repeat(var(--weeks),var(--cell));gap:var(--gap);margin-left:34px;margin-bottom:8px;min-width:calc(var(--weeks) * (var(--cell) + var(--gap)))}
.heat-months span{font-size:12px;color:var(--muted);white-space:nowrap}
.heat-body{position:relative;display:flex;gap:10px;align-items:flex-start}
.heat-weekdays{display:grid;grid-template-rows:repeat(7,var(--cell));gap:var(--gap);width:24px;color:var(--muted);font-size:12px;line-height:var(--cell);text-align:right}
.heat-grid{display:grid;grid-template-columns:repeat(var(--weeks),var(--cell));grid-template-rows:repeat(7,var(--cell));gap:var(--gap);min-width:calc(var(--weeks) * (var(--cell) + var(--gap)))}
.heat-cell{width:var(--cell);height:var(--cell);border:1px solid rgba(255,255,255,.035);border-radius:3px;background:#26303d;cursor:pointer;padding:0;transition:transform .12s ease,border-color .12s ease,box-shadow .12s ease}
.heat-cell:hover,.heat-cell.selected{transform:translateY(-1px);border-color:rgba(255,255,255,.45);box-shadow:0 0 0 2px rgba(123,115,255,.22)}
.heat-panel{height:auto;min-height:0;overflow:hidden}
.heat-grid-wrap{--cell:13px;--gap:3px;position:relative;margin-top:12px;width:100%;max-width:100%;overflow:hidden;scrollbar-width:none}
.heat-grid-wrap::-webkit-scrollbar{display:none;width:0;height:0}
.heat-months{position:relative;height:16px;margin:0 0 8px 34px}
.heat-months span{position:absolute;top:0;font-size:12px;line-height:16px;color:var(--muted);white-space:nowrap;overflow:hidden}
.heat-body{position:relative;display:flex;gap:10px;align-items:flex-start;min-width:0;overflow:hidden}
.heat-weekdays{display:grid;grid-template-rows:repeat(7,var(--cell));gap:var(--gap);width:24px;flex:none;color:var(--muted);font-size:12px;line-height:var(--cell);text-align:right}
.heat-grid{display:grid;grid-template-columns:repeat(var(--weeks),var(--cell));grid-template-rows:repeat(7,var(--cell));gap:var(--gap);min-width:0;flex:1}
.heat-cell{width:var(--cell);height:var(--cell);border:1px solid rgba(255,255,255,.035);border-radius:3px;background:#26303d;cursor:pointer;padding:0;transition:border-color .12s ease,box-shadow .12s ease}
.heat-cell:hover,.heat-cell.selected{border-color:rgba(255,255,255,.45);box-shadow:0 0 0 2px rgba(123,115,255,.22)}
.heat-cell.l1{background:#245140}.heat-cell.l2{background:#2e765b}.heat-cell.l3{background:#3cab7d}.heat-cell.l4{background:#55dfa1}
html[data-theme=light] .heat-cell{background:#e7ecf3;border-color:#d9e0ea}
html[data-theme=light] .heat-cell.l1{background:#b9efd4}html[data-theme=light] .heat-cell.l2{background:#81dfb4}html[data-theme=light] .heat-cell.l3{background:#42c990}html[data-theme=light] .heat-cell.l4{background:#159c68}
.heat-tooltip{position:absolute;left:44px;bottom:-30px;z-index:3;border:1px solid var(--border);border-radius:7px;background:var(--surface-3);padding:6px 9px;color:var(--text);font-size:12px;box-shadow:0 10px 26px rgba(0,0,0,.28);pointer-events:none}
.heat-tip{min-height:28px;margin:10px 0 0;color:var(--muted);font-size:12px;line-height:28px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.insights-hero{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:22px}
.score-ring{width:116px;height:116px;border-radius:50%;display:grid;place-items:center;background:radial-gradient(circle at center,var(--surface) 58%,transparent 59%),conic-gradient(var(--green) calc(var(--score,75)*1%),rgba(255,255,255,.08) 0);border:1px solid var(--border)}
.score-ring strong{font-size:34px;line-height:1}
@@ -345,6 +480,9 @@ html[data-theme=light] .heat-cell.l1{background:#b9efd4}html[data-theme=light] .
.insight-counts .medium,.issue-card.medium .issue-severity{color:#ffd166;background:rgba(231,189,53,.12)}
.insight-counts .low,.issue-card.low .issue-severity{color:#72b7ff;background:rgba(79,157,245,.12)}
.insight-filter select{height:36px;border:1px solid var(--border);border-radius:7px;background:var(--surface-2);color:var(--text);padding:0 10px}
.insight-exclude-panel .section-head h2{display:flex;align-items:center;gap:8px}
.insight-exclude-panel .section-head h2 svg{width:16px;height:16px;color:var(--primary)}
.insight-exclude-hint{margin:0 0 12px;font-size:12.5px;color:var(--muted);line-height:1.45}
.issue-list{display:grid;gap:10px;margin-top:16px;max-height:620px;overflow:auto;padding-right:6px}
.issue-card{position:relative;display:grid;grid-template-columns:1fr;gap:10px;padding:16px 18px;border:1px solid var(--border);border-radius:8px;background:linear-gradient(180deg,rgba(255,255,255,.045),rgba(255,255,255,.015)),var(--surface-2);overflow:hidden}
.issue-card::before{display:none}
@@ -559,9 +697,8 @@ html[data-theme=light] .heat-cell.l1{background:#b9efd4}html[data-theme=light] .
.flow-btn{height:32px;padding:0 11px;font-size:12px}
.flow-btn svg{width:13px}
.calendar-nav{gap:10px}
.calendar-nav .btn{width:38px;padding:0;justify-content:center;flex:0 0 auto}
/* 文字类按钮按内容自适应宽度(不能依赖 last-child末尾可能是管理员 icon 按钮) */
.calendar-nav .daily-open-btn{width:auto;padding:0 14px;white-space:nowrap}
.calendar-nav .btn{width:auto;min-width:38px;padding:0 12px;justify-content:center;flex:0 0 auto;white-space:nowrap}
.calendar-nav .fest-admin-btn{width:38px;min-width:38px;padding:0}
.calendar-month{min-width:120px;text-align:center}
/* 固定左右两栏:右栏按比例随窗口缩放(约 1/4不再在窄屏折叠为单列 */
.calendar-layout{display:grid;grid-template-columns:minmax(0,3fr) minmax(230px,1fr);gap:20px;align-items:start}
@@ -906,7 +1043,7 @@ html[data-theme=light] .heat-cell.l1{background:#b9efd4}html[data-theme=light] .
@keyframes loadingTrackSweep{0%,100%{transform:translateX(-62%);opacity:.35}50%{transform:translateX(62%);opacity:.9}}
@media(max-width:1150px){main::before,main::after{left:72px}.sidebar-bottom{padding-left:0;padding-right:0;justify-content:center}.quick-settings{left:0}.quick-settings-btn{width:40px;height:40px}.stats-grid.three,.stats-grid.four{grid-template-columns:repeat(2,minmax(0,1fr))}.project-card{padding:20px}}
@media(max-width:980px){body{min-width:0}.page{padding:24px 24px 56px}.stats-grid.three,.stats-grid.four,.stats-grid.five{grid-template-columns:repeat(2,minmax(0,1fr))}.project-grid{grid-template-columns:1fr}.section-head{align-items:flex-start;gap:12px;flex-direction:column}.project-tools{width:100%;justify-content:flex-start}.group-filter{width:100%;flex-wrap:wrap;height:auto}.group-filter select{flex:1;min-width:160px}.search{width:100%}.git-error-panel{grid-template-columns:36px 1fr}.git-error-panel .btn{grid-column:1/3;width:max-content}}
@media(max-width:720px){.loading-style-grid{grid-template-columns:1fr}.loading-style-card{min-height:104px}}
@media(max-width:720px){.loading-style-grid{grid-template-columns:1fr}.loading-style-card{min-height:104px}.tray-style-grid{grid-template-columns:1fr 1fr}}
@media(max-width:980px){.detail-page{--detail-sticky-offset:12px;padding:var(--detail-sticky-offset) 20px 56px}.insights-hero{grid-template-columns:1fr}.detail-head-row{align-items:flex-start;flex-wrap:wrap;gap:10px}.detail-head-id{flex:1 1 220px}.detail-head-acts{width:100%;flex-wrap:wrap;justify-content:flex-start}.detail-tabs{width:100%;max-width:100%;overflow-x:auto}}
@media(prefers-reduced-motion:reduce){main::before,main::after,.logo-track,.logo-spark,.shine-card:hover::after{animation:none!important}.shine-card:hover,.heat-cell:hover{transform:none}.toast{transition:opacity .2s ease}}
@@ -1825,11 +1962,13 @@ html[data-theme=light] .lp-log-line{color:#1f2937}
/* ============ 日历页头紧凑化:单行标题 + 32px 按钮 ============ */
.calendar-page .calendar-head{padding:9px 16px;margin-bottom:14px}
.calendar-page .calendar-head>div{display:flex;align-items:baseline;gap:10px;min-width:0}
.calendar-page .calendar-head>div{display:flex;align-items:center;gap:10px;min-width:0}
.calendar-page .calendar-head>div:first-child{align-items:baseline}
.calendar-page .calendar-head h1{font-size:19px;margin:0;white-space:nowrap}
.calendar-page .calendar-head p{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.calendar-page .calendar-head .actions{flex-wrap:nowrap}
.calendar-page .calendar-head .actions .btn{height:32px;padding:0 10px;font-size:12.5px;white-space:nowrap;flex-shrink:0}
.calendar-page .calendar-head .actions{align-items:center;flex-wrap:nowrap}
.calendar-page .calendar-head .actions .btn{height:32px;width:auto;padding:0 12px;font-size:12.5px;white-space:nowrap;flex-shrink:0}
.calendar-page .calendar-head .actions .fest-admin-btn{width:38px;padding:0}
.calendar-page .calendar-head .calendar-month{font-size:13.5px;white-space:nowrap}
.calendar-grid-panel{min-height:calc(100vh - 150px)}
@@ -2029,6 +2168,8 @@ html[data-theme=light] .lp-log-line{color:#1f2937}
/* ============ 无边框自定义标题栏logo + 菜单 + 窗控同一行) ============ */
:root{--titlebar-h:40px}
html,body,#app{height:100%;overflow:hidden}
html.tray-window,html.tray-window body,html.tray-window #app{min-width:0!important;width:100%!important;height:100%!important;overflow:hidden!important;background:transparent!important;scrollbar-width:none!important}
html.tray-window::-webkit-scrollbar,html.tray-window body::-webkit-scrollbar,html.tray-window #app::-webkit-scrollbar{display:none!important;width:0!important;height:0!important}
/* 只有主内容区滚动;侧栏不设 overflow:auto避免滚动条夹在 rail 中间、裁切铃铛/飞出菜单 */
.shell{
height:100%;

View File

@@ -8,7 +8,7 @@ export const useAppStore = defineStore('app', {
projectGroups: [],
selectedProjectGroupId: Number(localStorage.getItem('cc-project-group-id') || 0),
dashboard: { projects: 0, totalLines: 0, commits: 0 },
settings: { theme: 'dark', locale: 'zh-CN', glassOpacity: 55, gitScope: 'current', autoRefresh: true, loadingStyle: 'fullscreen-orbit', imageMode: 'base64' },
settings: { theme: 'dark', locale: 'zh-CN', glassOpacity: 55, gitScope: 'current', autoRefresh: true, loadingStyle: 'fullscreen-orbit', trayMenuStyle: 'native', imageMode: 'base64' },
tasks: {},
batchTaskIds: [],
batchSummary: null,

File diff suppressed because one or more lines are too long

View File

@@ -2,7 +2,7 @@
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ArrowLeft, Code2, GitCommitHorizontal, FolderTree, RefreshCw, Files, MessageSquareText, Rows3, Users, Plus, Minus, HardDrive, Folder, FileWarning, GitBranch, ExternalLink, TriangleAlert, ClipboardCheck, Flame, Sparkles, MessageCircleQuestion, Rocket, ListFilter } from 'lucide-vue-next'
import { ArrowLeft, Code2, GitCommitHorizontal, FolderTree, RefreshCw, Files, MessageSquareText, Rows3, Users, Plus, Minus, HardDrive, Folder, FileWarning, GitBranch, ExternalLink, TriangleAlert, ClipboardCheck, Flame, Sparkles, MessageCircleQuestion, Rocket, ListFilter, Trash2 } from 'lucide-vue-next'
import StatCard from '../components/StatCard.vue'
import ChartView from '../components/ChartView.vue'
import GitHeatmap from '../components/GitHeatmap.vue'
@@ -38,7 +38,11 @@ const previewLine = ref(0)
// AI 问答抽屉:详情页内的“二级页面”,不跳转
const aiDrawer = ref(false)
const aiAsk = ref('')
const aiDiffHash = ref('')
const askText = ref('')
const insightExcludes = ref([])
const insightExcludeInput = ref('')
const insightExcludeBusy = ref(false)
// 这些检查项的 path 是真实源码文件folder_concentration 是目录、large_commit 是提交哈希,不可预览)
const fileIssueTypes = ['large_file', 'long_file', 'todo_marker']
const colors = ['#7b73ff', '#4fd1a1', '#4da5ff', '#f4c84a', '#ef6683', '#23b5d3']
@@ -69,6 +73,7 @@ async function load() {
;[p.value, git.value, structure.value, insights.value] = await Promise.all([call('GetProject', +route.params.id), call('GetGitStats', +route.params.id), call('GetStructure', +route.params.id), call('GetProjectInsights', +route.params.id)])
try { diag.value = await call('GetGitDiagnostics', +route.params.id) } catch { diag.value = null }
loadProjRules()
loadInsightExcludes()
loading.value = false
}
@@ -82,11 +87,11 @@ async function loadProjRules() {
function onRulesChanged(list) {
projRules.value = list || []
}
async function refreshInsights() {
async function refreshInsights(silent = false) {
insightLoading.value = true
try {
insights.value = await call('RefreshProjectInsights', +route.params.id)
store.showToast({ type: 'success', key: 'insightDone' })
if (!silent) store.showToast({ type: 'success', key: 'insightDone' })
} catch (e) {
store.showToast({ type: 'error', text: String(e) })
} finally {
@@ -131,10 +136,48 @@ async function showCommit(c) {
try { detail.value = await call('GetCommitDetails', +route.params.id, c.hash) } finally { detailLoading.value = false }
}
function openChat(text) {
aiDiffHash.value = ''
aiAsk.value = (text || '').trim()
askText.value = ''
aiDrawer.value = true
}
function analyzeDiff(d) {
const hash = d?.hash || detail.value?.hash || ''
if (!hash) return
aiDiffHash.value = hash
aiAsk.value = t('aiPromptDiff')
askText.value = ''
aiDrawer.value = true
}
async function loadInsightExcludes() {
try { insightExcludes.value = (await call('GetInsightExcludes', +route.params.id)) || [] } catch { insightExcludes.value = [] }
}
async function addInsightExclude() {
const v = insightExcludeInput.value.trim()
const id = +route.params.id
if (!v || !id || insightExcludeBusy.value) return
insightExcludeBusy.value = true
try {
await call('AddInsightExclude', id, v)
insightExcludeInput.value = ''
await loadInsightExcludes()
await refreshInsights(true)
} catch (e) {
const code = String(e).split(':')[0].trim()
store.showToast({ type: 'error', key: code ? `errors.${code}` : null, text: String(e) })
} finally {
insightExcludeBusy.value = false
}
}
async function removeInsightExclude(r) {
try {
await call('DeleteRule', r.id)
await loadInsightExcludes()
await refreshInsights(true)
} catch (e) {
store.showToast({ type: 'error', text: String(e) })
}
}
onMounted(load)
</script>
@@ -216,7 +259,7 @@ onMounted(load)
</div>
</section>
<section class="panel shine-card"><h2>{{ t('contributorRanking') }}</h2><div class="contributor" v-for="(c, i) in git.contributors" :key="c.email"><b>#{{ i + 1 }}</b><span class="avatar">{{ c.name?.[0] }}</span><div><strong>{{ c.name }}</strong><small>{{ c.email }}</small></div><span>{{ c.commits }} {{ t('commitsUnit') }}</span><span class="positive">+{{ fmt(c.added) }}</span><span class="negative">-{{ fmt(c.deleted) }}</span></div><div v-if="!git.contributors?.length" class="empty">{{ t('empty') }}</div></section>
<CommitDrawer v-if="detail" :detail="detail" :loading="detailLoading" @close="detail = null" />
<CommitDrawer v-if="detail" :detail="detail" :loading="detailLoading" @close="detail = null" @analyze="analyzeDiff" />
</template>
<template v-else-if="tab === 'structure'">
@@ -245,7 +288,19 @@ onMounted(load)
<span>{{ insights.summary?.todoCount || 0 }} TODO</span>
</div>
</div>
<button class="btn secondary" :disabled="insightLoading" @click="refreshInsights"><RefreshCw :class="{ spin: insightLoading }" />{{ t('refresh') }}</button>
<button class="btn secondary" :disabled="insightLoading" @click="refreshInsights()"><RefreshCw :class="{ spin: insightLoading }" />{{ t('refresh') }}</button>
</section>
<section class="panel insight-exclude-panel">
<div class="section-head"><h2><ListFilter />{{ t('insightExcludeTitle') }}</h2></div>
<p class="insight-exclude-hint">{{ t('insightExcludeHint') }}</p>
<div class="proj-rules-add">
<input v-model="insightExcludeInput" :placeholder="t('insightExcludePh')" :disabled="insightExcludeBusy" @keyup.enter="addInsightExclude" />
<button type="button" class="btn secondary" :disabled="insightExcludeBusy || !insightExcludeInput.trim()" @click="addInsightExclude"><Plus />{{ t('add') }}</button>
</div>
<div class="proj-rules-chips">
<button v-for="r in insightExcludes" :key="r.id" type="button" class="proj-rule-chip" :title="t('delete')" @click="removeInsightExclude(r)">{{ r.pattern }}<Trash2 /></button>
<span v-if="!insightExcludes.length" class="proj-rules-empty">{{ t('insightExcludeEmpty') }}</span>
</div>
</section>
<section class="panel">
<div class="section-head insight-filter">
@@ -279,7 +334,7 @@ onMounted(load)
</template>
<div class="center-action"><button class="btn secondary" @click="analyze()"><RefreshCw />{{ t('analyze') }}</button></div>
<FilePreviewModal v-if="preview" :project-id="+route.params.id" :path="preview" :line="previewLine" @close="preview = ''; previewLine = 0" />
<ProjectAIDrawer v-if="aiDrawer" :project-id="p.id" :project-name="p.name" :ask="aiAsk" @close="aiDrawer = false; aiAsk = ''" />
<ProjectAIDrawer v-if="aiDrawer" :project-id="p.id" :project-name="p.name" :ask="aiAsk" :diff-hash="aiDiffHash" @close="aiDrawer = false; aiAsk = ''; aiDiffHash = ''" />
<ProjectRulesModal
:open="rulesOpen"
:project-id="p.id"

View File

@@ -16,7 +16,7 @@ const pickTab=v=>TABS.includes(String(v))?String(v):''
const tab=ref(pickTab(route.query.tab)||pickTab(localStorage.getItem('cc-settings-tab'))||'rules'),rules=ref([]),form=reactive({pattern:'',category:'custom'})
const aiOpen=ref(false)
watch(tab,v=>localStorage.setItem('cc-settings-tab',v))
const settings=reactive({theme:'dark',locale:'zh-CN',gitScope:'current',databasePath:'',autoRefresh:true,glassOpacity:55,loadingStyle:'fullscreen-orbit',minimizeToTray:true,autoUpdateEnabled:false,autoUpdateMode:'daily',autoUpdateInterval:1,autoUpdateTime:'09:00',aiProvider:'spark',sparkKey:'',deepSeekKey:'',syncApiKeys:false,avatarMode:'',avatarValue:'',imageMode:'base64'})
const settings=reactive({theme:'dark',locale:'zh-CN',gitScope:'current',databasePath:'',autoRefresh:true,glassOpacity:55,loadingStyle:'fullscreen-orbit',trayMenuStyle:'native',minimizeToTray:true,autoUpdateEnabled:false,autoUpdateMode:'daily',autoUpdateInterval:1,autoUpdateTime:'09:00',aiProvider:'spark',sparkKey:'',deepSeekKey:'',syncApiKeys:false,avatarMode:'',avatarValue:'',imageMode:'base64'})
const store=useAppStore(),{locale,t}=useI18n(),native=isNative(),dbMessage=ref('')
const autostart=ref(false),autostartBusy=ref(false)
const groups=computed(()=>Object.groupBy?Object.groupBy(rules.value,x=>x.category):rules.value.reduce((a,x)=>((a[x.category]??=[]).push(x),a),{}))
@@ -27,11 +27,20 @@ const loadingOptions=[
{value:'fullscreen-matrix',title:'loadingStyleMatrix',desc:'loadingStyleMatrixDesc'},
{value:'bar',title:'loadingStyleBar',desc:'loadingStyleBarDesc'}
]
const trayOptions=[
{value:'native',title:'trayStyleNative',desc:'trayStyleNativeDesc'},
{value:'liquid',title:'trayStyleLiquid',desc:'trayStyleLiquidDesc'},
{value:'glass',title:'trayStyleGlass',desc:'trayStyleGlassDesc'},
{value:'compact',title:'trayStyleCompact',desc:'trayStyleCompactDesc'},
{value:'status',title:'trayStyleStatus',desc:'trayStyleStatusDesc'},
{value:'neon',title:'trayStyleNeon',desc:'trayStyleNeonDesc'}
]
async function load(){
rules.value=await call('GetRules')
const [saved,bootstrap]=await Promise.all([call('GetSettings'),call('GetBootstrapStatus')])
Object.assign(settings,saved)
if(settings.trayMenuStyle==='minimal')settings.trayMenuStyle='compact'
settings.databasePath=bootstrap.databasePath||saved.databasePath||bootstrap.defaultPath||''
try{autostart.value=await call('GetAutostart')}catch{autostart.value=false}
}
@@ -149,7 +158,7 @@ async function migrate(){
}
async function copyPath(){try{await navigator.clipboard.writeText(settings.databasePath);store.showToast({type:'success',key:'dbPathCopied'})}catch{store.showToast({type:'error',key:'dbCopyFail'})}}
async function clear(mode){const id=mode==='project'?Number(prompt(t('projectIdPrompt'))):0;if(mode==='project'&&!id)return;if(confirm(t('confirmIrreversible'))){await call('ClearData',mode,id);await store.refresh()}}
watch(()=>[settings.theme,settings.locale,settings.glassOpacity,settings.loadingStyle,settings.gitScope,settings.minimizeToTray,settings.autoUpdateEnabled,settings.autoUpdateMode,settings.autoUpdateInterval,settings.autoUpdateTime,settings.aiProvider,settings.syncApiKeys,settings.avatarMode,settings.avatarValue,settings.imageMode],save)
watch(()=>[settings.theme,settings.locale,settings.glassOpacity,settings.loadingStyle,settings.trayMenuStyle,settings.gitScope,settings.minimizeToTray,settings.autoUpdateEnabled,settings.autoUpdateMode,settings.autoUpdateInterval,settings.autoUpdateTime,settings.aiProvider,settings.syncApiKeys,settings.avatarMode,settings.avatarValue,settings.imageMode],save)
let aiKeyTimer=null
watch(()=>[settings.sparkKey,settings.deepSeekKey],()=>{clearTimeout(aiKeyTimer);aiKeyTimer=setTimeout(save,600)})
watch(()=>route.query.tab,v=>{const n=pickTab(v);if(n)tab.value=n})
@@ -162,7 +171,9 @@ onUnmounted(()=>{clearTimeout(aiKeyTimer)})
<div class="actions"><button class="btn secondary" @click="aiOpen=true"><Sparkles/>{{t('aiScopeBtn')}}</button></div>
</header>
<template v-if="tab==='rules'"><section class="panel rule-add"><h2><Plus/>{{t('addRule')}}</h2><div><input v-model="form.pattern" :placeholder="t('rulePatternPh')" @keyup.enter="add"/><select v-model="form.category"><option value="general">{{t('catGeneral')}}</option><option value="php">PHP</option><option value="go">Go</option><option value="vue">Vue/JS</option><option value="custom">{{t('catCustom')}}</option></select><button class="btn primary" @click="add"><Plus/>{{t('add')}}</button></div><small>{{t('ruleHint')}}</small></section><section v-for="(items,name) in groups" :key="name" class="panel rule-group"><h2>{{name}} <small>{{t('rulesCount',{n:items.length})}}</small></h2><div><button v-for="r in items" :key="r.id" :class="{builtin:r.builtin}" @click="remove(r)">{{r.pattern}}<small v-if="r.builtin">{{t('builtinTag')}}</small><Trash2 v-else/></button></div></section></template>
<template v-else-if="tab==='appearance'"><section class="panel form-panel"><h2><Languages/>{{t('langThemeTitle')}}</h2><label>{{t('uiLanguage')}}<select v-model="settings.locale"><option value="zh-CN">简体中文</option><option value="en">English</option></select></label><label>{{t('theme')}}<select v-model="settings.theme"><option value="dark">{{t('themeDark')}}</option><option value="light">{{t('themeLight')}}</option><option value="system">{{t('themeSystem')}}</option></select></label><label>{{t('gitScopeDefault')}}<select v-model="settings.gitScope"><option value="current">{{t('scopeCurrent')}}</option><option value="all">{{t('scopeAll')}}</option></select></label><div class="loading-style-setting"><span>{{t('loadingStyle')}}</span><div class="loading-style-grid" role="radiogroup" :aria-label="t('loadingStyle')"><button v-for="option in loadingOptions" :key="option.value" type="button" role="radio" :aria-checked="settings.loadingStyle===option.value" :class="['loading-style-card',option.value,{active:settings.loadingStyle===option.value}]" @click="settings.loadingStyle=option.value"><span class="loading-style-preview" aria-hidden="true"><i/></span><b>{{t(option.title)}}</b><small>{{t(option.desc)}}</small></button></div></div><label class="opacity-setting"><span>{{t('glassOpacity')}} <b>{{settings.glassOpacity}}%</b></span><input v-model.number="settings.glassOpacity" type="range" min="30" max="75" step="1"/></label></section>
<template v-else-if="tab==='appearance'"><section class="panel form-panel"><h2><Languages/>{{t('langThemeTitle')}}</h2><label>{{t('uiLanguage')}}<select v-model="settings.locale"><option value="zh-CN">简体中文</option><option value="en">English</option></select></label><label>{{t('theme')}}<select v-model="settings.theme"><option value="dark">{{t('themeDark')}}</option><option value="light">{{t('themeLight')}}</option><option value="system">{{t('themeSystem')}}</option></select></label><label>{{t('gitScopeDefault')}}<select v-model="settings.gitScope"><option value="current">{{t('scopeCurrent')}}</option><option value="all">{{t('scopeAll')}}</option></select></label><div class="loading-style-setting"><span>{{t('loadingStyle')}}</span><div class="loading-style-grid" role="radiogroup" :aria-label="t('loadingStyle')"><button v-for="option in loadingOptions" :key="option.value" type="button" role="radio" :aria-checked="settings.loadingStyle===option.value" :class="['loading-style-card',option.value,{active:settings.loadingStyle===option.value}]" @click="settings.loadingStyle=option.value"><span class="loading-style-preview" aria-hidden="true"><i/></span><b>{{t(option.title)}}</b><small>{{t(option.desc)}}</small></button></div></div>
<div class="tray-style-setting"><span>{{t('trayMenuStyle')}}</span><div class="tray-style-grid" role="radiogroup" :aria-label="t('trayMenuStyle')"><button v-for="option in trayOptions" :key="option.value" type="button" role="radio" :aria-checked="settings.trayMenuStyle===option.value" :class="['tray-style-card',option.value,{active:settings.trayMenuStyle===option.value}]" @click="settings.trayMenuStyle=option.value"><span class="tray-style-preview" aria-hidden="true"><span class="tsp-menu"><i/><i/><i/><i/><i/><i/><i/><i/><i/><i/></span></span><b>{{t(option.title)}}</b><small>{{t(option.desc)}}</small></button></div></div>
<label class="opacity-setting"><span>{{t('glassOpacity')}} <b>{{settings.glassOpacity}}%</b></span><input v-model.number="settings.glassOpacity" type="range" min="30" max="75" step="1"/></label></section>
<section class="panel form-panel"><h2><Rocket/>{{t('sysIntegration')}}</h2>
<label>{{t('onWindowClose')}}<select v-model="settings.minimizeToTray"><option :value="true">{{t('closeToTray')}}</option><option :value="false">{{t('closeQuit')}}</option></select></label>
<label>{{t('autostartLabel')}}<div class="autostart-row"><button type="button" class="btn secondary" :disabled="autostartBusy||!native" @click="toggleAutostart">{{autostart?t('autostartOnBtn'):t('autostartOffBtn')}}</button><small>{{autostart?t('autostartOnHint'):t('autostartOffHint')}}</small></div></label>

View File

@@ -0,0 +1,141 @@
<script setup>
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { LayoutDashboard, LayoutGrid, RefreshCw, CalendarCheck2, ListTodo, TicketCheck, Bell, Sparkles, Folder, Power, RotateCcw, Check, BarChart3 } from 'lucide-vue-next'
import { call, on } from '../api'
import { useAppStore } from '../store'
const { t, locale } = useI18n()
const store = useAppStore()
const root = ref(null)
const state = ref({
style: 'status', locale: 'zh-CN', theme: 'dark', status: 'signedOut', statusLabel: '',
username: '', loggedIn: false, unread: 0, todayDue: 0, pending: 0, autostart: false,
projects: [], hasMoreProjects: false
})
const projectsOpen = ref(false)
const busy = ref('')
let offRefresh
let offShown
let blurTimer
let blurArmed = false
let fitTimer
const style = computed(() => {
const s = state.value.style === 'minimal' ? 'compact' : (state.value.style || 'status')
return s === 'native' ? 'status' : s
})
const dense = computed(() => style.value !== 'status')
const items = computed(() => [
{ key: 'show', icon: LayoutDashboard, label: t('trayShow'), run: () => act('show') },
{ key: 'pad', icon: LayoutGrid, label: t('trayLaunchpad'), run: () => act('nav', '/launchpad') },
{ key: 'today', icon: CalendarCheck2, label: t('trayToday'), run: () => act('nav', '/today') },
{ key: 'todos', icon: ListTodo, label: t('trayTodos'), run: () => act('nav', '/todos') },
{ key: 'tickets', icon: TicketCheck, label: t('trayTickets'), run: () => act('nav', '/tickets') },
{ key: 'messages', icon: Bell, label: t('trayMessages'), run: () => act('nav', '/messages') },
{ key: 'ai', icon: Sparkles, label: t('aiHub'), run: () => act('nav', '/ai') },
{ key: 'projects', icon: Folder, label: t('trayProjects'), run: () => { projectsOpen.value = !projectsOpen.value }, on: () => projectsOpen.value },
{ key: 'sync', icon: RefreshCw, label: t('traySync'), run: () => act('sync') },
{ key: 'batch', icon: BarChart3, label: t('trayBatchShort'), run: () => act('batch') },
{ key: 'auto', icon: Check, label: t('trayAutostart'), run: () => act('autostart'), on: () => state.value.autostart },
{ key: 'restart', icon: RotateCcw, label: t('trayRestart'), run: () => act('restart') },
{ key: 'quit', icon: Power, label: t('trayQuit'), run: () => act('quit'), danger: true }
])
const groups = computed(() => dense.value
? [items.value.slice(0, 8), items.value.slice(8, 11), items.value.slice(11)]
: [items.value])
async function load() {
try {
const next = await call('GetTrayMenuState')
state.value = { ...state.value, ...next, projects: next.projects || [] }
if (next.locale) locale.value = next.locale
store.applyAppearance({ theme: next.theme, locale: next.locale, glassOpacity: store.settings.glassOpacity })
await nextTick()
fit()
} catch { /* 启动早期数据库未就绪时等下一次 tray:refresh */ }
}
function fit() {
const el = root.value
if (!el) return
clearTimeout(fitTimer)
fitTimer = setTimeout(() => {
const w = Math.ceil(Math.max(el.offsetWidth, el.scrollWidth))
const h = Math.ceil(Math.max(el.offsetHeight, el.scrollHeight)) + 2
if (w < 8 || h < 8) return
call('FitTrayPopup', w, h).catch(() => {})
}, 16)
}
function armBlur() {
blurArmed = false
clearTimeout(blurTimer)
blurTimer = setTimeout(() => { blurArmed = true }, 400)
}
function onWinBlur() {
if (!blurArmed) return
call('HideTrayPopup').catch(() => {})
}
async function act(action, arg = '') {
if (busy.value) return
busy.value = action
try {
await call('TrayMenuAction', action, String(arg || ''))
if (action === 'autostart') await load()
} catch { /* 弹层即将关闭或退出 */ }
finally { busy.value = '' }
}
watch(projectsOpen, async () => { await nextTick(); fit() })
watch(style, async () => { await nextTick(); fit() })
onMounted(async () => {
document.documentElement.classList.add('tray-window')
await load()
offRefresh = on('tray:refresh', load)
offShown = on('tray:shown', () => { armBlur(); fit() })
armBlur()
addEventListener('blur', onWinBlur)
})
onUnmounted(() => {
offRefresh?.()
offShown?.()
clearTimeout(blurTimer)
clearTimeout(fitTimer)
removeEventListener('blur', onWinBlur)
})
</script>
<template>
<div ref="root" class="tray-pop" :class="['skin-' + style, 'st-' + state.status, { dense }]">
<header class="tray-pop-head" @click="act('sync')">
<i class="tray-dot" aria-hidden="true" />
<b>{{ state.statusLabel || t('trayStatusSignedOut') }}</b>
<em v-if="state.unread" @click.stop="act('nav', '/messages')">{{ state.unread }}</em>
<em v-if="state.todayDue" class="due" @click.stop="act('nav', '/today')">{{ state.todayDue }}</em>
</header>
<template v-for="(group, gi) in groups" :key="gi">
<i v-if="gi" class="tray-sep" aria-hidden="true" />
<div class="tray-grid">
<button
v-for="it in group"
:key="it.key"
type="button"
:class="{ on: it.on?.(), danger: it.danger }"
@click="it.run"
>
<component :is="it.icon" />
<span>{{ it.label }}</span>
</button>
</div>
</template>
<div v-if="projectsOpen && state.projects.length" class="tray-projects">
<button v-for="p in state.projects" :key="p.id" type="button" @click="act('project', p.id)">{{ p.name }}</button>
<button v-if="state.hasMoreProjects" type="button" class="more" @click="act('nav', '/projects')">{{ t('trayAllProjects') }}</button>
</div>
</div>
</template>

View File

@@ -75,6 +75,9 @@ func TestGitRefDetailsAndSafeCheckout(t *testing.T) {
if len(detail.Files) == 0 {
t.Fatal("commit files missing")
}
if detail.Files[0].Patch == "" || !strings.Contains(detail.Files[0].Patch, "+// feature") {
t.Fatalf("commit patch missing: %#v", detail.Files[0])
}
if e = os.WriteFile(filepath.Join(d, "dirty.txt"), []byte("dirty"), 0644); e != nil {
t.Fatal(e)
}

View File

@@ -39,6 +39,8 @@ func main() {
Windows: application.WindowsOptions{
// Opt-in DevTools protocol endpoint for automated UI testing; inert unless the env var is set.
AdditionalBrowserArgs: devtoolsArgs(),
// 托盘弹层是第二个窗口;被销毁时不能把整个进程一起带走。
DisableQuitOnLastWindowClosed: true,
},
// 单实例:第二个进程启动时通过 Wails 内置的 WM_COPYDATA / DBus 通道
// 通知首个进程,回调里唤起已存在的主窗口并切到前台。

View File

@@ -163,10 +163,13 @@ type InsightIssue struct {
Evidence string `json:"evidence,omitempty"`
}
type GitFileChange struct {
Path string `json:"path"`
Status string `json:"status"`
Added int64 `json:"added"`
Deleted int64 `json:"deleted"`
Path string `json:"path"`
Status string `json:"status"`
Added int64 `json:"added"`
Deleted int64 `json:"deleted"`
Patch string `json:"patch,omitempty"`
Binary bool `json:"binary,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
type GitCommitDetail struct {
GitCommit
@@ -250,7 +253,9 @@ type AppSettings struct {
GlassOpacity int `json:"glassOpacity"`
LoadingStyle string `json:"loadingStyle"`
// 托盘与定时更新Phase 2
MinimizeToTray bool `json:"minimizeToTray"`
MinimizeToTray bool `json:"minimizeToTray"`
// TrayMenuStylenative 系统菜单liquid 液态玻璃glass 亚克力compact 紧凑宫格status 看板neon HUD。
TrayMenuStyle string `json:"trayMenuStyle"`
AutoUpdateEnabled bool `json:"autoUpdateEnabled"`
AutoUpdateMode string `json:"autoUpdateMode"` // daily | everyNDays | everyNHours
AutoUpdateInterval int `json:"autoUpdateInterval"` // everyNDays/everyNHours 的 N

View File

@@ -13,3 +13,8 @@ func configureHidden(_ *exec.Cmd) {}
func ConfigureDetached(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
// ConfigureUpdaterHelper 非 Windows 仅放入独立进程组。
func ConfigureUpdaterHelper(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}

View File

@@ -17,3 +17,10 @@ func configureHidden(cmd *exec.Cmd) {
func ConfigureDetached(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000 | 0x00000200}
}
// ConfigureUpdaterHelper 启动更新辅助脚本:隐藏控制台,并尽量脱离父进程作业对象,
// 避免主程序退出时把安装器一起杀掉。
// CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB
func ConfigureUpdaterHelper(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000 | 0x00000200 | 0x01000000}
}

View File

@@ -14,3 +14,15 @@ func TestConfigureHidden(t *testing.T) {
t.Fatalf("hidden process flags missing: %#v", c.SysProcAttr)
}
}
func TestConfigureUpdaterHelper(t *testing.T) {
c := exec.Command("cmd.exe", "/c", "exit", "0")
ConfigureUpdaterHelper(c)
if c.SysProcAttr == nil || !c.SysProcAttr.HideWindow {
t.Fatalf("updater helper should hide console: %#v", c.SysProcAttr)
}
flags := c.SysProcAttr.CreationFlags
if flags&0x08000000 == 0 || flags&0x00000200 == 0 || flags&0x01000000 == 0 {
t.Fatalf("updater helper flags missing: %#v", c.SysProcAttr)
}
}

View File

@@ -39,7 +39,14 @@ func TestWildcardMatch(t *testing.T) {
cases := []struct {
p, s string
want bool
}{{"*.log", "storage/app.log", true}, {"vendor", "vendor/a.php", true}, {"dist", "src/main.js", false}}
}{
{"*.log", "storage/app.log", true},
{"vendor", "vendor/a.php", true},
{"dist", "src/main.js", false},
{"src/todo", "src/todo", true},
{"src/todo", "src/todo/list.go", true},
{"src/todo", "src/other/list.go", false},
}
for _, c := range cases {
if got := wildcardMatch(c.p, c.s); got != c.want {
t.Errorf("%s %s = %v", c.p, c.s, got)

View File

@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
"fmt"
"os/exec"
"sort"
"strconv"
@@ -259,9 +260,181 @@ func (g GitService) CommitDetail(ctx context.Context, dir, hash string) (model.G
d.Added += a
d.Deleted += del
}
if patch, e := g.run(ctx, dir, "show", "--format=", "--patch", "--no-color", "--unified=3", hash); e == nil {
attachCommitPatches(&d, patch)
}
return d, nil
}
const (
maxPatchLines = 500
maxPatchBytes = 80_000
maxPatchBytesTotal = 400_000
)
type parsedPatch struct {
Path string
Text string
Binary bool
Truncated bool
}
func attachCommitPatches(d *model.GitCommitDetail, raw string) {
patches := parseCommitPatches(raw)
used := 0
for i := range d.Files {
key := patchFileKey(d.Files[i].Path)
p, ok := patches[key]
if !ok {
p, ok = patches[d.Files[i].Path]
}
if !ok {
continue
}
d.Files[i].Binary = p.Binary
if p.Binary {
continue
}
if used+len(p.Text) > maxPatchBytesTotal {
d.Files[i].Truncated = true
continue
}
d.Files[i].Patch = p.Text
d.Files[i].Truncated = p.Truncated
used += len(p.Text)
}
}
func patchFileKey(path string) string {
if i := strings.LastIndex(path, " => "); i >= 0 {
return strings.Trim(path[i+4:], "{}")
}
return path
}
func parseCommitPatches(raw string) map[string]parsedPatch {
out := map[string]parsedPatch{}
raw = strings.ReplaceAll(strings.TrimSpace(raw), "\r\n", "\n")
if raw == "" {
return out
}
parts := strings.Split(raw, "\ndiff --git ")
for i, part := range parts {
if i == 0 {
if !strings.HasPrefix(part, "diff --git ") {
continue
}
} else {
part = "diff --git " + part
}
p := parseOneDiff(part)
if p.Path == "" {
continue
}
out[p.Path] = p
}
return out
}
func parseOneDiff(block string) parsedPatch {
p := parsedPatch{Path: diffPath(block)}
if strings.Contains(block, "Binary files ") || strings.Contains(block, "GIT binary patch") {
p.Binary = true
return p
}
lines := strings.Split(block, "\n")
kept := make([]string, 0, len(lines))
for _, line := range lines {
if strings.HasPrefix(line, "diff --git ") || strings.HasPrefix(line, "index ") || strings.HasPrefix(line, "new file mode ") || strings.HasPrefix(line, "deleted file mode ") || strings.HasPrefix(line, "similarity index ") || strings.HasPrefix(line, "rename ") || strings.HasPrefix(line, "copy ") {
continue
}
kept = append(kept, line)
}
text := strings.Join(kept, "\n")
if n := strings.Count(text, "\n") + 1; n > maxPatchLines {
kept = strings.Split(text, "\n")[:maxPatchLines]
text = strings.Join(kept, "\n")
p.Truncated = true
}
if len(text) > maxPatchBytes {
text = text[:maxPatchBytes]
p.Truncated = true
}
p.Text = strings.TrimRight(text, "\n")
return p
}
func diffPath(block string) string {
for _, line := range strings.Split(block, "\n") {
if strings.HasPrefix(line, "+++ b/") {
return strings.TrimPrefix(line, "+++ b/")
}
if strings.HasPrefix(line, "+++ /dev/null") {
continue
}
if strings.HasPrefix(line, "--- a/") {
fallback := strings.TrimPrefix(line, "--- a/")
if fallback != "/dev/null" {
// 删除文件没有 +++ b/,用旧路径
if !strings.Contains(block, "+++ b/") {
return fallback
}
}
}
}
first, _, _ := strings.Cut(block, "\n")
rest := strings.TrimPrefix(first, "diff --git ")
if i := strings.LastIndex(rest, " b/"); i >= 0 {
return strings.Trim(rest[i+3:], `"`)
}
return ""
}
const aiDiffMaxBytes = 80_000
// FormatCommitDiffForAI 把提交明细收成给模型看的文本,超长时省略部分文件 patch。
func FormatCommitDiffForAI(d model.GitCommitDetail, maxBytes int) string {
if maxBytes <= 0 {
maxBytes = aiDiffMaxBytes
}
var b strings.Builder
fmt.Fprintf(&b, "## 本次提交\n- 哈希: %s\n- 作者: %s <%s>\n- 时间: %s\n- 说明: %s\n- 变更: +%d / -%d共 %d 个文件\n",
d.Hash, d.Author, d.Email, d.Date, d.Message, d.Added, d.Deleted, len(d.Files))
b.WriteString("\n## 变更文件\n")
for i, f := range d.Files {
if i >= 80 {
fmt.Fprintf(&b, "- … 其余 %d 个文件已省略\n", len(d.Files)-i)
break
}
note := ""
if f.Binary {
note = " [binary]"
} else if f.Truncated {
note = " [truncated]"
}
fmt.Fprintf(&b, "- %s %s +%d/-%d%s\n", f.Status, f.Path, f.Added, f.Deleted, note)
}
b.WriteString("\n## Diff\n")
used := 0
omitted := 0
for _, f := range d.Files {
if f.Binary || f.Patch == "" {
continue
}
block := fmt.Sprintf("### %s\n```diff\n%s\n```\n", f.Path, f.Patch)
if used+len(block) > maxBytes {
omitted++
continue
}
b.WriteString(block)
used += len(block)
}
if omitted > 0 {
fmt.Fprintf(&b, "\n另有 %d 个文件的 diff 因过长未纳入)\n", omitted)
}
return b.String()
}
// CheckoutBranch 在修改工作区前先检查已跟踪和未跟踪变更;发现任何内容都拒绝切换。
func (g GitService) CheckoutBranch(ctx context.Context, dir, ref string) (model.CheckoutResult, error) {
dirty, e := g.run(ctx, dir, "status", "--porcelain")

68
service/git_patch_test.go Normal file
View File

@@ -0,0 +1,68 @@
package service
import (
"strings"
"testing"
"view/model"
)
func TestParseCommitPatches(t *testing.T) {
raw := `diff --git a/main.go b/main.go
index 111..222 100644
--- a/main.go
+++ b/main.go
@@ -1,2 +1,3 @@
package main
+// feature
`
got := parseCommitPatches(raw)
p, ok := got["main.go"]
if !ok || p.Binary || p.Text == "" {
t.Fatalf("patch=%#v", got)
}
if !strings.Contains(p.Text, "+// feature") {
t.Fatalf("missing added line: %q", p.Text)
}
}
func TestParseCommitPatchesBinaryAndDelete(t *testing.T) {
raw := `diff --git a/logo.png b/logo.png
index 111..222 100644
Binary files a/logo.png and b/logo.png differ
diff --git a/gone.go b/gone.go
deleted file mode 100644
index 111..000
--- a/gone.go
+++ /dev/null
@@ -1 +0,0 @@
-package gone
`
got := parseCommitPatches(raw)
if !got["logo.png"].Binary {
t.Fatalf("binary not marked: %#v", got["logo.png"])
}
if got["gone.go"].Text == "" || got["gone.go"].Binary {
t.Fatalf("deleted file patch=%#v", got["gone.go"])
}
}
func TestFormatCommitDiffForAI(t *testing.T) {
d := model.GitCommitDetail{
GitCommit: model.GitCommit{Hash: "abc123", Author: "Ann", Email: "a@b.c", Date: "2026-08-19", Message: "add feature", Added: 2, Deleted: 1},
Files: []model.GitFileChange{
{Path: "main.go", Status: "modified", Added: 2, Deleted: 1, Patch: "+// feature\n-old"},
{Path: "logo.png", Status: "modified", Binary: true},
},
}
text := FormatCommitDiffForAI(d, 0)
if !strings.Contains(text, "add feature") || !strings.Contains(text, "main.go") || !strings.Contains(text, "+// feature") {
t.Fatalf("unexpected prompt:\n%s", text)
}
if !strings.Contains(text, "[binary]") {
t.Fatal("binary file should be listed")
}
tiny := FormatCommitDiffForAI(d, 80)
if !strings.Contains(tiny, "因过长未纳入") && !strings.Contains(tiny, "add feature") {
t.Fatalf("truncated prompt:\n%s", tiny)
}
}

View File

@@ -21,7 +21,7 @@ const (
// 它不会重新遍历整个仓库,只读取已记录的小型源码文件,用于发现 TODO、长文件等轻量风险。
type InsightService struct{}
func (InsightService) Analyze(ctx context.Context, project model.Project, structure model.StructureStats, git model.GitStats) (model.ProjectInsights, error) {
func (InsightService) Analyze(ctx context.Context, project model.Project, structure model.StructureStats, git model.GitStats, excludes []model.ExclusionRule) (model.ProjectInsights, error) {
desc, e := platform.ResolvePath(project.Path)
if e != nil {
return model.ProjectInsights{}, e
@@ -40,6 +40,7 @@ func (InsightService) Analyze(ctx context.Context, project model.Project, struct
}
checkLanguageHealth(project.Languages, add)
structure = filterStructureForInsights(structure, excludes)
out.Summary.LargeFiles = len(structure.LargeFiles)
checkStructureHealth(structure, add)
checkGitHealth(git, add)
@@ -162,7 +163,7 @@ func inspectTextFile(path string) (int, []model.InsightIssue) {
kind, severity = "FIXME", "medium"
case strings.Contains(upper, "HACK"):
kind, severity = "HACK", "medium"
case strings.Contains(upper, "TODO"):
case hasUpperTODO(text):
kind = "TODO"
}
if kind != "" {
@@ -172,6 +173,70 @@ func inspectTextFile(path string) (int, []model.InsightIssue) {
return line, issues
}
func filterStructureForInsights(s model.StructureStats, rules []model.ExclusionRule) model.StructureStats {
if len(rules) == 0 {
return s
}
out := s
out.Files = out.Files[:0:0]
out.LargeFiles = out.LargeFiles[:0:0]
out.Folders = out.Folders[:0:0]
for _, f := range s.Files {
if pathExcluded(f.Path, rules) {
continue
}
out.Files = append(out.Files, f)
}
for _, f := range s.LargeFiles {
if pathExcluded(f.Path, rules) {
continue
}
out.LargeFiles = append(out.LargeFiles, f)
}
for _, f := range s.Folders {
if pathExcluded(f.Name, rules) {
continue
}
out.Folders = append(out.Folders, f)
}
return out
}
func pathExcluded(path string, rules []model.ExclusionRule) bool {
path = strings.TrimSpace(path)
if path == "" || len(rules) == 0 {
return false
}
slash := filepath.ToSlash(path)
for _, r := range rules {
if MatchExcludedPattern(r.Pattern, slash) {
return true
}
}
return false
}
// hasUpperTODO 只认大写 TODO 标记,避免命中 todo 表名、模块名或变量。
func hasUpperTODO(text string) bool {
for i := 0; i <= len(text)-4; i++ {
if text[i:i+4] != "TODO" {
continue
}
if i > 0 && isIdentByte(text[i-1]) {
continue
}
if i+4 < len(text) && isIdentByte(text[i+4]) {
continue
}
return true
}
return false
}
func isIdentByte(b byte) bool {
return b == '_' || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
}
func isInsightTextFile(ext string) bool {
switch strings.ToLower(ext) {
case ".go", ".php", ".js", ".ts", ".vue", ".jsx", ".tsx", ".css", ".scss", ".sass", ".less", ".html", ".md", ".json", ".yaml", ".yml", ".xml", ".sql", ".py", ".java", ".cs", ".rb", ".rs", ".c", ".cpp", ".h":

66
service/insights_test.go Normal file
View File

@@ -0,0 +1,66 @@
package service
import (
"testing"
"view/model"
)
func TestHasUpperTODO(t *testing.T) {
cases := []struct {
text string
want bool
}{
{"// TODO: fix later", true},
{"# TODO", true},
{" TODO()", true},
{"create table todo", false},
{"type TodoService struct {}", false},
{"const todos = []", false},
{"TODOS := 1", false},
{"myTODO", false},
{"TODO_ITEM", false},
{"// todo: later", false},
{"// Todo: later", false},
}
for _, c := range cases {
if got := hasUpperTODO(c.text); got != c.want {
t.Errorf("hasUpperTODO(%q) = %v, want %v", c.text, got, c.want)
}
}
}
func TestPathExcludedAndFilterStructure(t *testing.T) {
rules := []model.ExclusionRule{{Pattern: "vendor"}, {Pattern: "src/todo"}, {Pattern: "*.pb.go"}}
if !pathExcluded("vendor/lib.go", rules) {
t.Fatal("vendor dir should be excluded")
}
if !pathExcluded("src/todo/list.go", rules) {
t.Fatal("src/todo dir should be excluded")
}
if !pathExcluded("api/user.pb.go", rules) {
t.Fatal("*.pb.go should be excluded")
}
if pathExcluded("src/app/main.go", rules) {
t.Fatal("normal source should stay")
}
s := model.StructureStats{
Files: []model.FileEntry{
{Path: "src/app/main.go"},
{Path: "vendor/lib.go"},
{Path: "src/todo/list.go"},
},
LargeFiles: []model.FileEntry{{Path: "vendor/huge.bin"}},
Folders: []model.FolderStat{{Name: "vendor"}, {Name: "src"}},
}
got := filterStructureForInsights(s, rules)
if len(got.Files) != 1 || got.Files[0].Path != "src/app/main.go" {
t.Fatalf("files=%#v", got.Files)
}
if len(got.LargeFiles) != 0 {
t.Fatalf("large=%#v", got.LargeFiles)
}
if len(got.Folders) != 1 || got.Folders[0].Name != "src" {
t.Fatalf("folders=%#v", got.Folders)
}
}

View File

@@ -9,6 +9,7 @@ import (
gitignore "github.com/sabhiram/go-gitignore"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strings"
@@ -23,12 +24,22 @@ type Scanner struct{}
func MatchExcludedPattern(pattern, rel string) bool {
pattern = filepath.ToSlash(strings.TrimSpace(pattern))
rel = filepath.ToSlash(rel)
if pattern == "" || rel == "" {
return false
}
if strings.Contains(pattern, "/") {
ok, _ := filepath.Match(filepath.FromSlash(pattern), filepath.FromSlash(rel))
pattern = strings.TrimSuffix(pattern, "/")
if ok, _ := path.Match(pattern, rel); ok {
return true
}
if strings.HasPrefix(rel, pattern+"/") {
return true
}
ok, _ := path.Match(pattern+"/*", rel)
return ok
}
for _, part := range strings.Split(rel, "/") {
if ok, _ := filepath.Match(pattern, part); ok {
if ok, _ := path.Match(pattern, part); ok {
return true
}
}

View File

@@ -72,10 +72,14 @@ func shellTexts(locale string) shellText {
// shellState 保存原生外壳(窗口/托盘/菜单)的运行引用。
type shellState struct {
wapp *application.App
win *application.WebviewWindow
tray *application.SystemTray
quitting atomic.Bool
wapp *application.App
win *application.WebviewWindow
tray *application.SystemTray
popup *application.WebviewWindow
popupReady atomic.Bool
popupScheduled atomic.Bool
popupShownAt atomic.Int64
quitting atomic.Bool
}
// SetupShell 在窗口创建后接管关闭行为,并挂载原生菜单与系统托盘。
@@ -109,8 +113,21 @@ func (a *App) SetupShell(wapp *application.App, win *application.WebviewWindow)
a.shell.tray.SetIcon(appIcon)
a.shell.tray.OnClick(a.showMainWindow)
a.shell.tray.OnDoubleClick(a.showMainWindow)
a.shell.tray.OnRightClick(a.onTrayRightClick)
a.wireNotificationClicks()
a.RefreshShell()
a.scheduleTrayPopup()
}
func (a *App) onTrayRightClick() {
if a.trayMenuStyle() != "native" && a.shell != nil && a.shell.popupReady.Load() {
a.showTrayPopup()
return
}
a.hideTrayPopup()
if a.shell != nil && a.shell.tray != nil {
a.shell.tray.OpenMenu()
}
}
// wireNotificationClicks 点击系统通知时唤起窗口并跳到对应页面。
@@ -180,9 +197,14 @@ func (a *App) refreshTray(t shellText, locale string) {
st := a.collectTrayStatus()
a.shell.tray.SetTooltip(st.tooltip(locale))
a.shell.tray.SetIcon(trayIconWithBadge(appIcon, st.badgeColor()))
// 原生菜单始终挂上:自定义弹层没就绪时右键仍走 OpenMenu。刷新图标时不重绑点击、不藏已打开的弹层。
a.shell.tray.SetMenu(a.buildTrayMenu(t, st))
a.shell.tray.OnClick(a.showMainWindow)
a.shell.tray.OnDoubleClick(a.showMainWindow)
if a.trayMenuStyle() == "native" {
a.hideTrayPopup()
} else {
a.scheduleTrayPopup()
}
a.emit("tray:refresh", nil)
}
// RefreshTrayStatus 轻量刷新托盘状态(同步/消息变更时调用,不重建应用菜单)。
@@ -377,6 +399,7 @@ func (a *App) navigateTo(path string) {
}
func (a *App) showMainWindow() {
a.hideTrayPopup()
if a.shell == nil || a.shell.win == nil {
return
}

238
tray_menu.go Normal file
View File

@@ -0,0 +1,238 @@
package main
import (
"errors"
"strconv"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
)
// TrayProjectItem 是自定义托盘弹层里的项目快捷项。
type TrayProjectItem struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
// TrayMenuState 是自定义托盘弹层的完整快照。
type TrayMenuState struct {
Style string `json:"style"`
Locale string `json:"locale"`
Theme string `json:"theme"`
Status string `json:"status"`
StatusLabel string `json:"statusLabel"`
Username string `json:"username"`
LoggedIn bool `json:"loggedIn"`
Unread int `json:"unread"`
TodayDue int `json:"todayDue"`
Pending int `json:"pending"`
Autostart bool `json:"autostart"`
Projects []TrayProjectItem `json:"projects"`
HasMoreProjects bool `json:"hasMoreProjects"`
}
func (a *App) trayMenuStyle() string {
if a.store == nil {
return "native"
}
st, e := a.store.Settings()
if e != nil || !validTrayMenuStyle(st.TrayMenuStyle) {
return "native"
}
return normalizeTrayMenuStyle(st.TrayMenuStyle)
}
func (a *App) scheduleTrayPopup() {
if a.shell == nil || a.trayMenuStyle() == "native" || a.shell.popup != nil {
return
}
if !a.shell.popupScheduled.CompareAndSwap(false, true) {
return
}
go func() {
time.Sleep(1500 * time.Millisecond)
application.InvokeAsync(func() {
if a.shell == nil || a.trayMenuStyle() == "native" || a.shell.popup != nil {
return
}
a.createTrayPopup()
})
}()
}
func (a *App) createTrayPopup() {
if a.shell == nil || a.shell.wapp == nil || a.shell.tray == nil || a.shell.popup != nil {
return
}
popup := a.shell.wapp.Window.NewWithOptions(application.WebviewWindowOptions{
Name: "tray-popup",
Title: "Tray Menu",
Width: 300,
Height: 348,
URL: "/tray.html",
Frameless: true,
AlwaysOnTop: true,
Hidden: true,
HideOnFocusLost: false,
HideOnEscape: true,
DisableResize: true,
DefaultContextMenuDisabled: true,
BackgroundColour: application.NewRGBA(13, 18, 28, 255),
Windows: application.WindowsWindow{
DisableMenu: true,
HiddenOnTaskbar: true,
},
})
popup.RegisterHook(events.Common.WindowClosing, func(e *application.WindowEvent) {
popup.Hide()
e.Cancel()
})
popup.OnWindowEvent(events.Common.WindowLostFocus, func(*application.WindowEvent) {
if a.shell == nil {
return
}
shown := a.shell.popupShownAt.Load()
if shown == 0 || time.Since(time.Unix(0, shown)) < 600*time.Millisecond {
return
}
a.hideTrayPopup()
})
a.shell.popup = popup
}
func (a *App) showTrayPopup() {
if a.shell == nil || a.shell.popup == nil || !a.shell.popupReady.Load() {
return
}
popup := a.shell.popup
if popup.IsVisible() {
popup.Hide()
return
}
if a.shell.tray != nil {
_ = a.shell.tray.PositionWindow(popup, 8)
}
a.shell.popupShownAt.Store(time.Now().UnixNano())
popup.Show()
activateTrayPopup(popup)
a.emit("tray:shown", nil)
}
func (a *App) hideTrayPopup() {
if a.shell == nil || a.shell.popup == nil {
return
}
a.shell.popup.Hide()
}
// HideTrayPopup 供弹层在失焦时自行关闭。
func (a *App) HideTrayPopup() {
a.hideTrayPopup()
}
// TrayPopupReady 轻量托盘页加载完成后调用;此前右键一律走原生菜单。
func (a *App) TrayPopupReady() {
if a.shell != nil {
a.shell.popupReady.Store(true)
}
}
// FitTrayPopup 保留给旧绑定;不再改窗口尺寸,避免 WebView2 在 Show 后立刻 SetSize 闪退。
func (a *App) FitTrayPopup(width, height int) { _, _ = width, height }
// GetTrayMenuState 返回自定义托盘弹层所需的状态与项目列表。
func (a *App) GetTrayMenuState() (TrayMenuState, error) {
out := TrayMenuState{Style: "native", Locale: "zh-CN", Theme: "dark", Projects: []TrayProjectItem{}}
if e := a.ready(); e != nil {
return out, e
}
st, e := a.store.Settings()
if e != nil {
return out, e
}
out.Style = a.trayMenuStyle()
out.Locale = st.Locale
out.Theme = st.Theme
ts := a.collectTrayStatus()
out.Status = trayStatusKey(ts)
out.StatusLabel = trayStatusLabel(shellTexts(st.Locale), ts)
out.Username = ts.username
out.LoggedIn = ts.loggedIn
out.Unread = ts.unread
out.TodayDue = ts.todayDue
out.Pending = ts.pending
if auto, err := a.GetAutostart(); err == nil {
out.Autostart = auto
}
if projects, err := a.ListProjects(); err == nil {
for i, p := range projects {
if i >= trayProjectLimit {
out.HasMoreProjects = true
break
}
out.Projects = append(out.Projects, TrayProjectItem{ID: p.ID, Name: p.Name})
}
}
return out, nil
}
func trayStatusKey(st trayStatus) string {
switch {
case st.syncing:
return "syncing"
case !st.loggedIn:
return "signedOut"
case st.lastErr != "":
return "error"
case st.online:
return "online"
default:
return "offline"
}
}
// TrayMenuAction 处理自定义托盘弹层的点击。autostart 保持弹层打开以便看到勾选变化。
func (a *App) TrayMenuAction(action, arg string) error {
if e := a.ready(); e != nil {
return e
}
if action != "autostart" {
a.hideTrayPopup()
}
switch action {
case "show":
a.showMainWindow()
case "nav":
if arg == "" {
return errors.New("TRAY_NAV_REQUIRED")
}
a.navigateTo(arg)
case "sync":
a.trayQuickSync()
case "batch":
_, _ = a.StartBatchAnalysis()
case "autostart":
cur, err := a.GetAutostart()
if err != nil {
return err
}
if e := a.SetAutostart(!cur); e != nil {
return e
}
a.emit("tray:refresh", nil)
case "restart":
a.RestartApp()
case "quit":
a.QuitApp()
case "project":
id, err := strconv.ParseInt(arg, 10, 64)
if err != nil || id <= 0 {
return errors.New("TRAY_PROJECT_INVALID")
}
a.navigateTo("/project/" + strconv.FormatInt(id, 10))
default:
return errors.New("UNKNOWN_TRAY_ACTION")
}
return nil
}

7
tray_other.go Normal file
View File

@@ -0,0 +1,7 @@
//go:build !windows
package main
import "github.com/wailsapp/wails/v3/pkg/application"
func activateTrayPopup(*application.WebviewWindow) {}

25
tray_windows.go Normal file
View File

@@ -0,0 +1,25 @@
//go:build windows
package main
import (
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/w32"
)
// activateTrayPopup 只置前 HWND不调用 WebView2 FocusMoveFocus 失败会 os.Exit(1))。
func activateTrayPopup(win *application.WebviewWindow) {
if win == nil {
return
}
ptr := win.NativeWindow()
if ptr == nil {
return
}
hwnd := w32.HWND(uintptr(ptr))
if hwnd == 0 {
return
}
w32.SetForegroundWindow(hwnd)
w32.BringWindowToTop(hwnd)
}

123
update.go
View File

@@ -13,6 +13,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
@@ -70,7 +71,7 @@ func (a *App) SkipAppUpdate(version string) error {
return a.store.SetMeta("app_update_skipped", strings.TrimSpace(version))
}
// DownloadAndInstallUpdate 下载最新安装包、校验哈希后启动并退出应用
// DownloadAndInstallUpdate 下载最新安装包、校验后退出应用并由独立脚本拉起安装器
func (a *App) DownloadAndInstallUpdate() error {
if e := a.ready(); e != nil {
return e
@@ -86,20 +87,12 @@ func (a *App) DownloadAndInstallUpdate() error {
if e != nil {
return e
}
cmd := exec.Command(path, "/S")
platform.ConfigureHidden(cmd)
if e := cmd.Start(); e != nil {
// 静默失败则普通启动
cmd2 := exec.Command(path)
if e2 := cmd2.Start(); e2 != nil {
return errors.New("INSTALLER_START_FAILED")
}
if e := launchDownloadedInstaller(path); e != nil {
return e
}
a.store.Log("info", "系统", "开始安装更新", info.Version)
go func() {
time.Sleep(800 * time.Millisecond)
a.QuitApp()
}()
// 安装脚本会等本进程退出后再 start 安装器,避免占用 exe / 作业对象杀掉子进程。
a.QuitApp()
return nil
}
@@ -152,9 +145,8 @@ func (a *App) downloadRelease(info *appLatestInfo) (string, error) {
if e != nil {
return "", errors.New("SYNC_OFFLINE")
}
if tok := strings.TrimSpace(a.store.Meta("sync_access_token")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
// 公开接口不带过期 JWT避免网关/反代因 Authorization 直接 401。
req.Header.Set("Accept-Encoding", "identity")
client := &http.Client{Timeout: 30 * time.Minute}
resp, e := client.Do(req)
if e != nil {
@@ -171,15 +163,23 @@ func (a *App) downloadRelease(info *appLatestInfo) (string, error) {
}
return "", errors.New("SYNC_HTTP_" + strconv.Itoa(resp.StatusCode))
}
total := info.SizeBytes
if resp.ContentLength > 0 {
total = resp.ContentLength
}
a.emit("app:update-progress", map[string]any{"received": int64(0), "total": total})
dir := filepath.Join(os.TempDir(), "code-count-updates")
_ = os.MkdirAll(dir, 0755)
outPath := filepath.Join(dir, info.Version+"-installer.exe")
if e := os.MkdirAll(dir, 0755); e != nil {
return "", errors.New("SAVE_FAILED")
}
outPath := filepath.Join(dir, fmt.Sprintf("%s-installer-%d.exe", info.Version, os.Getpid()))
f, e := os.Create(outPath)
if e != nil {
return "", errors.New("SAVE_FAILED")
}
h := sha256.New()
n, e := io.Copy(io.MultiWriter(f, h), resp.Body)
prog := &updateProgressWriter{a: a, total: total}
n, e := io.Copy(io.MultiWriter(f, h, prog), resp.Body)
_ = f.Close()
if e != nil {
_ = os.Remove(outPath)
@@ -191,11 +191,94 @@ func (a *App) downloadRelease(info *appLatestInfo) (string, error) {
return "", errors.New("SHA256_MISMATCH")
}
if info.SizeBytes > 0 && n != info.SizeBytes {
a.store.Log("warning", "系统", "更新包大小与元数据不一致", fmt.Sprintf("%d vs %d", n, info.SizeBytes))
_ = os.Remove(outPath)
return "", errors.New("SIZE_MISMATCH")
}
if !isWindowsPE(outPath) {
_ = os.Remove(outPath)
return "", errors.New("NOT_INSTALLER")
}
a.emit("app:update-progress", map[string]any{"received": n, "total": total})
return outPath, nil
}
type updateProgressWriter struct {
a *App
total int64
written int64
lastEmit time.Time
}
func (w *updateProgressWriter) Write(p []byte) (int, error) {
n := len(p)
w.written += int64(n)
now := time.Now()
if w.lastEmit.IsZero() || now.Sub(w.lastEmit) >= 200*time.Millisecond || (w.total > 0 && w.written >= w.total) {
w.lastEmit = now
if w.a != nil {
w.a.emit("app:update-progress", map[string]any{"received": w.written, "total": w.total})
}
}
return n, nil
}
func isWindowsPE(path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
var hdr [2]byte
if _, err := io.ReadFull(f, hdr[:]); err != nil {
return false
}
return hdr[0] == 'M' && hdr[1] == 'Z'
}
// launchDownloadedInstaller 用独立脚本等本进程退出后再打开安装器。
// 不能对安装器本身用 CREATE_NO_WINDOW + /S需要 UAC 的 NSIS 会静默失败,且文件仍被占用。
func launchDownloadedInstaller(path string) error {
path = strings.TrimPrefix(filepath.Clean(path), `\\?\`)
if runtime.GOOS != "windows" {
cmd := exec.Command(path)
if e := cmd.Start(); e != nil {
return errors.New("INSTALLER_START_FAILED")
}
return nil
}
bat := filepath.Join(os.TempDir(), fmt.Sprintf("cc-update-%d.bat", os.Getpid()))
if e := os.WriteFile(bat, []byte(updateLaunchScript(os.Getpid(), path)), 0644); e != nil {
return errors.New("SAVE_FAILED")
}
cmd := exec.Command("cmd", "/C", bat)
platform.ConfigureUpdaterHelper(cmd)
if e := cmd.Start(); e != nil {
cmd = exec.Command("cmd", "/C", bat)
platform.ConfigureHidden(cmd)
if e2 := cmd.Start(); e2 != nil {
return errors.New("INSTALLER_START_FAILED")
}
}
return nil
}
func updateLaunchScript(pid int, installer string) string {
return fmt.Sprintf(""+
"@echo off\r\n"+
"set \"PID=%d\"\r\n"+
"set /a N=0\r\n"+
":wait\r\n"+
"set /a N+=1\r\n"+
"if %%N%% GEQ 90 goto launch\r\n"+
"ping -n 2 127.0.0.1 >nul\r\n"+
"tasklist /FI \"PID eq %%PID%%\" /NH 2>nul | find \"%%PID%%\" >nul\r\n"+
"if not errorlevel 1 goto wait\r\n"+
":launch\r\n"+
"ping -n 3 127.0.0.1 >nul\r\n"+
"start \"\" \"%s\"\r\n"+
"del \"%%~f0\"\r\n", pid, installer)
}
// versionNewer 判断 remote 是否比 local 新(简单 x.y.z 比较)。
func versionNewer(remote, local string) bool {
rp := parseSemver(remote)

66
update_test.go Normal file
View File

@@ -0,0 +1,66 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestVersionNewer(t *testing.T) {
if !versionNewer("2.0.1", "2.0.0") {
t.Fatal("2.0.1 should be newer than 2.0.0")
}
if versionNewer("2.0.0", "2.0.0") {
t.Fatal("same version is not newer")
}
if versionNewer("1.9.9", "2.0.0") {
t.Fatal("1.9.9 should not be newer than 2.0.0")
}
if !versionNewer("v2.1.0", "2.0.9") {
t.Fatal("v prefix should be ignored")
}
}
func TestParseSemver(t *testing.T) {
got := parseSemver("v2.3.4-beta")
if got != [3]int{2, 3, 4} {
t.Fatalf("got %#v", got)
}
}
func TestUpdateLaunchScript(t *testing.T) {
s := updateLaunchScript(4242, `C:\Temp\2.0.1-installer.exe`)
for _, want := range []string{
"set \"PID=4242\"",
`start "" "C:\Temp\2.0.1-installer.exe"`,
"tasklist /FI \"PID eq %PID%\"",
":wait",
":launch",
} {
if !strings.Contains(s, want) {
t.Fatalf("script missing %q\n%s", want, s)
}
}
if strings.Contains(s, " /S") {
t.Fatal("installer must not be started silently; UAC/file lock would fail")
}
}
func TestIsWindowsPE(t *testing.T) {
dir := t.TempDir()
pe := filepath.Join(dir, "ok.exe")
html := filepath.Join(dir, "page.html")
if err := os.WriteFile(pe, []byte("MZ\x90\x00fake"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(html, []byte("<!doctype html>"), 0644); err != nil {
t.Fatal(err)
}
if !isWindowsPE(pe) {
t.Fatal("MZ header should pass")
}
if isWindowsPE(html) {
t.Fatal("html should not pass as installer")
}
}