chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
package main
import (
"context"
"fmt"
"strings"
"sync/atomic"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// App holds Wails-bound state for the desktop shell.
type App struct {
ctx context.Context
setupToken string
backendURL string
apiLanBaseURL string
listenPublic bool
shutdownCh chan struct{}
shutdownDone chan struct{}
pickingDir atomic.Bool
}
// NewApp creates a new App application struct.
func NewApp() *App {
return &App{
shutdownCh: make(chan struct{}, 1),
shutdownDone: make(chan struct{}),
}
}
// startup is called when the application starts.
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
}
func (a *App) shutdown(ctx context.Context) {
select {
case a.shutdownCh <- struct{}{}:
default:
}
<-a.shutdownDone
}
// GetAPIBaseURL returns the local HTTP base URL for REST API calls (e.g. http://127.0.0.1:PORT/api/v1).
// The desktop shell proxies the webview to this address; window.location.origin is not the API host.
func (a *App) GetAPIBaseURL() string {
if a.backendURL == "" {
return ""
}
return strings.TrimRight(a.backendURL, "/") + "/api/v1"
}
// GetDesktopHTTPPortSetting returns the saved local API port (0 = random port each launch).
func (a *App) GetDesktopHTTPPortSetting() int {
return LoadDesktopPrefsHTTPPort()
}
// SetDesktopHTTPPortSetting saves the preferred local API port to application support. Restart the app for it to take effect unless it matches the current listener.
func (a *App) SetDesktopHTTPPortSetting(port int) error {
return SaveDesktopHTTPPortPreference(port)
}
// GetDesktopHTTPBindPublicSetting returns whether API listens on all interfaces (0.0.0.0).
func (a *App) GetDesktopHTTPBindPublicSetting() bool {
return LoadDesktopHTTPBindPublic()
}
// SetDesktopHTTPBindPublicSetting saves LAN/public listen preference. Restart the app for it to take effect.
func (a *App) SetDesktopHTTPBindPublicSetting(v bool) error {
return SaveDesktopHTTPBindPublicPreference(v)
}
// GetAPILanBaseURL returns a suggested base URL for other devices on the LAN (…/api/v1), or empty if not in bind-public mode or IP detection failed.
func (a *App) GetAPILanBaseURL() string {
return a.apiLanBaseURL
}
// GetDesktopListenPublicActive is true when this session’s API server is listening on all interfaces (runtime), not the saved preference.
func (a *App) GetDesktopListenPublicActive() bool {
return a.listenPublic
}
// CheckForUpdates manually triggers the update check from the frontend.
func (a *App) CheckForUpdates() {
if a.ctx != nil {
checkUpdate(a.ctx, desktopAboutVersion(), true, false)
}
}
// AutoCheckForUpdates silently checks for updates and downloads them.
func (a *App) AutoCheckForUpdates() {
if a.ctx != nil {
checkUpdate(a.ctx, desktopAboutVersion(), false, true)
}
}
// GetAutoSetupToken exposes the per-process capability only through the native bridge.
func (a *App) GetAutoSetupToken() string { return a.setupToken }
// GetApprovalMode returns the machine-local sandbox approval mode.
func (a *App) GetApprovalMode() string {
return LoadApprovalMode()
}
// SetApprovalMode persists the approval mode. Unshipped modes ("ask", "full")
// are rejected; currently only "auto" can be stored.
func (a *App) SetApprovalMode(mode string) error {
return SaveApprovalMode(mode)
}
// GetProjectDirs returns the user-approved project directories.
func (a *App) GetProjectDirs() []string {
return LoadProjectDirs()
}
// RemoveProjectDir drops one approved directory. The only way to add a
// directory is PickProjectDir; typed replacement of the whole list is not
// an authorization path.
func (a *App) RemoveProjectDir(dir string) error {
return removeApprovedProjectDir(dir)
}
// PickProjectDir opens the system directory picker and appends the result to
// the approved list. Users must pick a folder this way; typed paths are not
// an authorization path.
func (a *App) PickProjectDir() (string, error) {
if !a.pickingDir.CompareAndSwap(false, true) {
return "", fmt.Errorf("a folder picker is already open")
}
defer a.pickingDir.Store(false)
dir, err := wailsruntime.OpenDirectoryDialog(a.ctx, wailsruntime.OpenDialogOptions{
Title: "Select Project Directory",
CanCreateDirectories: true,
})
if err != nil {
return "", err
}
return appendApprovedProjectDir(dir)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

+63
View File
@@ -0,0 +1,63 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleName</key>
<string>{{.Info.ProductName}}</string>
<key>CFBundleExecutable</key>
<string>{{.OutputFilename}}</string>
<key>CFBundleIdentifier</key>
<string>com.wails.{{.Name}}</string>
<key>CFBundleVersion</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleGetInfoString</key>
<string>{{.Info.Comments}}</string>
<key>CFBundleShortVersionString</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleIconFile</key>
<string>iconfile</string>
<key>LSMinimumSystemVersion</key>
<string>10.13.0</string>
<key>NSHighResolutionCapable</key>
<string>true</string>
<key>NSHumanReadableCopyright</key>
<string>{{.Info.Copyright}}</string>
{{if .Info.FileAssociations}}
<key>CFBundleDocumentTypes</key>
<array>
{{range .Info.FileAssociations}}
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>{{.Ext}}</string>
</array>
<key>CFBundleTypeName</key>
<string>{{.Name}}</string>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
<key>CFBundleTypeIconFile</key>
<string>{{.IconName}}</string>
</dict>
{{end}}
</array>
{{end}}
{{if .Info.Protocols}}
<key>CFBundleURLTypes</key>
<array>
{{range .Info.Protocols}}
<dict>
<key>CFBundleURLName</key>
<string>com.wails.{{.Scheme}}</string>
<key>CFBundleURLSchemes</key>
<array>
<string>{{.Scheme}}</string>
</array>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
</dict>
{{end}}
</array>
{{end}}
</dict>
</plist>
@@ -0,0 +1,123 @@
; Based on the Wails v2.12.0 default installer (MIT).
; See licenses/Wails-MIT.txt. Local change: install the notice/source bundle.
Unicode true
####
## Please note: Template replacements don't work in this file. They are provided with default defines like
## mentioned underneath.
## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo.
## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually
## from outside of Wails for debugging and development of the installer.
##
## For development first make a wails nsis build to populate the "wails_tools.nsh":
## > wails build --target windows/amd64 --nsis
## Then you can call makensis on this file with specifying the path to your binary:
## For a AMD64 only installer:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe
## For a ARM64 only installer:
## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe
## For a installer with both architectures:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe
####
## The following information is taken from the ProjectInfo file, but they can be overwritten here.
####
## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}"
## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}"
## !define INFO_PRODUCTNAME "MyProduct" # Default "{{.Info.ProductName}}"
## !define INFO_PRODUCTVERSION "1.0.0" # Default "{{.Info.ProductVersion}}"
## !define INFO_COPYRIGHT "Copyright" # Default "{{.Info.Copyright}}"
###
## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe"
## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
####
## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html
####
## Include the wails tools
####
!include "wails_tools.nsh"
# The version information for this two must consist of 4 parts
VIProductVersion "${INFO_PRODUCTVERSION}.0"
VIFileVersion "${INFO_PRODUCTVERSION}.0"
VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}"
VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer"
VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}"
VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}"
# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware
ManifestDPIAware true
!include "MUI.nsh"
!define MUI_ICON "..\icon.ico"
!define MUI_UNICON "..\icon.ico"
# !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314
!define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps
!define MUI_ABORTWARNING # This will warn the user if they exit from the installer.
!insertmacro MUI_PAGE_WELCOME # Welcome to the installer page.
# !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer
!insertmacro MUI_PAGE_DIRECTORY # In which folder install page.
!insertmacro MUI_PAGE_INSTFILES # Installing page.
!insertmacro MUI_PAGE_FINISH # Finished installation page.
!insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page
!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer
## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1
#!uninstfinalize 'signtool --file "%1"'
#!finalize 'signtool --file "%1"'
Name "${INFO_PRODUCTNAME}"
OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file.
InstallDir "$PROGRAMFILES64\${INFO_COMPANYNAME}\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder).
ShowInstDetails show # This will always show the installation details.
Function .onInit
!insertmacro wails.checkArchitecture
FunctionEnd
Section
!insertmacro wails.setShellContext
!insertmacro wails.webview2runtime
SetOutPath $INSTDIR
!insertmacro wails.files
; Paths are relative to cmd/desktop/build/windows/installer.
File "..\..\..\..\..\LICENSE"
File "..\..\..\..\..\THIRD_PARTY_NOTICES.md"
SetOutPath "$INSTDIR\licenses"
File /r "..\..\..\..\..\licenses\*"
SetOutPath $INSTDIR
CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
!insertmacro wails.associateFiles
!insertmacro wails.associateCustomProtocols
!insertmacro wails.writeUninstaller
SectionEnd
Section "uninstall"
!insertmacro wails.setShellContext
RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath
RMDir /r $INSTDIR
Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk"
Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk"
!insertmacro wails.unassociateFiles
!insertmacro wails.unassociateCustomProtocols
!insertmacro wails.deleteUninstaller
SectionEnd
+701
View File
@@ -0,0 +1,701 @@
//go:build !bindings
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/menu"
"github.com/wailsapp/wails/v2/pkg/menu/keys"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/options/mac"
"academy/internal/config"
"academy/internal/container"
"academy/internal/handler"
"academy/internal/handler/session"
"academy/internal/logger"
"academy/internal/runtime"
"academy/internal/stream"
"academy/internal/types/interfaces"
"github.com/joho/godotenv"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// dragHandlerJS is injected into the webview on DomReady.
// It bypasses Wails' built-in CSS-variable-based drag detection (which uses
// getComputedStyle and has timing/inheritance issues with dynamic SPA content)
// and instead uses robust DOM-traversal via el.closest() plus a Y-position
// fallback for the top 40px of a layout container, including its children.
// The "drag"
// message is sent directly through the WKWebView script-message bridge,
// which the native Objective-C handler in WailsContext.m converts to
// [NSWindow performWindowDragWithEvent:].
const dragHandlerJS = `(function(){
if(window.__wkDragBound)return;
window.__wkDragBound=true;
document.documentElement.classList.add('wails-desktop');
// Disable rubber-band overscroll that reveals the dark window background
document.documentElement.style.overscrollBehavior='none';
document.body.style.overscrollBehavior='none';
if(window.wails&&window.wails.flags){
window.wails.flags.cssDragProperty='__disabled__';
window.wails.flags.cssDragValue='__never__';
}
// Prevent native text/image drag-out to fix the "selected and dragged away" issue
window.addEventListener('dragstart', function(e){
e.preventDefault();
}, true);
var TITLEBAR_H=40;
// We specifically look for Wails' inline style attributes injected by Vue,
// and custom drag classes, avoiding generic headers like .section-header.
// .chat-topbar is the window top on the conversation page.
var dragSel='.logo_row,.menu_top,.chat-topbar,.drag-region,[data-wails-drag],' +
'[style*="--wails-draggable: drag"],[style*="--wails-draggable:drag"]';
var noDragSel='button,a,input,select,textarea,[role="button"],' +
'.t-button,.t-input,.t-select,.t-textarea,' +
'.header-actions,.header-action-btn,.sidebar-toggle,.logo_box,' +
'.close-btn,.menu_item,.submenu,.submenu_item,.menu_bottom,' +
'.t-popup,.t-dropdown,.t-tooltip,.t-dialog,[data-no-drag],' +
'[style*="--wails-draggable: no-drag"],[style*="--wails-draggable:no-drag"]';
var layoutClasses=['main','chat','dialogue-wrap','kb-list-container','kb-list-content',
'agent-list-container','agent-list-content','org-list-container','org-list-content','aside_box',
'ks-container','ks-content','settings-overlay','knowledge-layout',
'faq-manager-wrapper','login-layout'];
function sendDrag(){
try{window.webkit.messageHandlers.external.postMessage('drag')}
catch(_){try{window.WailsInvoke('drag')}catch(e){}}
}
function isLayoutEl(el){
for(var i=0;i<layoutClasses.length;i++){
if(el.classList.contains(layoutClasses[i]))return true;
}
var tag=el.tagName;
return tag==='BODY'||tag==='HTML';
}
function inTitlebar(el,y){
if(y>TITLEBAR_H)return false;
var node=el;
while(node&&node instanceof Element){
if(isLayoutEl(node))return true;
node=node.parentElement;
}
return false;
}
function shouldDrag(el,y){
if(!(el instanceof Element))return false;
if(el.closest(noDragSel))return false;
if(el.closest(dragSel))return true;
if(inTitlebar(el,y))return true;
return false;
}
window.addEventListener('mousedown',function(e){
var target=e.target;
if(target&&target.nodeType===Node.TEXT_NODE){
target=target.parentElement;
}
if(e.button!==0||e.detail!==1)return;
if(!shouldDrag(target,e.clientY))return;
// The session title renames on double-click. Wait until the pointer
// actually moves so that click still lands; other top-bar hits drag now.
var defer=target.closest&&target.closest('.chat-header__title');
if(!defer){
e.preventDefault();
sendDrag();
return;
}
var x=e.clientX,y=e.clientY;
function move(ev){
if(Math.abs(ev.clientX-x)<4&&Math.abs(ev.clientY-y)<4)return;
cleanup();
sendDrag();
}
function up(){cleanup();}
function cleanup(){
window.removeEventListener('mousemove',move,true);
window.removeEventListener('mouseup',up,true);
}
window.addEventListener('mousemove',move,true);
window.addEventListener('mouseup',up,true);
},true);
// Intercept external link clicks and window.open so they open in the system browser
document.addEventListener('click',function(e){
var el=e.target;
while(el&&el.tagName!=='A')el=el.parentElement;
if(!el||!el.href)return;
var href=el.href;
if(href.indexOf('http://')===0||href.indexOf('https://')===0){
if(window.runtime&&window.runtime.BrowserOpenURL){
e.preventDefault();
e.stopPropagation();
window.runtime.BrowserOpenURL(href);
}
}
},true);
var origOpen=window.open;
window.open=function(url){
if(url&&(typeof url==='string')&&(url.indexOf('http://')===0||url.indexOf('https://')===0)){
if(window.runtime&&window.runtime.BrowserOpenURL){
window.runtime.BrowserOpenURL(url);
return null;
}
}
return origOpen.apply(window,arguments);
};
})();`
// wailsThemeSyncJS:与 index.html 首屏一致,在 DomReady 再跑一遍,覆盖 Ctrl+R 后 runtime 就绪时机
const wailsThemeSyncJS = `(function(){try{var t=localStorage.getItem('Academy_theme')||'light';if(t==='system')t=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';var bg=t==='dark'?'#181818':'#eee';document.documentElement.setAttribute('theme-mode',t);document.documentElement.style.background=bg;document.documentElement.style.minHeight='100%';document.documentElement.style.colorScheme=t==='dark'?'dark':'light';if(document.body){document.body.style.background=bg;document.body.style.minHeight='100%';}var w=window.runtime;if(!w)return;if(t==='dark'){if(w.WindowSetDarkTheme)w.WindowSetDarkTheme();if(w.WindowSetBackgroundColour)w.WindowSetBackgroundColour(24,24,24,255);}else{if(w.WindowSetLightTheme)w.WindowSetLightTheme();if(w.WindowSetBackgroundColour)w.WindowSetBackgroundColour(238,238,238,255);}}catch(e){}})()`
const academyGitHubRepoURL = "https://academy"
// ensureDesktopLiteEdition marks this process as Lite. cmd/desktop is the
// Lite app; packaged builds also inject this via ldflags. wails dev often
// does not, and auto-setup / the embedded SPA / capabilities still key off
// the string. Host sandbox is gated by the desktop build tag, not this.
func ensureDesktopLiteEdition() {
handler.Edition = "lite"
}
func main() {
ensureDesktopLiteEdition()
// For macOS .app bundle, the working directory is usually "/" or the MacOS folder.
// We need to change the working directory to the Resources folder where our configs are.
execPath, errPath := os.Executable()
// A packaged .app keeps config under Contents/Resources. wails dev also
// runs from a .app, but that bundle has no copied config; stay in the
// repo and use config/ there.
if errPath == nil && strings.Contains(execPath, ".app/Contents/MacOS") {
resPath := filepath.Join(filepath.Dir(filepath.Dir(execPath)), "Resources")
if _, err := os.Stat(filepath.Join(resPath, "config", "config.yaml")); err == nil {
_ = os.Chdir(resPath)
}
}
if _, err := os.Stat(filepath.Join("config", "config.yaml")); os.IsNotExist(err) {
// wails dev 的 cwd 是 cmd/desktop。仓库配置在上两级。
repoRoot := filepath.Clean(filepath.Join("..", ".."))
if _, err := os.Stat(filepath.Join(repoRoot, "config", "config.yaml")); err == nil {
_ = os.Chdir(repoRoot)
}
}
// Load .env explicitly for the desktop app so DB_DRIVER gets loaded
_ = godotenv.Load()
// wails dev picks up the repo .env, which may ask for Redis streams
// without REDIS_ADDR. go-redis then dials localhost:6379 and aborts
// startup. Lite has no Redis; keep the in-memory stream manager.
if strings.TrimSpace(os.Getenv("REDIS_ADDR")) == "" &&
strings.EqualFold(strings.TrimSpace(os.Getenv("STREAM_MANAGER_TYPE")), stream.TypeRedis) {
_ = os.Setenv("STREAM_MANAGER_TYPE", stream.TypeMemory)
}
configureDesktopStorage(execPath)
configureDesktopFileStorage(execPath)
logger.ConfigureFromEnv()
// Set Gin mode
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
// Mute Gin's per-route registration spam; replaced by a single
// summary printed after router build.
runtime.SilenceGinRouteSpam()
// Provision the signing key first so the startup banner reflects it
// instead of warning about a key the desktop is about to create.
if err := ensureDesktopSigningKey(); err != nil {
panic(fmt.Sprintf("initialize desktop signing key: %v", err))
}
runtime.LogStartupEnv(context.Background())
// Build dependency injection container
c := container.BuildContainer(runtime.GetContainer())
if err := c.Decorate(func(container.HostApprovalModeLoader) container.HostApprovalModeLoader {
return LoadApprovalMode
}); err != nil {
panic(fmt.Sprintf("wire desktop approval mode: %v", err))
}
if err := c.Decorate(func(session.HostProjectDirsLoader) session.HostProjectDirsLoader {
return LoadProjectDirs
}); err != nil {
panic(fmt.Sprintf("wire desktop project dirs: %v", err))
}
// Initialize the Academy App struct
app := NewApp()
setupBytes := make([]byte, 32)
if _, err := rand.Read(setupBytes); err != nil {
panic("failed to generate desktop authentication capability")
}
app.setupToken = base64.RawURLEncoding.EncodeToString(setupBytes)
handler.SetLiteSetupToken(app.setupToken)
handler.SetHostProjectPicker(app.PickProjectDir)
// Error channel to capture server startup errors
serverErrCh := make(chan error, 1)
// Run backend in a separate goroutine
go func() {
defer close(app.shutdownDone)
err := c.Invoke(func(
cfg *config.Config,
router *gin.Engine,
resourceCleaner interfaces.ResourceCleaner,
) error {
server := &http.Server{Handler: router}
runtime.LogGinRouteCount(context.Background())
// 127.0.0.1 + saved port from settings (desktop-prefs.json), or :0 for random free port.
addr := desktopBackendListenAddr()
listener, err := listenWithRetry(addr, 10, 300*time.Millisecond)
if err != nil {
return fmt.Errorf("failed to start server: %v", err)
}
tcpAddr := listener.Addr().(*net.TCPAddr)
port := tcpAddr.Port
app.listenPublic = LoadDesktopHTTPBindPublic()
// Reverse proxy and webview API calls always use loopback; avoid 0.0.0.0 / [::] as dial target.
app.backendURL = fmt.Sprintf("http://127.0.0.1:%d", port)
app.apiLanBaseURL = ""
if app.listenPublic {
if ip := desktopPreferredLANIPv4(); ip != nil {
app.apiLanBaseURL = fmt.Sprintf("http://%s:%d/api/v1", ip.String(), port)
}
}
// Wails OnShutdown returns only after this goroutine closes
// serverStopped. Closing the listener by hand makes Serve return
// "use of closed network connection" instead of ErrServerClosed,
// and the error path calls logger.Fatalf → os.Exit(1) before cleanup.
serverStopped := make(chan struct{})
go func() {
defer close(serverStopped)
<-app.shutdownCh
logger.Infof(context.Background(), "Wails shutting down, stopping Go backend...")
drainBudget, cleanupBudget := runtime.ShutdownBudgets(cfg.Server.ShutdownTimeout)
shutdownCtx, cancel := context.WithTimeout(context.Background(), drainBudget)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
server.Close()
}
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), cleanupBudget)
defer cleanupCancel()
if errs := resourceCleaner.Cleanup(cleanupCtx); len(errs) > 0 {
logger.Errorf(context.Background(), "Errors occurred during resource cleanup: %v", errs)
}
}()
// Also listen for OS signals just in case
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-signals
select {
case app.shutdownCh <- struct{}{}:
default:
}
}()
logger.Infof(context.Background(), "Server is running at %s (proxy -> %s)", tcpAddr.String(), app.backendURL)
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("server error: %v", err)
}
<-serverStopped
return nil
})
if err != nil {
serverErrCh <- err
logger.Fatalf(context.Background(), "Failed to run backend: %v", err)
}
}()
// Give the server a moment to start and determine its port
time.Sleep(500 * time.Millisecond)
// Create application with options
// macOS app menu
AppMenu := menu.NewMenu()
FileMenu := AppMenu.AddSubmenu("Academy Lite")
FileMenu.AddText("About Academy", keys.CmdOrCtrl("i"), func(_ *menu.CallbackData) {
if app.ctx == nil {
return
}
choice, err := wailsruntime.MessageDialog(app.ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.InfoDialog,
Title: "Academy Lite",
Message: fmt.Sprintf("Academy Lite — Desktop Edition\n\nA RAG framework for document understanding and semantic Q&A over complex, heterogeneous content.\n\nVersion %s\n© 2026 Tencent\n\nGitHub:\n%s", desktopAboutVersion(), academyGitHubRepoURL),
Buttons: []string{"Open GitHub", "OK"},
DefaultButton: "OK",
})
if err != nil {
logger.Warnf(context.Background(), "About dialog: %v", err)
return
}
if choice == "Open GitHub" {
wailsruntime.BrowserOpenURL(app.ctx, academyGitHubRepoURL)
}
})
FileMenu.AddText("Check for Updates...", nil, func(_ *menu.CallbackData) {
if app.ctx == nil {
return
}
checkUpdate(app.ctx, desktopAboutVersion(), true, false)
})
FileMenu.AddSeparator()
FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
app.shutdown(context.Background())
os.Exit(0)
})
AppMenu.Append(menu.EditMenu())
ViewMenu := AppMenu.AddSubmenu("View")
ViewMenu.AddText("Reload", keys.CmdOrCtrl("r"), func(_ *menu.CallbackData) {
if app.ctx != nil {
wailsruntime.EventsEmit(app.ctx, "app:reload")
}
})
// Wait for the backend URL to be set
targetURL, _ := url.Parse(app.backendURL)
proxy := desktopAPIProxy(targetURL)
// Start Wails application
// We use a Reverse Proxy to seamlessly proxy Wails' frontend to our Go backend
err := wails.Run(&options.App{
Title: "Academy Lite",
Width: 1280,
Height: 800,
DisableResize: false,
Menu: AppMenu,
AssetServer: &assetserver.Options{
Handler: proxy,
},
StartHidden: false, // Show window on startup
OnStartup: app.startup,
OnDomReady: func(ctx context.Context) {
wailsruntime.WindowExecJS(ctx, wailsThemeSyncJS)
wailsruntime.WindowExecJS(ctx, dragHandlerJS)
// 注入真实 API 根路径(与 window.location.origin 不同);无 Go 绑定时仍可显示。
if u := strings.TrimSpace(app.backendURL); u != "" {
apiRoot := strings.TrimRight(u, "/") + "/api/v1"
inject := fmt.Sprintf(`try{window.__ACADEMY_API_BASE__=%s}catch(e){}`, strconv.Quote(apiRoot))
wailsruntime.WindowExecJS(ctx, inject)
}
if lan := strings.TrimSpace(app.apiLanBaseURL); lan != "" {
injectLan := fmt.Sprintf(`try{window.__ACADEMY_API_LAN_BASE__=%s}catch(e){}`, strconv.Quote(lan))
wailsruntime.WindowExecJS(ctx, injectLan)
}
},
OnShutdown: app.shutdown,
Bind: []interface{}{
app,
},
BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 255},
Mac: &mac.Options{
TitleBar: mac.TitleBarHiddenInset(),
WebviewIsTransparent: false,
WindowIsTranslucent: false,
},
})
if err != nil {
println("Error:", err.Error())
}
}
func configureDesktopStorage(execPath string) {
if execPath == "" || !strings.Contains(execPath, ".app/Contents/MacOS") {
return
}
appSupportDir, err := defaultMacAppSupportDir(execPath)
if err != nil {
logger.Warnf(context.Background(), "Failed to resolve app support dir: %v", err)
return
}
legacyResourcesDir := filepath.Join(filepath.Dir(filepath.Dir(execPath)), "Resources")
targetDataDir := filepath.Join(appSupportDir, "data")
migrateLegacyDesktopData(legacyResourcesDir, targetDataDir)
dbPath := resolveDesktopDataPath(os.Getenv("DB_PATH"), filepath.Join("data", "academy.db"), appSupportDir)
if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil {
logger.Warnf(context.Background(), "Failed to create desktop DB directory %s: %v", filepath.Dir(dbPath), err)
}
_ = os.Setenv("DB_PATH", dbPath)
}
// configureDesktopFileStorage points Lite file uploads at ~/.academy/data/files.
// wails dev is not always inside a packaged .app, so this runs for every
// desktop process. An explicit absolute directory is kept; the Docker default
// /data/files is not writable on macOS and is replaced. Uploads move over from
// wherever the previous build kept them.
func configureDesktopFileStorage(execPath string) {
home, err := os.UserHomeDir()
if err != nil {
logger.Warnf(context.Background(), "Failed to resolve home dir for file storage: %v", err)
return
}
filesPath := desktopLocalFilesDir(home)
raw := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR"))
if !useDesktopFilesDir(raw) {
return
}
if appSupport, err := defaultMacAppSupportDir(execPath); err == nil {
migrateDesktopFiles(legacyDesktopFilesDir(raw, appSupport), filesPath)
}
if err := os.MkdirAll(filesPath, 0o755); err != nil {
logger.Warnf(context.Background(), "Failed to create desktop files directory %s: %v", filesPath, err)
return
}
_ = os.Setenv("LOCAL_STORAGE_BASE_DIR", filesPath)
}
func desktopLocalFilesDir(home string) string {
return filepath.Join(home, ".academy", "data", "files")
}
func useDesktopFilesDir(raw string) bool {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return true
}
cleaned := filepath.Clean(trimmed)
switch cleaned {
case "/data/files", "data/files", filepath.Join(".", "data", "files"):
return true
default:
return !filepath.IsAbs(cleaned)
}
}
// legacyDesktopFilesDir is where the previous build stored uploads: raw
// resolved under the bundle's Application Support dir, or its data/files
// default when raw is empty or the absolute Docker default.
func legacyDesktopFilesDir(raw, appSupportDir string) string {
if filepath.IsAbs(strings.TrimSpace(raw)) {
raw = ""
}
return resolveDesktopDataPath(raw, filepath.Join("data", "files"), appSupportDir)
}
func migrateDesktopFiles(oldDir, newDir string) {
if filepath.Clean(oldDir) == filepath.Clean(newDir) {
return
}
info, err := os.Stat(oldDir)
if err != nil || !info.IsDir() {
return
}
if _, err := os.Stat(newDir); err == nil {
logger.Warnf(context.Background(),
"Desktop files already exist at %s; leaving %s in place", newDir, oldDir)
return
}
if err := os.MkdirAll(filepath.Dir(newDir), 0o755); err != nil {
logger.Warnf(context.Background(), "Failed to create %s: %v", filepath.Dir(newDir), err)
return
}
if err := os.Rename(oldDir, newDir); err != nil {
logger.Warnf(context.Background(), "Failed to migrate desktop files from %s to %s: %v", oldDir, newDir, err)
}
}
func defaultMacAppSupportDir(execPath string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
appName := "Academy Lite"
if idx := strings.Index(execPath, ".app/Contents/MacOS"); idx >= 0 {
bundleName := filepath.Base(execPath[:idx+4])
if trimmed := strings.TrimSuffix(bundleName, ".app"); trimmed != "" {
appName = trimmed
}
}
return filepath.Join(homeDir, "Library", "Application Support", appName), nil
}
func resolveDesktopDataPath(rawPath, defaultRelativePath, appSupportDir string) string {
trimmed := strings.TrimSpace(rawPath)
if trimmed == "" {
trimmed = defaultRelativePath
}
if filepath.IsAbs(trimmed) {
return filepath.Clean(trimmed)
}
trimmed = strings.TrimPrefix(trimmed, "."+string(filepath.Separator))
return filepath.Join(appSupportDir, filepath.Clean(trimmed))
}
// desktopAPIProxy forwards the webview to the loopback Gin server. Pairing
// needs the API listener as Host so the link cannot be aimed at another
// machine. Other routes keep the page Host (wails.localhost), which OIDC
// callbacks and embed origin checks still compare against.
func desktopAPIProxy(target *url.URL) *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetURL(target)
r.SetXForwarded()
if !isBrowserPairingRequest(r.In) {
r.Out.Host = r.In.Host
}
},
}
}
func isBrowserPairingRequest(req *http.Request) bool {
return req != nil && req.URL != nil && req.Method == http.MethodPost && req.URL.Path == "/api/v1/me/browser"
}
// desktopBackendListenAddr returns the TCP address for the embedded Gin server (Wails desktop).
// Binds 127.0.0.1 by default, or 0.0.0.0 when http_bind_public is set in desktop-prefs.json.
func desktopBackendListenAddr() string {
host := "127.0.0.1"
if LoadDesktopHTTPBindPublic() {
host = "0.0.0.0"
}
pref := LoadDesktopPrefsHTTPPort()
if pref >= 1 && pref <= 65535 {
return net.JoinHostPort(host, strconv.Itoa(pref))
}
return net.JoinHostPort(host, "0")
}
// desktopPreferredLANIPv4 picks a non-loopback IPv4 for “other devices on this network” URL hints.
func desktopPreferredLANIPv4() net.IP {
ifaces, err := net.Interfaces()
if err == nil {
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, aerr := iface.Addrs()
if aerr != nil {
continue
}
for _, a := range addrs {
ipNet, ok := a.(*net.IPNet)
if !ok || ipNet.IP == nil {
continue
}
ip4 := ipNet.IP.To4()
if ip4 == nil || ip4.IsLoopback() {
continue
}
if ip4.IsPrivate() {
return ip4
}
}
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, aerr := iface.Addrs()
if aerr != nil {
continue
}
for _, a := range addrs {
ipNet, ok := a.(*net.IPNet)
if !ok || ipNet.IP == nil {
continue
}
ip4 := ipNet.IP.To4()
if ip4 == nil || ip4.IsLoopback() || ip4.IsUnspecified() {
continue
}
return ip4
}
}
}
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return nil
}
defer conn.Close()
la, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok || la.IP == nil {
return nil
}
return la.IP.To4()
}
func migrateLegacyDesktopData(resourcesDir, targetDataDir string) {
legacyDataDir := filepath.Join(resourcesDir, "data")
if info, err := os.Stat(legacyDataDir); err != nil || !info.IsDir() {
return
}
if _, err := os.Stat(targetDataDir); err == nil {
return
}
if err := os.MkdirAll(filepath.Dir(targetDataDir), 0o755); err != nil {
logger.Warnf(context.Background(), "Failed to create app support parent dir %s: %v", filepath.Dir(targetDataDir), err)
return
}
if err := os.Rename(legacyDataDir, targetDataDir); err != nil {
logger.Warnf(context.Background(), "Failed to migrate legacy desktop data from %s to %s: %v", legacyDataDir, targetDataDir, err)
return
}
logger.Infof(context.Background(), "Migrated legacy desktop data to %s", targetDataDir)
}
func listenWithRetry(addr string, maxRetries int, baseDelay time.Duration) (net.Listener, error) {
var lastErr error
for i := 0; i < maxRetries; i++ {
listener, err := net.Listen("tcp", addr)
if err == nil {
return listener, nil
}
lastErr = err
if i < maxRetries-1 {
delay := baseDelay * time.Duration(1<<uint(i))
if delay > 3*time.Second {
delay = 3 * time.Second
}
time.Sleep(delay)
}
}
return nil, lastErr
}
+17
View File
@@ -0,0 +1,17 @@
//go:build bindings
package main
import (
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
)
// Wails「生成绑定」阶段使用 -tags bindings 单独编译本文件,不启动 Gin/数据库,避免依赖本机 Postgres。
func main() {
app := NewApp()
_ = wails.Run(&options.App{
Title: "Academy Lite",
Bind: []interface{}{app},
})
}
+193
View File
@@ -0,0 +1,193 @@
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"academy/internal/localsandbox"
)
const desktopPrefsFileName = "desktop-prefs.json"
type desktopPrefs struct {
HTTPPort int `json:"http_port"`
HTTPBindPublic bool `json:"http_bind_public"`
ProjectDirs []string `json:"project_dirs,omitempty"`
ApprovalMode string `json:"approval_mode,omitempty"`
SessionRoot string `json:"session_root,omitempty"`
}
// Which stances exist, and which of them this build can serve, are decided by
// the sandbox itself (localsandbox.ApprovalMode). Keeping a second list here
// is how the two drift.
func desktopConfigDir() (string, error) {
// Tests (and some Unix setups) isolate via XDG_CONFIG_HOME. Darwin's
// UserConfigDir ignores that variable, so honor it first or prefs tests
// write into the real Application Support directory.
if xdg := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); xdg != "" {
return xdg, nil
}
return os.UserConfigDir()
}
func desktopPrefsDir() (string, error) {
cfg, err := desktopConfigDir()
if err != nil {
return "", err
}
dir := filepath.Join(cfg, "Academy Lite")
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
return dir, nil
}
func desktopPrefsFilePath() (string, error) {
dir, err := desktopPrefsDir()
if err != nil {
return "", err
}
return filepath.Join(dir, desktopPrefsFileName), nil
}
func loadDesktopPrefs() desktopPrefs {
path, err := desktopPrefsFilePath()
if err != nil {
return desktopPrefs{}
}
data, err := os.ReadFile(path)
if err != nil {
return desktopPrefs{}
}
var p desktopPrefs
if json.Unmarshal(data, &p) != nil {
return desktopPrefs{}
}
if p.HTTPPort < 0 || p.HTTPPort > 65535 {
p.HTTPPort = 0
}
return p
}
func saveDesktopPrefs(p desktopPrefs) error {
path, err := desktopPrefsFilePath()
if err != nil {
return err
}
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o600)
}
// LoadDesktopPrefsHTTPPort returns http_port from prefs file, or 0 if unset / invalid (ephemeral port on each launch).
func LoadDesktopPrefsHTTPPort() int {
return loadDesktopPrefs().HTTPPort
}
// LoadDesktopHTTPBindPublic returns whether the embedded API server should listen on all interfaces (0.0.0.0).
func LoadDesktopHTTPBindPublic() bool {
return loadDesktopPrefs().HTTPBindPublic
}
// SaveDesktopHTTPPortPreference persists listen port preference. port 0 means use a random free port on each launch.
func SaveDesktopHTTPPortPreference(port int) error {
if port < 0 || port > 65535 {
return fmt.Errorf("invalid port")
}
cur := loadDesktopPrefs()
cur.HTTPPort = port
return saveDesktopPrefs(cur)
}
// SaveDesktopHTTPBindPublicPreference persists whether to listen on 0.0.0.0 for LAN/public access.
func SaveDesktopHTTPBindPublicPreference(v bool) error {
cur := loadDesktopPrefs()
cur.HTTPBindPublic = v
return saveDesktopPrefs(cur)
}
// LoadApprovalMode returns the stored mode. Unknown values become "auto".
// Known-but-unshipped modes are returned unchanged so the sandbox can refuse
// them instead of silently widening access.
func LoadApprovalMode() string {
return string(localsandbox.ParseApprovalMode(loadDesktopPrefs().ApprovalMode))
}
// SaveApprovalMode refuses what it cannot deliver. Storing "ask" would promise
// an approval card that does not exist yet, and "full" would promise an
// unsandboxed run that the sandbox has no policy for; both look like a working
// setting and behave like a broken one.
func SaveApprovalMode(mode string) error {
requested := localsandbox.ApprovalMode(mode)
if !requested.Known() {
return fmt.Errorf("invalid approval mode %q", mode)
}
if !requested.Shipped() {
return fmt.Errorf("approval mode %q is not available yet", mode)
}
cur := loadDesktopPrefs()
cur.ApprovalMode = mode
return saveDesktopPrefs(cur)
}
// LoadProjectDirs returns the project directories the user picked. Only the UI
// writes this list: the agent must never widen its own reach.
func LoadProjectDirs() []string {
return loadDesktopPrefs().ProjectDirs
}
func SaveProjectDirs(dirs []string) error {
cleaned := make([]string, 0, len(dirs))
for _, dir := range dirs {
if !filepath.IsAbs(dir) {
return fmt.Errorf("project directory must be absolute: %q", dir)
}
cleaned = append(cleaned, filepath.Clean(dir))
}
cur := loadDesktopPrefs()
cur.ProjectDirs = cleaned
return saveDesktopPrefs(cur)
}
// appendApprovedProjectDir adds an absolute directory the user just picked.
// Duplicate paths are ignored so opening the same folder twice does not
// grow the recent list.
func appendApprovedProjectDir(dir string) (string, error) {
dir = filepath.Clean(strings.TrimSpace(dir))
if dir == "" || dir == "." {
return "", nil
}
existing := LoadProjectDirs()
for _, item := range existing {
if item == dir {
return dir, nil
}
}
if err := SaveProjectDirs(append(append([]string{}, existing...), dir)); err != nil {
return "", err
}
return dir, nil
}
// removeApprovedProjectDir drops one previously picked directory. Missing
// paths are a no-op so clearing the same folder twice does not error.
func removeApprovedProjectDir(dir string) error {
dir = filepath.Clean(strings.TrimSpace(dir))
if dir == "" || dir == "." {
return nil
}
existing := LoadProjectDirs()
kept := make([]string, 0, len(existing))
for _, item := range existing {
if item != dir {
kept = append(kept, item)
}
}
return SaveProjectDirs(kept)
}
+167
View File
@@ -0,0 +1,167 @@
package main
import (
"os"
"path/filepath"
"reflect"
"testing"
"academy/internal/handler"
"academy/internal/utils"
"github.com/stretchr/testify/require"
)
func TestDesktopSigningKeyKeepsExistingAESHMAC(t *testing.T) {
dir := t.TempDir()
aes := "abcdefghijklmnopqrstuvwxyz123456"
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("JWT_SECRET", "academy-jwt-secret")
t.Setenv("SYSTEM_AES_KEY", aes)
require.Equal(t, aes, string(utils.SystemHMACKey()))
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
require.Equal(t, aes, string(utils.SystemHMACKey()))
_, err := os.Stat(filepath.Join(dir, "signing.key"))
require.True(t, os.IsNotExist(err), "the AES key must not be copied into signing.key")
require.NotEqual(t, aes, os.Getenv("JWT_SECRET"))
require.GreaterOrEqual(t, len(os.Getenv("JWT_SECRET")), 32)
}
func TestDesktopLocalFilesDir(t *testing.T) {
require.Equal(t, filepath.Join("/Users/dev", ".academy", "data", "files"), desktopLocalFilesDir("/Users/dev"))
}
func TestUseDesktopFilesDirReplacesDockerDefault(t *testing.T) {
require.True(t, useDesktopFilesDir(""))
require.True(t, useDesktopFilesDir("/data/files"))
require.True(t, useDesktopFilesDir("./data/files"))
require.False(t, useDesktopFilesDir("/Users/dev/custom-files"))
}
func TestConfigureDesktopFileStorageUsesHomeAcademy(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("LOCAL_STORAGE_BASE_DIR", "/data/files")
configureDesktopFileStorage("")
require.Equal(t, filepath.Join(home, ".academy", "data", "files"), os.Getenv("LOCAL_STORAGE_BASE_DIR"))
info, err := os.Stat(os.Getenv("LOCAL_STORAGE_BASE_DIR"))
require.NoError(t, err)
require.True(t, info.IsDir())
}
func TestLegacyDesktopFilesDirFollowsTheOldResolution(t *testing.T) {
appSupport := "/Users/dev/Library/Application Support/Academy"
require.Equal(t, filepath.Join(appSupport, "data", "files"), legacyDesktopFilesDir("", appSupport))
require.Equal(t, filepath.Join(appSupport, "data", "files"), legacyDesktopFilesDir("/data/files", appSupport))
require.Equal(t, filepath.Join(appSupport, "custom", "files"), legacyDesktopFilesDir("custom/files", appSupport))
}
func TestConfigureDesktopFileStorageMigratesFromTheBundleDir(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("LOCAL_STORAGE_BASE_DIR", "custom/files")
old := filepath.Join(home, "Library", "Application Support", "Academy", "custom", "files")
require.NoError(t, os.MkdirAll(filepath.Join(old, "1"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(old, "1", "a.txt"), []byte("a"), 0o600))
configureDesktopFileStorage("/Applications/Academy.app/Contents/MacOS/Academy")
require.FileExists(t, filepath.Join(home, ".academy", "data", "files", "1", "a.txt"))
}
func TestEnsureDesktopLiteEditionOverridesDefaultStandard(t *testing.T) {
old := handler.Edition
t.Cleanup(func() { handler.Edition = old })
handler.Edition = "standard"
ensureDesktopLiteEdition()
require.Equal(t, "lite", handler.Edition)
}
func TestApprovalModeDefaultsToAuto(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
require.Equal(t, "auto", LoadApprovalMode())
}
func TestSaveApprovalModeRejectsUnknownValue(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
require.Error(t, SaveApprovalMode("yolo"))
}
// Only "auto" is shipped. Accepting "ask" would promise an approval card
// that does not exist yet (the command is just denied); accepting "full" makes
// Build return ErrFullAccessHasNoPolicy, i.e. nothing runs at all.
func TestSaveApprovalModeRejectsModesNotShippedYet(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
require.Error(t, SaveApprovalMode("ask"))
require.Error(t, SaveApprovalMode("full"))
}
func TestSaveApprovalModeRoundTrips(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
require.NoError(t, SaveApprovalMode("auto"))
require.Equal(t, "auto", LoadApprovalMode())
}
func TestProjectDirsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
dirs := []string{"/Users/dev/My Project", "/Users/dev/other"}
require.NoError(t, SaveProjectDirs(dirs))
require.Equal(t, dirs, LoadProjectDirs())
}
func TestSaveProjectDirsRejectsRelativePath(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
require.Error(t, SaveProjectDirs([]string{"relative/dir"}))
}
func TestAppendApprovedProjectDirDedupes(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
dir := t.TempDir()
got, err := appendApprovedProjectDir(dir)
require.NoError(t, err)
require.Equal(t, filepath.Clean(dir), got)
again, err := appendApprovedProjectDir(dir)
require.NoError(t, err)
require.Equal(t, filepath.Clean(dir), again)
require.Equal(t, []string{filepath.Clean(dir)}, LoadProjectDirs())
}
func TestAppendApprovedProjectDirFromFileParent(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
dir := t.TempDir()
file := filepath.Join(dir, "notes.md")
require.NoError(t, os.WriteFile(file, []byte("x"), 0o644))
got, err := appendApprovedProjectDir(filepath.Dir(file))
require.NoError(t, err)
require.Equal(t, filepath.Clean(dir), got)
require.Equal(t, []string{filepath.Clean(dir)}, LoadProjectDirs())
}
func TestRemoveApprovedProjectDirRemovesOnlyThatPath(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
keep := t.TempDir()
drop := t.TempDir()
_, err := appendApprovedProjectDir(keep)
require.NoError(t, err)
_, err = appendApprovedProjectDir(drop)
require.NoError(t, err)
require.NoError(t, removeApprovedProjectDir(drop+"/"))
require.Equal(t, []string{filepath.Clean(keep)}, LoadProjectDirs())
}
func TestRemoveApprovedProjectDirIsIdempotent(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
dir := t.TempDir()
require.NoError(t, removeApprovedProjectDir(dir))
require.Empty(t, LoadProjectDirs())
}
func TestSetProjectDirsIsNotAWailsMethod(t *testing.T) {
typ := reflect.TypeOf(&App{})
_, ok := typ.MethodByName("SetProjectDirs")
require.False(t, ok, "replacing the allowlist from the webview is not an authorization path")
_, ok = typ.MethodByName("RemoveProjectDir")
require.True(t, ok)
_, ok = typ.MethodByName("PickProjectDir")
require.True(t, ok)
}
+61
View File
@@ -0,0 +1,61 @@
//go:build !bindings
package main
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/require"
)
func TestDesktopAPIProxyRewritesWailsHostToLoopback(t *testing.T) {
var got string
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Host
w.WriteHeader(http.StatusNoContent)
}))
defer backend.Close()
target, err := url.Parse(backend.URL)
require.NoError(t, err)
front := httptest.NewServer(desktopAPIProxy(target))
defer front.Close()
req, err := http.NewRequest(http.MethodPost, front.URL+"/api/v1/me/browser", nil)
require.NoError(t, err)
req.Host = "wails.localhost"
resp, err := front.Client().Do(req)
require.NoError(t, err)
_, _ = io.Copy(io.Discard, resp.Body)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusNoContent, resp.StatusCode)
require.Equal(t, target.Host, got)
}
func TestDesktopAPIProxyKeepsHostForOtherRoutes(t *testing.T) {
var got string
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Host
w.WriteHeader(http.StatusNoContent)
}))
defer backend.Close()
target, err := url.Parse(backend.URL)
require.NoError(t, err)
front := httptest.NewServer(desktopAPIProxy(target))
defer front.Close()
req, err := http.NewRequest(http.MethodGet, front.URL+"/api/v1/auth/oidc/start", nil)
require.NoError(t, err)
req.Host = "wails.localhost"
resp, err := front.Client().Do(req)
require.NoError(t, err)
_, _ = io.Copy(io.Discard, resp.Body)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusNoContent, resp.StatusCode)
require.Equal(t, "wails.localhost", got)
}
+120
View File
@@ -0,0 +1,120 @@
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"os"
"path/filepath"
"strings"
"academy/internal/utils"
)
// ensureDesktopSigningKey persists the desktop signing key and, when no
// explicit secret is configured, a JWT secret. It never replaces an AES
// encryption key, so upgrading cannot make stored credentials unreadable.
// The JWT secret is never that AES key: a leaked session secret must not
// decrypt stored credentials.
func ensureDesktopSigningKey() error {
dir, err := os.UserConfigDir()
if err != nil {
return err
}
return ensureDesktopSigningKeyInDir(filepath.Join(dir, "Academy Lite"))
}
func ensureDesktopSigningKeyInDir(dir string) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
// An existing HMAC (an explicit signing key, or the AES key of an older
// install) stays the signer exactly as configured: replacing it would
// invalidate presigned URLs, and copying it into signing.key would leave
// the AES key in a second file. Sessions then get their own secret.
if len(utils.SystemHMACKey()) != 0 {
return ensureDesktopJWTSecret(dir, nil)
}
path := filepath.Join(dir, "signing.key")
key, err := os.ReadFile(path)
if os.IsNotExist(err) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return err
}
key = []byte(base64.RawURLEncoding.EncodeToString(bytes))
f, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if os.IsExist(createErr) {
key, err = os.ReadFile(path)
} else if createErr != nil {
return createErr
} else {
_, err = f.Write(key)
closeErr := f.Close()
if err == nil {
err = closeErr
}
}
}
if err != nil {
return err
}
if len(key) < 32 {
return fmt.Errorf("invalid desktop signing key in %s", path)
}
if err := os.Setenv("SYSTEM_SIGNING_KEY", string(key)); err != nil {
return err
}
return ensureDesktopJWTSecret(dir, key)
}
// ensureDesktopJWTSecret fills JWT_SECRET when it is unset or still a
// placeholder. A signing key this function generated can also sign sessions.
// A nil signingKey means the signer came from the environment (possibly the
// AES key), so sessions get their own persisted secret.
func ensureDesktopJWTSecret(dir string, signingKey []byte) error {
jwtSecret := strings.TrimSpace(os.Getenv("JWT_SECRET"))
if jwtSecret != "" && jwtSecret != "academy-jwt-secret" && jwtSecret != "CHANGE-ME-jwt-secret" {
return nil
}
secret := string(signingKey)
if signingKey == nil {
var err error
secret, err = desktopJWTSecret(dir)
if err != nil {
return err
}
}
return os.Setenv("JWT_SECRET", secret)
}
func desktopJWTSecret(dir string) (string, error) {
path := filepath.Join(dir, "jwt.key")
key, err := os.ReadFile(path)
if os.IsNotExist(err) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
key = []byte(base64.RawURLEncoding.EncodeToString(bytes))
f, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if os.IsExist(createErr) {
key, err = os.ReadFile(path)
} else if createErr != nil {
return "", createErr
} else {
_, err = f.Write(key)
closeErr := f.Close()
if err == nil {
err = closeErr
}
}
}
if err != nil {
return "", err
}
if len(key) < 32 {
return "", fmt.Errorf("invalid desktop jwt secret in %s", path)
}
return string(key), nil
}
+72
View File
@@ -0,0 +1,72 @@
package main
import (
"os"
"path/filepath"
"runtime"
"testing"
"academy/internal/utils"
"github.com/stretchr/testify/require"
)
func TestDesktopSigningKeyPersistsWithoutChangingAES(t *testing.T) {
dir := t.TempDir()
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("JWT_SECRET", "")
t.Setenv("SYSTEM_AES_KEY", "academy-system-aes-key-32bytes!!")
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
first := string(utils.SystemHMACKey())
firstJWT := os.Getenv("JWT_SECRET")
require.GreaterOrEqual(t, len(first), 32)
require.Equal(t, first, firstJWT)
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("JWT_SECRET", "")
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
require.Equal(t, first, string(utils.SystemHMACKey()))
require.Equal(t, firstJWT, os.Getenv("JWT_SECRET"))
require.Equal(t, "academy-system-aes-key-32bytes!!", os.Getenv("SYSTEM_AES_KEY"))
info, err := os.Stat(filepath.Join(dir, "signing.key"))
require.NoError(t, err)
if runtime.GOOS != "windows" {
require.Zero(t, info.Mode().Perm()&0o077)
}
}
func TestDesktopJWTSecretIsNotTheAESKey(t *testing.T) {
dir := t.TempDir()
const aes = "0123456789abcdef0123456789abcdef"
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("JWT_SECRET", "academy-jwt-secret")
t.Setenv("SYSTEM_AES_KEY", aes)
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
jwt := os.Getenv("JWT_SECRET")
require.GreaterOrEqual(t, len(jwt), 32)
require.NotEqual(t, aes, jwt)
require.Equal(t, aes, string(utils.SystemHMACKey()))
require.Equal(t, aes, os.Getenv("SYSTEM_AES_KEY"))
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("JWT_SECRET", "CHANGE-ME-jwt-secret")
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
require.Equal(t, jwt, os.Getenv("JWT_SECRET"))
require.Equal(t, aes, string(utils.SystemHMACKey()))
require.Equal(t, aes, os.Getenv("SYSTEM_AES_KEY"))
_, err := os.Stat(filepath.Join(dir, "signing.key"))
require.True(t, os.IsNotExist(err), "the AES key must not be copied into signing.key")
}
func TestDesktopSigningKeyKeepsAnExplicitKey(t *testing.T) {
dir := t.TempDir()
stale := []byte("stale-file-key-0123456789abcdefgh")
require.NoError(t, os.WriteFile(filepath.Join(dir, "signing.key"), stale, 0o600))
const explicit = "explicit-24-byte-signkey"
t.Setenv("SYSTEM_SIGNING_KEY", explicit)
t.Setenv("SYSTEM_AES_KEY", "")
t.Setenv("JWT_SECRET", "")
require.NoError(t, ensureDesktopSigningKeyInDir(dir))
require.Equal(t, explicit, string(utils.SystemHMACKey()))
require.NotEqual(t, explicit, os.Getenv("JWT_SECRET"))
}
+413
View File
@@ -0,0 +1,413 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"academy/internal/handler"
"academy/internal/logger"
wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
"golang.org/x/mod/semver"
)
type githubAsset struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
}
type githubRelease struct {
TagName string `json:"tag_name"`
HTMLURL string `json:"html_url"`
Assets []githubAsset `json:"assets"`
}
func checkUpdate(ctx context.Context, currentVersion string, showUpToDate bool, autoDownload bool) {
go func() {
if currentVersion == "unknown" || currentVersion == "" {
if showUpToDate {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.InfoDialog,
Title: "Check for Updates",
Message: "Unable to determine the current version. Cannot check for updates.",
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
if !strings.HasPrefix(currentVersion, "v") {
currentVersion = "v" + currentVersion
}
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", "https://api.github.com/repos/Tencent/WeKnora/releases/latest", nil)
if err != nil {
logger.Warnf(context.Background(), "Check update failed: %v", err)
return
}
// Add User-Agent header which is required/recommended by GitHub API
req.Header.Set("User-Agent", "Academy-Lite-Desktop-App")
// Add Authorization header if GITHUB_TOKEN is present to increase rate limit
if token := os.Getenv("GITHUB_TOKEN"); token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := client.Do(req)
if err != nil {
logger.Warnf(context.Background(), "Check update failed: %v", err)
if showUpToDate {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Check Update Failed",
Message: fmt.Sprintf("Failed to connect to GitHub to check for updates:\n%v", err),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Warnf(context.Background(), "GitHub API returned status code: %d", resp.StatusCode)
if showUpToDate {
msg := fmt.Sprintf("GitHub API returned an unexpected status code: %d", resp.StatusCode)
if resp.StatusCode == 403 {
msg = "GitHub API rate limit exceeded. Please try again later."
}
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Check Update Failed",
Message: msg,
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
var release githubRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
logger.Warnf(context.Background(), "Failed to parse release info: %v", err)
return
}
latestVersion := release.TagName
if !strings.HasPrefix(latestVersion, "v") {
latestVersion = "v" + latestVersion
}
if semver.IsValid(latestVersion) && semver.IsValid(currentVersion) {
if semver.Compare(latestVersion, currentVersion) > 0 {
assetURL, assetName := findBestAsset(release.Assets, runtime.GOOS, runtime.GOARCH)
if autoDownload && assetURL != "" {
// Silent download in background
downloadAndInstall(ctx, assetURL, assetName, currentVersion, latestVersion, true)
return
}
msg := fmt.Sprintf("A new version of Academy Lite is available!\n\nCurrent version: %s\nLatest version: %s\n\nWould you like to download it now?", currentVersion, latestVersion)
choice, _ := wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.InfoDialog,
Title: "Update Available",
Message: msg,
Buttons: []string{"Download", "Cancel"},
DefaultButton: "Download",
})
if choice == "Download" {
if assetURL != "" {
downloadAndInstall(ctx, assetURL, assetName, currentVersion, latestVersion, false)
} else {
// Fallback to opening the release page if no specific asset is found
wailsruntime.BrowserOpenURL(ctx, release.HTMLURL)
}
}
return
}
}
if showUpToDate {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.InfoDialog,
Title: "Up to Date",
Message: fmt.Sprintf("You are using the latest version of Academy Lite.\n\nCurrent version: %s", currentVersion),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
}()
}
func findBestAsset(assets []githubAsset, goos, goarch string) (string, string) {
osKeyword := ""
switch goos {
case "darwin":
osKeyword = "mac"
case "windows":
osKeyword = "win"
case "linux":
osKeyword = "linux"
}
archKeyword := ""
switch goarch {
case "amd64":
archKeyword = "amd64"
case "arm64":
archKeyword = "arm64"
}
// 1. Try to match both OS and Arch
for _, asset := range assets {
name := strings.ToLower(asset.Name)
if strings.Contains(name, osKeyword) && (strings.Contains(name, archKeyword) || strings.Contains(name, "universal") || strings.Contains(name, "aarch64")) {
return asset.BrowserDownloadURL, asset.Name
}
}
// 2. Try to match OS only (e.g. universal binaries without arch in name)
for _, asset := range assets {
name := strings.ToLower(asset.Name)
if strings.Contains(name, osKeyword) {
return asset.BrowserDownloadURL, asset.Name
}
}
// 3. MacOS specific fallback (e.g. .dmg)
if goos == "darwin" {
for _, asset := range assets {
if strings.HasSuffix(strings.ToLower(asset.Name), ".dmg") {
return asset.BrowserDownloadURL, asset.Name
}
}
}
// 4. Windows specific fallback (e.g. .exe)
if goos == "windows" {
for _, asset := range assets {
if strings.HasSuffix(strings.ToLower(asset.Name), ".exe") {
return asset.BrowserDownloadURL, asset.Name
}
}
}
return "", ""
}
func downloadAndInstall(ctx context.Context, url string, filename string, currentVersion string, latestVersion string, silent bool) {
tempDir := os.TempDir()
savePath := filepath.Join(tempDir, filename)
go func() {
logger.Infof(context.Background(), "Starting download from %s to %s", url, savePath)
resp, err := http.Get(url)
if err != nil {
logger.Warnf(context.Background(), "Download failed: %v", err)
if !silent {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Download Failed",
Message: fmt.Sprintf("Failed to download the update:\n%v", err),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Warnf(context.Background(), "Download failed, server returned status: %d", resp.StatusCode)
if !silent {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Download Failed",
Message: fmt.Sprintf("Server returned status: %d", resp.StatusCode),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
out, err := os.Create(savePath)
if err != nil {
logger.Warnf(context.Background(), "Failed to create file for download: %v", err)
if !silent {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Save Failed",
Message: fmt.Sprintf("Failed to save the update file:\n%v", err),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
logger.Warnf(context.Background(), "Error occurred during download copying: %v", err)
if !silent {
wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.ErrorDialog,
Title: "Download Error",
Message: fmt.Sprintf("An error occurred while downloading:\n%v", err),
Buttons: []string{"OK"},
DefaultButton: "OK",
})
}
return
}
logger.Infof(context.Background(), "Download completed successfully: %s", savePath)
// Prompt user to restart
choice, _ := wailsruntime.MessageDialog(ctx, wailsruntime.MessageDialogOptions{
Type: wailsruntime.InfoDialog,
Title: "Update Ready",
Message: fmt.Sprintf("Academy Lite %s has been downloaded successfully.\n\nWould you like to restart and install the new version now?", latestVersion),
Buttons: []string{"Restart Now", "Later"},
DefaultButton: "Restart Now",
})
if choice == "Restart Now" {
applyUpdateAndRestart(ctx, savePath)
}
}()
}
// desktopAboutVersion 优先使用构建脚本注入的 handler.Version,否则尝试读取仓库根目录 VERSION(本地 wails dev 等未带 ldflags 时)。
func desktopAboutVersion() string {
if v := strings.TrimSpace(handler.Version); v != "" && v != "unknown" {
return v
}
for _, p := range []string{
"VERSION",
filepath.Join("..", "..", "VERSION"),
filepath.Join("..", "..", "..", "VERSION"),
} {
b, err := os.ReadFile(p)
if err != nil {
continue
}
if v := strings.TrimSpace(string(b)); v != "" {
return v
}
}
return "unknown"
}
// applyUpdateAndRestart applies the downloaded update and restarts the application
func applyUpdateAndRestart(ctx context.Context, savePath string) {
if runtime.GOOS == "windows" {
scriptPath := filepath.Join(os.TempDir(), "academy_update.bat")
execPath, err := os.Executable()
if err != nil {
logger.Warnf(context.Background(), "Failed to get executable path: %v", err)
return
}
scriptContent := fmt.Sprintf(`@echo off
timeout /t 2 /nobreak
start /wait "" "%s" /S
start "" "%s"
del "%%~f0"
`, savePath, execPath)
os.WriteFile(scriptPath, []byte(scriptContent), 0755)
cmd := exec.Command("cmd.exe", "/C", "start", "/b", scriptPath)
cmd.Start()
wailsruntime.Quit(ctx)
} else if runtime.GOOS == "darwin" {
if strings.HasSuffix(strings.ToLower(savePath), ".dmg") {
go func() {
execPath, err := os.Executable()
if err != nil {
logger.Warnf(context.Background(), "Failed to get executable path: %v", err)
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
return
}
appBundlePath := filepath.Dir(filepath.Dir(filepath.Dir(execPath)))
if !strings.HasSuffix(appBundlePath, ".app") {
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
return
}
mountPoint := filepath.Join(os.TempDir(), "AcademyUpdateMount")
os.MkdirAll(mountPoint, 0755)
cmdMount := exec.Command("hdiutil", "attach", savePath, "-mountpoint", mountPoint, "-nobrowse", "-quiet")
if err := cmdMount.Run(); err != nil {
logger.Warnf(context.Background(), "Failed to mount dmg: %v", err)
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
return
}
entries, err := os.ReadDir(mountPoint)
if err != nil {
exec.Command("hdiutil", "detach", mountPoint, "-force").Run()
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
return
}
var newAppPath string
for _, entry := range entries {
if strings.HasSuffix(entry.Name(), ".app") {
newAppPath = filepath.Join(mountPoint, entry.Name())
break
}
}
if newAppPath == "" {
exec.Command("hdiutil", "detach", mountPoint, "-force").Run()
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
return
}
appDir := filepath.Dir(appBundlePath)
scriptPath := filepath.Join(os.TempDir(), "academy_update.sh")
scriptContent := fmt.Sprintf(`#!/bin/bash
sleep 2
if ! (rm -rf "%s" && cp -a "%s" "%s"); then
osascript -e "do shell script \"rm -rf \\\"%s\\\" && cp -a \\\"%s\\\" \\\"%s\\\"\" with administrator privileges"
fi
hdiutil detach "%s" -force
open "%s"
rm "$0"
`, appBundlePath, newAppPath, appDir, appBundlePath, newAppPath, appDir, mountPoint, appBundlePath)
os.WriteFile(scriptPath, []byte(scriptContent), 0755)
exec.Command("bash", scriptPath).Start()
wailsruntime.Quit(ctx)
}()
} else {
exec.Command("open", savePath).Start()
wailsruntime.Quit(ctx)
}
} else {
exec.Command("xdg-open", savePath).Start()
wailsruntime.Quit(ctx)
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "https://wails.io/schemas/config.v2.json",
"name": "Academy Lite",
"outputfilename": "Academy Lite",
"frontend:dir": "../../frontend",
"wailsjsdir": "../../frontend/src",
"build:tags": "desktop",
"author": {
"name": "Academy Team",
"email": ""
},
"info": {
"companyName": "Tencent",
"productName": "Academy Lite",
"productVersion": "1.0.0",
"copyright": "Copyright 2026 Tencent",
"comments": "Academy Desktop Edition"
},
"mac": {
"category": "public.app-category.productivity",
"titlebar": "hiddenInset"
}
}
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"context"
"database/sql"
"fmt"
_ "github.com/duckdb/duckdb-go/v2"
)
// duckdbExtensions is the list of DuckDB extensions required by Academy's
// data analysis tool. `spatial` is used for layer metadata (st_read_meta)
// so we can enumerate sheet names from Excel files, while `excel` provides
// the dedicated read_xlsx reader with proper type inference.
var duckdbExtensions = []string{"spatial", "excel"}
func downloadExtensions() {
ctx := context.Background()
sqlDB, err := sql.Open("duckdb", ":memory:")
if err != nil {
panic(err)
}
defer sqlDB.Close()
for _, ext := range duckdbExtensions {
if _, err := sqlDB.ExecContext(ctx, fmt.Sprintf("INSTALL %s;", ext)); err != nil {
panic(fmt.Errorf("failed to install %s extension: %w", ext, err))
}
if _, err := sqlDB.ExecContext(ctx, fmt.Sprintf("LOAD %s;", ext)); err != nil {
panic(fmt.Errorf("failed to load %s extension: %w", ext, err))
}
}
}
func main() {
downloadExtensions()
}
+59
View File
@@ -0,0 +1,59 @@
# Milvus 多语言 BM25 迁移
旧版 Academy 的 Milvus Collection 只有一个默认文本分析器,中文内容可能没有有效 BM25 关键词。`milvus-migrate` 会保留旧 Collection,并复制已有稠密向量到新的多语言 Collection;Milvus 会依据每行的 `language` 字段重新生成 BM25 稀疏向量。
稠密向量的 metric(IP / COSINE / L2)默认从源 Collection 的 embedding 索引读取。不要改成与源 Collection 不同的值,否则同一批向量会按错误距离排序。
## 使用方法
先确保 Milvus 已启动,再在项目根目录执行:
```bash
go run ./cmd/milvus-migrate --source academy_embeddings --target academy_embeddings_multilingual
```
如果当前 shell 已经导入了 `MILVUS_ADDRESS` 和 `MILVUS_COLLECTION`,可以省略对应参数。仅仅把变量写在 `.env.local` 中不会自动注入 `go run` 进程;不确定时建议显式传参:
```bash
go run ./cmd/milvus-migrate \
--address 127.0.0.1:19530 \
--source academy_embeddings \
--target academy_embeddings_multilingual
```
若要核对 metric,可传入与源 Collection 相同的 `--metric-type`(以及环境变量 `MILVUS_METRIC_TYPE`)。传入的值必须与源索引一致,否则迁移会失败。
迁移完成后,把 Academy 的 `MILVUS_COLLECTION` 改为目标前缀并重启服务,**保持原来的 `MILVUS_METRIC_TYPE` 不变**:
```dotenv
MILVUS_COLLECTION=academy_embeddings_multilingual
```
检索列表按 `{前缀}_{维度}` 精确匹配,因此 `academy_embeddings` 不会误搜到 `academy_embeddings_multilingual_*`。切换前缀后,新写入和向量/关键词检索才会都走新 Collection。
迁移程序不会删除旧 Collection。确认中文和英文 BM25 都能召回后,再通过 Milvus 管理工具删除旧 Collection;删除前请先备份。
迁移默认每批读取 64 行,并且只读取重建目标 Collection 所需的字段,不会读取旧 Collection 中生成的 BM25 稀疏向量。若单个文本块特别长,可以显式降低批大小,例如追加 `--batch-size 32`。
## Windows PowerShell 注意事项
Academy 的 `internal/utils` 使用 `pg_query_go` 解析 SQL,该依赖需要 CGO。直接执行 `go run` 时,如果当前会话的 `CGO_ENABLED=0`,会出现 `undefined: pg_query.Parse` 或 `undefined: pg_query.Deparse`。
项目附带了 MSYS2 GCC,可以在当前 PowerShell 会话中临时启用 CGO 后再运行迁移。下面的设置只影响当前窗口,不会修改系统级 Go 配置:
```powershell
# 确认当前目录是包含 go.mod 的项目根目录
if (!(Test-Path -LiteralPath '.\go.mod')) { throw '请先切换到 Academy 项目根目录' }
# 使用项目自带的 GCC,避免 Go 找不到 C 编译器
$compilerBin = Join-Path (Get-Location) '.local-tools\msys64\ucrt64\bin'
$env:CGO_ENABLED = '1'
$env:CC = Join-Path $compilerBin 'gcc.exe'
$env:CXX = Join-Path $compilerBin 'g++.exe'
$env:PATH = "$compilerBin;$env:PATH"
# 运行迁移;metric 沿用源 Collection,不删除旧 Collection
go run ./cmd/milvus-migrate --address 127.0.0.1:19530 --source academy_embeddings --target academy_embeddings_multilingual
```
如果项目目录中没有 `.local-tools\msys64\ucrt64\bin`,请先安装可用的 GCC,并将 `$env:CC`、`$env:CXX` 改为对应的 `gcc.exe`、`g++.exe` 绝对路径。
+97
View File
@@ -0,0 +1,97 @@
// milvus-migrate 将旧版 Milvus Collection 复制为支持中英文 BM25 的新 Collection。
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strings"
"time"
milvusRepo "academy/internal/application/repository/retriever/milvus"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
)
func main() {
sourceDefault := strings.TrimSpace(os.Getenv("MILVUS_COLLECTION"))
if sourceDefault == "" {
sourceDefault = "academy_embeddings"
}
targetDefault := sourceDefault + "_multilingual"
source := flag.String("source", sourceDefault, "旧 Collection 前缀,例如 academy_embeddings")
target := flag.String("target", targetDefault, "新 Collection 前缀,例如 academy_embeddings_multilingual")
address := flag.String("address", envOr("MILVUS_ADDRESS", "localhost:19530"), "Milvus 地址")
username := flag.String("username", os.Getenv("MILVUS_USERNAME"), "Milvus 用户名")
password := flag.String("password", os.Getenv("MILVUS_PASSWORD"), "Milvus 密码")
database := flag.String("database", os.Getenv("MILVUS_DB_NAME"), "Milvus 数据库名")
metric := flag.String(
"metric-type",
strings.TrimSpace(os.Getenv("MILVUS_METRIC_TYPE")),
"稠密向量距离:IP、COSINE 或 L2;省略则沿用源 Collection",
)
batchSize := flag.Int("batch-size", 64, "每批迁移的行数;文本较长时可进一步调小")
flag.Parse()
metricType, err := milvusRepo.ParseMetricType(*metric)
if err != nil {
log.Fatal(err)
}
if strings.TrimSpace(*source) == strings.TrimSpace(*target) {
log.Fatal("--source 和 --target 必须不同;迁移只会复制到新 Collection,不会覆盖旧 Collection")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
connectCtx, cancelConnect := context.WithTimeout(ctx, 30*time.Second)
milvusClient, err := client.New(connectCtx, &client.ClientConfig{
Address: *address,
Username: *username,
Password: *password,
DBName: *database,
})
cancelConnect()
if err != nil {
log.Fatalf("连接 Milvus 失败:%v", err)
}
defer func() {
closeCtx, cancelClose := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelClose()
if err := milvusClient.Close(closeCtx); err != nil {
log.Printf("关闭 Milvus 连接失败:%v", err)
}
}()
summary, err := milvusRepo.MigrateLegacyCollections(ctx, milvusClient, milvusRepo.MultilingualMigrationOptions{
SourceCollectionBaseName: *source,
TargetCollectionBaseName: *target,
MetricType: metricType,
BatchSize: *batchSize,
})
if err != nil {
log.Fatalf(
"迁移失败(已检查 %d 个 Collection,已复制 %d 个 Collection、%d 行):%v",
summary.ExaminedCollections,
summary.MigratedCollections,
summary.MigratedRows,
err,
)
}
fmt.Printf(
"迁移完成:检查 %d 个 Collection,复制 %d 个 Collection、%d 行。旧 Collection 保留未删除。\n",
summary.ExaminedCollections,
summary.MigratedCollections,
summary.MigratedRows,
)
}
func envOr(name, fallback string) string {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
return fallback
}
+125
View File
@@ -0,0 +1,125 @@
// Bootstrap-time hooks that run after the DI container is built but
// before the HTTP server starts listening. These are deliberately
// best-effort: any failure here only warns and does NOT abort startup.
// The reasoning is that an operator running with a misconfigured env
// var should still be able to bring the server up (and fix the issue
// from the running instance) rather than have a typo brick the deploy.
package main
import (
"context"
"os"
"strings"
"go.uber.org/dig"
"academy/internal/logger"
"academy/internal/types/interfaces"
)
// bootstrapEnvVar is the env var that names the email of the user who
// may be promoted to system administrator when the deployment has no
// existing system administrators.
//
// Why an env var (vs a CLI subcommand)?
// - Zero-friction in docker-compose / k8s deploys: set it once in the
// manifest and the very first user account that signs up with that
// email is auto-promoted, with no extra ops step.
// - Idempotent: if the user is already a system admin, bootstrapping is
// a no-op.
// - Safe to leave set: once at least one system admin exists, the env
// var stops granting privileges. That prevents a UI revoke from being
// silently undone on the next restart.
const bootstrapEnvVar = "ACADEMY_BOOTSTRAP_SYSTEM_ADMIN_EMAIL"
// runStartupBootstrap consults the env and applies any one-shot
// bootstrap actions. Currently it only handles system-admin promotion;
// future bootstrap steps (default model seeding, etc.) can be added
// here as additional dig.Invoke calls.
func runStartupBootstrap(c *dig.Container) {
ctx := context.Background()
// Legacy hash repair for migration 000065 placeholder rows. Invoked each
// startup but short-circuits with a cheap EXISTS once every row is
// backfilled (no api_key decryption on the steady-state path).
if err := c.Invoke(func(apiKeySvc interfaces.TenantAPIKeyService) {
if n, err := apiKeySvc.BackfillMissingKeyHashes(ctx); err != nil {
logger.Warnf(ctx, "[bootstrap] tenant api key hash backfill failed: %v", err)
} else if n > 0 {
logger.Infof(ctx, "[bootstrap] backfilled %d legacy tenant api key hash(es)", n)
}
}); err != nil {
logger.Warnf(ctx, "[bootstrap] failed to resolve TenantAPIKeyService: %v", err)
}
email := strings.TrimSpace(os.Getenv(bootstrapEnvVar))
if email == "" {
return
}
// dig.Invoke resolves UserService from the container; if user
// service registration is broken we want to know loudly, but still
// not abort startup — bootstrap is best-effort.
if err := c.Invoke(func(userSvc interfaces.UserService) {
bootstrapSystemAdmin(ctx, userSvc, email)
}); err != nil {
logger.Warnf(ctx, "[bootstrap] failed to resolve UserService: %v", err)
}
}
// bootstrapSystemAdmin promotes the user identified by `email` to system
// administrator only when the deployment currently has no system admins.
// The function is idempotent and non-fatal — it warns and returns on
// every error path.
//
// The bootstrap intentionally does NOT create a user when the email is
// not yet registered: account creation is a workflow with side effects
// (password hashing, tenant assignment, audit) that we don't want to
// short-circuit. Operators should sign up normally first, then set the
// env var on the next restart.
func bootstrapSystemAdmin(ctx context.Context, userSvc interfaces.UserService, email string) {
user, err := userSvc.GetUserByEmail(ctx, email)
if err != nil {
// "not found" surfaces as an error in this codebase; treat it
// gently — operators commonly set the var before the user has
// signed up. The next restart after registration will succeed.
logger.Warnf(ctx,
"[bootstrap] %s=%s: user lookup failed (have they signed up yet?): %v",
bootstrapEnvVar, email, err)
return
}
if user == nil {
logger.Warnf(ctx,
"[bootstrap] %s=%s: no matching user (will retry on next restart)",
bootstrapEnvVar, email)
return
}
if user.IsSystemAdmin {
logger.Infof(ctx,
"[bootstrap] %s=%s: user %s is already a system admin (no-op)",
bootstrapEnvVar, email, user.ID)
return
}
_, total, err := userSvc.ListSystemAdmins(ctx, 0, 1)
if err != nil {
logger.Warnf(ctx,
"[bootstrap] %s=%s: cannot verify existing system admins, skipping promotion: %v",
bootstrapEnvVar, email, err)
return
}
if total > 0 {
logger.Infof(ctx,
"[bootstrap] %s=%s: %d system admin(s) already exist; not promoting user %s",
bootstrapEnvVar, email, total, user.ID)
return
}
user.IsSystemAdmin = true
if err := userSvc.UpdateUser(ctx, user); err != nil {
logger.Warnf(ctx,
"[bootstrap] %s=%s: failed to promote user %s: %v",
bootstrapEnvVar, email, user.ID, err)
return
}
logger.Infof(ctx,
"[bootstrap] promoted user %s (%s) to system admin via %s",
user.ID, email, bootstrapEnvVar)
}
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"context"
"net"
"time"
"academy/internal/logger"
)
func listenWithRetry(addr string, maxRetries int, baseDelay time.Duration) (net.Listener, error) {
var lastErr error
for i := 0; i < maxRetries; i++ {
listener, err := net.Listen("tcp", addr)
if err == nil {
return listener, nil
}
lastErr = err
if i < maxRetries-1 {
delay := baseDelay * time.Duration(1<<uint(i))
if delay > 3*time.Second {
delay = 3 * time.Second
}
logger.Warnf(context.Background(), "Port %s in use, retrying in %v... (%d/%d)", addr, delay, i+1, maxRetries)
time.Sleep(delay)
}
}
return nil, lastErr
}
+149
View File
@@ -0,0 +1,149 @@
// Package main is the main package for the Academy server
// It contains the main function and the entry point for the server
//
// @title Academy API
// @version 1.0
// @description Academy 知识库管理系统 API 文档
// @termsOfService http://swagger.io/terms/
//
// @contact.name Academy Github
// @contact.url https://academy
//
// @BasePath /api/v1
//
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description 用户登录认证:输入 Bearer {token} 格式的 JWT 令牌
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name X-API-Key
// @description API Key 认证:空间 Key 固定访问所属空间;平台 Key 调用空间接口时需同时传 X-Tenant-ID
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
"academy/internal/application/service"
"academy/internal/config"
"academy/internal/container"
"academy/internal/logger"
"academy/internal/runtime"
"academy/internal/types/interfaces"
)
func main() {
// Set Gin mode
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
// Mute Gin's per-route registration spam (one line per route × ~150
// routes) — replaced by a single summary printed after router build.
runtime.SilenceGinRouteSpam()
// Print the env banner before container build so operators see what
// config landed even when DB / storage init fails.
runtime.LogStartupEnv(context.Background())
runtime.MarkServerStarted()
// Build dependency injection container
c := container.BuildContainer(runtime.GetContainer())
// One-shot bootstrap hooks (e.g. promote env-named user to system
// admin). Best-effort: never aborts startup — see bootstrap.go.
runStartupBootstrap(c)
// Run application
err := c.Invoke(func(
cfg *config.Config,
router *gin.Engine,
resourceCleaner interfaces.ResourceCleaner,
systemSettingSvc interfaces.SystemSettingService,
modelCatalogSvc *service.ModelCatalogService,
) error {
// Create HTTP server
server := &http.Server{
Handler: router,
}
addr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
listener, err := listenWithRetry(addr, 10, 300*time.Millisecond)
if err != nil {
return fmt.Errorf("failed to start server: %v", err)
}
ctx, done := context.WithCancel(context.Background())
modelCatalogSvc.Start(ctx)
// Start the system_settings pubsub subscriber. Runs in its own
// goroutine and exits when ctx is cancelled at shutdown. Best-
// effort: an error here only warns (Redis may legitimately be
// disabled in lite-mode deployments — the service no-ops in
// that case anyway).
if err := systemSettingSvc.SubscribeRedis(ctx); err != nil {
logger.Warnf(ctx, "[system_settings] subscribe failed: %v", err)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, shutdownSignals...)
go func() {
sig := <-signals
logger.Infof(context.Background(), "Received signal: %v, starting server shutdown...", sig)
drainBudget, cleanupBudget := runtime.ShutdownBudgets(cfg.Server.ShutdownTimeout)
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), drainBudget)
defer shutdownCancel()
// Second signal → force close all connections immediately.
go func() {
sig := <-signals
logger.Warnf(context.Background(), "Received second signal: %v, forcing shutdown...", sig)
server.Close()
}()
// Do NOT close the listener manually before Shutdown. Serve would
// return the raw accept error ("use of closed network connection")
// instead of ErrServerClosed, and logger.Fatalf → os.Exit(1) would
// kill the process before ResourceCleaner runs. Shutdown closes
// listeners first, so the port is released before the drain.
if err := server.Shutdown(shutdownCtx); err != nil {
logger.Errorf(context.Background(), "Server forced to shutdown: %v", err)
server.Close()
}
logger.Info(context.Background(), "Cleaning up resources...")
// Fresh context sized from the reserved slice of ShutdownTimeout.
// Drain must not hand cleanup an already-expired context, and the
// two slices must still add up to one supervisor grace period.
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), cleanupBudget)
defer cleanupCancel()
errs := resourceCleaner.Cleanup(cleanupCtx)
if len(errs) > 0 {
logger.Errorf(context.Background(), "Errors occurred during resource cleanup: %v", errs)
}
logger.Info(context.Background(), "Server has exited")
done()
}()
runtime.LogGinRouteCount(context.Background())
logger.Infof(context.Background(), "Server is running at %s", addr)
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("server error: %v", err)
}
<-ctx.Done()
return nil
})
if err != nil {
logger.Fatalf(context.Background(), "Failed to run application: %v", err)
}
}
+71
View File
@@ -0,0 +1,71 @@
package main
import (
"context"
"errors"
"net"
"net/http"
"testing"
"time"
)
func startTestServer(t *testing.T) (*http.Server, net.Listener, <-chan error) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
srv := &http.Server{Handler: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})}
errCh := make(chan error, 1)
go func() {
errCh <- srv.Serve(ln)
}()
waitUntilAccepting(t, ln.Addr().String())
return srv, ln, errCh
}
func waitUntilAccepting(t *testing.T, addr string) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("tcp", addr, 50*time.Millisecond)
if err == nil {
_ = conn.Close()
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("server at %s did not accept", addr)
}
func TestShutdownReturnsErrServerClosed(t *testing.T) {
srv, _, errCh := startTestServer(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
t.Fatalf("Shutdown: %v", err)
}
select {
case err := <-errCh:
if !errors.Is(err, http.ErrServerClosed) {
t.Fatalf("Serve err = %v, want ErrServerClosed", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Serve did not return")
}
}
func TestManualListenerCloseIsNotErrServerClosed(t *testing.T) {
_, ln, errCh := startTestServer(t)
if err := ln.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
select {
case err := <-errCh:
if err == nil || errors.Is(err, http.ErrServerClosed) {
t.Fatalf("Serve err = %v, want the raw accept error", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Serve did not return")
}
}
+10
View File
@@ -0,0 +1,10 @@
//go:build !windows
package main
import (
"os"
"syscall"
)
var shutdownSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP}
+10
View File
@@ -0,0 +1,10 @@
//go:build windows
package main
import (
"os"
"syscall"
)
var shutdownSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}