An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Read historical database colors only from inline styles https://github.com/siyuan-note/siyuan/issues/18931
Daniel3dd654761ece
diff --git a/kernel/av/color.go b/kernel/av/color.goindex 2d0413ca5f..9628708aa4 100644--- a/kernel/av/color.go+++ b/kernel/av/color.go@@ -39,10 +39,6 @@ var attributeViewColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)// LoadWorkspacePalette 返回工作空间级数据库自定义色。由 model 在启动时绑定。var LoadWorkspacePalette func() (colors []*AttributeViewCustomColor, order []string)-type persistedAttributeViewPalette struct {- CustomColors []*AttributeViewCustomColor `json:"customColors"`-}-// AttributeViewColorTheme 描述一种主题模式下的数据库选项颜色。type AttributeViewColorTheme struct {Color string `json:"color"`@@ -173,15 +169,6 @@ func WorkspacePalette() (colors []*AttributeViewCustomColor, order []string) {return}-// DecodePersistedPalette 从属性视图 JSON 中读取历史快照里的自定义色,不写入属性视图结构体。-func DecodePersistedPalette(data []byte) (colors []*AttributeViewCustomColor, err error) {- parsed := &persistedAttributeViewPalette{}- if err = json.Unmarshal(data, parsed); nil != err {- return- }- return NormalizeAttributeViewCustomColors(parsed.CustomColors, false)-}-// DefaultAttributeViewColorOrder 返回内置色在前、自定义色按编号排列的默认顺序。func DefaultAttributeViewColorOrder(colors []*AttributeViewCustomColor) []string {keys := make([]string, 0, BuiltinColorCount+len(colors))diff --git a/kernel/model/attribute_view_custom_color_history_test.go b/kernel/model/attribute_view_custom_color_history_test.goindex 5764ae7056..478cf7ca70 100644--- a/kernel/model/attribute_view_custom_color_history_test.go+++ b/kernel/model/attribute_view_custom_color_history_test.go@@ -21,64 +21,19 @@ import ("os""path/filepath""sync"- "sync/atomic""testing""github.com/siyuan-note/siyuan/kernel/av")-func TestLoadHistoryAttributeViewCustomColors(t *testing.T) {- const avID = "20260824000000-target1"- historyDir := t.TempDir()- path := filepath.Join(historyDir, "storage", "av", avID+".json")- if err := os.MkdirAll(filepath.Dir(path), 0755); nil != err {- t.Fatal(err)- }- data, err := json.Marshal(struct {- Spec int `json:"spec"`- ID string `json:"id"`- CustomColors []*av.AttributeViewCustomColor `json:"customColors"`- }{- Spec: av.CurrentSpec,- ID: avID,- CustomColors: []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }},- })- if nil != err {- t.Fatal(err)- }- if err = os.WriteFile(path, data, 0644); nil != err {- t.Fatal(err)- }-- colors, order, found := loadHistoryAttributeViewCustomColors(historyDir, avID)- if !found || 1 != len(colors) || "#010203" != colors[0].Light.Color {- t.Fatalf("unexpected historical palette: %+v, found %v", colors, found)- }- if len(order) != av.BuiltinColorCount+1 || order[len(order)-1] != "15" {- t.Fatalf("unexpected historical palette order: %v", order)- }- if _, _, found = loadHistoryAttributeViewCustomColors(historyDir, "20260824000001-missing"); found {- t.Fatal("missing historical palette was reported as found")- }- if _, _, found = loadHistoryAttributeViewCustomColors(historyDir, "../target1"); found {- t.Fatal("invalid related attribute view ID was accepted")- }-}--func TestLoadHistoryAttributeViewUsesWorkspacePaletteOrder(t *testing.T) {+func TestHistoryAttributeViewPaletteOnlyUsesInlineStyles(t *testing.T) {const avID = "20260824000002-target2"historyDir := t.TempDir()avPath := filepath.Join(historyDir, "storage", "av", avID+".json")if err := os.MkdirAll(filepath.Dir(avPath), 0755); err != nil {t.Fatal(err)}- if err := os.WriteFile(avPath, []byte(`{"spec":13,"id":"20260824000002-target2"}`), 0644); err != nil {+ if err := os.WriteFile(avPath, []byte(`{"customColors":[{"index":16,"light":{"color":"#111111","backgroundColor":"#222222"},"dark":{"color":"#333333","backgroundColor":"#444444"}}]}`), 0644); err != nil {t.Fatal(err)}stylesPath := filepath.Join(historyDir, "storage", "inline-styles.json")@@ -103,31 +58,28 @@ func TestLoadHistoryAttributeViewUsesWorkspacePaletteOrder(t *testing.T) {t.Fatal(err)}- colors, order, found := loadHistoryAttributeViewCustomColors(historyDir, avID)+ colors, order, found := loadHistoryWorkspacePalette(historyDir)if !found || len(colors) != 1 || len(order) != av.BuiltinColorCount+1 ||- order[0] != "15" || order[1] != "2" || order[2] != "1" {+ colors[0].Index != 15 || order[0] != "15" || order[1] != "2" || order[2] != "1" {t.Fatalf("unexpected historical workspace palette: colors=%+v order=%v found=%v", colors, order, found)}attrView := &av.AttributeView{ID: avID, CustomColorRenderContext: newHistoryAttributeViewCustomColorRenderContext(historyDir)}- if resolvedOrder := attrView.PaletteOrder(); len(resolvedOrder) == 0 || resolvedOrder[0] != "15" {- t.Fatalf("historical render context lost palette order: %v", resolvedOrder)+ resolvedColors := attrView.Palette()+ resolvedOrder := attrView.PaletteOrder()+ if len(resolvedColors) != 1 || resolvedColors[0].Index != 15 || len(resolvedOrder) == 0 || resolvedOrder[0] != "15" {+ t.Fatalf("historical render context did not use inline styles: colors=%+v order=%v", resolvedColors, resolvedOrder)}}-func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(t *testing.T) {- var calls atomic.Int32- resolver := newCachedAttributeViewCustomColorResolver(- func(string) ([]*av.AttributeViewCustomColor, []string, bool) {- calls.Add(1)- return []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }}, []string{"15", "1"}, true+func TestAttributeViewCustomColorRenderContextReturnsIndependentPalettes(t *testing.T) {+ context := newAttributeViewCustomColorRenderContext([]*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},},- )+ }}, []string{"15", "1"}, true)+ resolver := context.ResolveRelatedCustomColorsconst goroutines = 32var waitGroup sync.WaitGroup@@ -143,6 +95,7 @@ func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(tif len(order) == 0 || order[0] != "15" {errs <- "resolver returned an invalid palette order"}+ colors[0].Light.Color = "#ffffff"}()}waitGroup.Wait()@@ -150,18 +103,13 @@ func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(tfor err := range errs {t.Fatal(err)}- if 1 != calls.Load() {- t.Fatalf("palette loader called %d times, want 1", calls.Load())+ colors, _, _ := resolver("20260824000001-target2")+ if colors[0].Light.Color != "#010203" {+ t.Fatal("render context shared a mutable palette between consumers")}- secondCalls := atomic.Int32{}- secondResolver := newCachedAttributeViewCustomColorResolver(- func(string) ([]*av.AttributeViewCustomColor, []string, bool) {- secondCalls.Add(1)- return nil, nil, false- },- )- if _, _, found := secondResolver("20260824000000-target1"); found || 1 != secondCalls.Load() {- t.Fatal("separate request resolver reused another request cache")+ missingContext := newAttributeViewCustomColorRenderContext(nil, nil, false)+ if _, _, found := missingContext.ResolveRelatedCustomColors("20260824000000-target1"); found {+ t.Fatal("missing historical palette was reported as found")}}diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex 031b09e32a..9f5514dd7a 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -26,7 +26,6 @@ import ("sort""strconv""strings"- "sync""time""github.com/88250/gulu"@@ -1202,90 +1201,6 @@ func ResolveHistoryAttributeViewBoxID(avID, created string) (string, error) {return "", nil}-type attributeViewCustomColorPaletteCacheEntry struct {- colors []*av.AttributeViewCustomColor- order []string- found bool-}--// newCachedAttributeViewCustomColorResolver 将历史调色板解析限制在单次渲染请求内,并避免并发重复读取。-func newCachedAttributeViewCustomColorResolver(- loader func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool),-) func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {- cache := map[string]attributeViewCustomColorPaletteCacheEntry{}- var lock sync.Mutex- return func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {- lock.Lock()- defer lock.Unlock()-- if entry, ok := cache[avID]; ok {- colors, _ = av.NormalizeAttributeViewCustomColors(entry.colors, false)- order = av.NormalizeAttributeViewColorOrder(entry.order, colors)- return colors, order, entry.found- }- colors, order, found = loader(avID)- colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)- order = av.NormalizeAttributeViewColorOrder(order, colors)- cache[avID] = attributeViewCustomColorPaletteCacheEntry{colors: colors, order: order, found: found}- colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)- order = av.NormalizeAttributeViewColorOrder(order, colors)- return- }-}--func decodeHistoricalAttributeViewCustomColors(boxID, avID string, data []byte) (ret []*av.AttributeViewCustomColor, err error) {- data, err = decryptHistoricalAttributeView(boxID, avID, data)- if nil != err {- return- }- return av.DecodePersistedPalette(data)-}--func loadHistoryAttributeViewCustomColors(historyDir, avID string) (- ret []*av.AttributeViewCustomColor, order []string, found bool,-) {- if !ast.IsNodeIDPattern(avID) {- return nil, nil, false- }- type source struct {- path string- boxID string- }- var sources []source- globalPath := filepath.Join(historyDir, "storage", "av", avID+".json")- if gulu.File.IsExist(globalPath) {- sources = append(sources, source{path: globalPath})- }- entries, _ := os.ReadDir(historyDir)- for _, entry := range entries {- if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {- continue- }- candidate := filepath.Join(historyDir, entry.Name(), "storage", "av", avID+".json")- if gulu.File.IsExist(candidate) {- sources = append(sources, source{path: candidate, boxID: entry.Name()})- }- }- if 1 != len(sources) {- return nil, nil, false- }-- data, err := os.ReadFile(sources[0].path)- if nil != err {- logging.LogWarnf("read related history attribute view [%s] failed: %s", avID, err)- return nil, nil, false- }- ret, err = decodeHistoricalAttributeViewCustomColors(sources[0].boxID, avID, data)- if nil != err {- logging.LogWarnf("parse related history attribute view [%s] failed: %s", avID, err)- return nil, nil, false- }- if 0 < len(ret) {- return ret, av.DefaultAttributeViewColorOrder(ret), true- }- return loadHistoryWorkspacePalette(historyDir)-}-func loadHistoryWorkspacePalette(historyDir string) (ret []*av.AttributeViewCustomColor, order []string, found bool,) {@@ -1320,12 +1235,22 @@ func decodeHistoricalWorkspacePalette(data []byte) (return colors, av.NormalizeAttributeViewColorOrder(styles.AV.Order, colors), true}+func newAttributeViewCustomColorRenderContext(colors []*av.AttributeViewCustomColor, order []string,+ found bool) *av.CustomColorRenderContext {+ colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)+ order = av.NormalizeAttributeViewColorOrder(order, colors)+ return &av.CustomColorRenderContext{ResolveRelatedCustomColors: func(string) (+ retColors []*av.AttributeViewCustomColor, retOrder []string, retFound bool,+ ) {+ retColors, _ = av.NormalizeAttributeViewCustomColors(colors, false)+ retOrder = av.NormalizeAttributeViewColorOrder(order, retColors)+ return retColors, retOrder, found+ }}+}+func newHistoryAttributeViewCustomColorRenderContext(historyDir string) *av.CustomColorRenderContext {- return &av.CustomColorRenderContext{ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(- func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {- return loadHistoryAttributeViewCustomColors(historyDir, avID)- },- )}+ colors, order, found := loadHistoryWorkspacePalette(historyDir)+ return newAttributeViewCustomColorRenderContext(colors, order, found)}func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID string) (viewable av.Viewable, attrView *av.AttributeView, err error) {@@ -1403,42 +1328,8 @@ func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID stringsnapshotColors, snapshotOrder, snapshotPaletteFound = decodeHistoricalWorkspacePalette(inlineStylesData)break}- attrView.CustomColorRenderContext = &av.CustomColorRenderContext{- ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(- func(targetAvID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {- if !ast.IsNodeIDPattern(targetAvID) {- return nil, nil, false- }- var matches []*entity.File- for _, file := range files {- if strings.HasSuffix(file.Path, "/storage/av/"+targetAvID+".json") {- matches = append(matches, file)- }- }- if 1 != len(matches) {- return nil, nil, false- }- data, readErr := repo.OpenFile(matches[0])- if nil != readErr {- logging.LogWarnf("read related snapshot attribute view [%s] failed: %s", targetAvID, readErr)- return nil, nil, false- }- colors, parseErr := decodeHistoricalAttributeViewCustomColors(- avBoxIDFromRepoPath(matches[0].Path), targetAvID, data)- if nil != parseErr {- logging.LogWarnf("parse related snapshot attribute view [%s] failed: %s", targetAvID, parseErr)- return nil, nil, false- }- if 0 < len(colors) {- return colors, av.DefaultAttributeViewColorOrder(colors), true- }- if snapshotPaletteFound {- return snapshotColors, snapshotOrder, true- }- return []*av.AttributeViewCustomColor{}, av.DefaultAttributeViewColorOrder(nil), true- },- ),- }+ attrView.CustomColorRenderContext = newAttributeViewCustomColorRenderContext(+ snapshotColors, snapshotOrder, snapshotPaletteFound)attrView.ResolveDirectColors()viewable, err = renderAttributeView(attrView, "", viewID, carrierViewID, "", 1, -1, nil, false, false, nil, "")