Skip to content

Commit

Permalink
implement mechanism to detect ui-freezes; "soft-restart" application …
Browse files Browse the repository at this point in the history
…if detect them
rainu committed Jan 22, 2025
1 parent 2581cd1 commit ceb07a7
Showing 17 changed files with 244 additions and 31 deletions.
14 changes: 8 additions & 6 deletions config/debug.go
Original file line number Diff line number Diff line change
@@ -6,15 +6,17 @@ import (
)

type DebugConfig struct {
LogLevel int `yaml:"log-level"`
PprofAddress string `yaml:"pprof-address" usage:"Address for the pprof server (only available for debug binary)"`
VueDevTools VueDevToolsConfig `yaml:"vue-dev-tools"`
WebKit WebKitInspectorConfig `yaml:"webkit" usage:"Webkit debug configuration (only available for debug binary): "`
PrintVersion bool `config:"version" yaml:"-" short:"v" usage:"Show the version"`
LogLevel int `yaml:"log-level"`
PprofAddress string `yaml:"pprof-address" usage:"Address for the pprof server (only available for debug binary)"`
VueDevTools VueDevToolsConfig `yaml:"vue-dev-tools"`
WebKit WebKitInspectorConfig `yaml:"webkit" usage:"Webkit debug configuration (only available for debug binary): "`
EnableCrashDetection bool `yaml:"enable" usage:"Enable crash detection. If a crash is detected the application will try to recover the last state"`
RestartShortcut Shortcut `yaml:"shortcut" usage:"The shortcut for triggering a restart"`
PrintVersion bool `config:"version" yaml:"-" short:"v" usage:"Show the version"`
}

type VueDevToolsConfig struct {
Host string `yaml:"host" usage:"The host of the vue dev tools server. If empty the dev tools will be disabled."`
Host string `yaml:"host" usage:"The host of the vue dev tools server. If empty the dev tools will be disabled"`
Port int `yaml:"port" usage:"The port of the vue dev tools server"`
}

5 changes: 5 additions & 0 deletions config/default.go
Original file line number Diff line number Diff line change
@@ -22,6 +22,11 @@ func defaultConfig() *Config {
OpenInspectorOnStartup: false,
HttpServerAddress: "",
},
EnableCrashDetection: true,
RestartShortcut: Shortcut{
Alt: true,
Code: "keyr",
},
PrintVersion: false,
},
LLM: llm.LLMConfig{
2 changes: 1 addition & 1 deletion config/parser.go
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@ func Parse(arguments []string, env []string) *Config {
} else if target == PrinterTargetErr {
c.Printer.Targets = append(c.Printer.Targets, os.Stderr)
} else {
file, err := os.Create(target)
file, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
panic(fmt.Errorf("Error creating printer target file: %w", err))
}
1 change: 1 addition & 0 deletions controller/base.go
Original file line number Diff line number Diff line change
@@ -25,6 +25,7 @@ type Controller struct {

vueAppMounted bool
streamBuffer []byte
lastState string
}

type llmAskResult struct {
3 changes: 2 additions & 1 deletion controller/build.go
Original file line number Diff line number Diff line change
@@ -16,9 +16,10 @@ import (
"net/http"
)

func BuildFromConfig(cfg *config.Config) (ctrl *Controller, err error) {
func BuildFromConfig(cfg *config.Config, lastState string) (ctrl *Controller, err error) {
ctrl = &Controller{
appConfig: cfg,
lastState: lastState,
}

printer := io.MultiResponsePrinter{}
17 changes: 17 additions & 0 deletions controller/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package controller

import "github.com/wailsapp/wails/v2/pkg/runtime"

func (c *Controller) TriggerRestart() {
runtime.EventsEmit(c.ctx, "system:restart")
}

func (c *Controller) Restart(state string) {
c.lastState = state
runtime.Hide(c.ctx)
runtime.Quit(c.ctx)
}

func (c *Controller) GetLastState() string {
return c.lastState
}
4 changes: 4 additions & 0 deletions controller/vue.go
Original file line number Diff line number Diff line change
@@ -19,6 +19,10 @@ func (c *Controller) AppMounted() {
c.vueAppMounted = true
}

func (c *Controller) IsAppMounted() bool {
return c.vueAppMounted
}

func (c *Controller) applyInitialWindowConfig() {
_, height := runtime.WindowGetSize(c.ctx)

21 changes: 15 additions & 6 deletions frontend/src/App.vue
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@

<script lang="ts">
import { defineComponent } from 'vue'
import { Shutdown } from '../wailsjs/go/controller/Controller'
import { TriggerRestart, Shutdown } from '../wailsjs/go/controller/Controller'
export default defineComponent({
data() {
@@ -36,15 +36,24 @@ export default defineComponent({
},
methods: {
handleGlobalKeydown(event: KeyboardEvent) {
const code = event.code.toLowerCase() === this.$appConfig.UI.QuitShortcut.Code.toLowerCase()
const ctrl = event.ctrlKey === this.$appConfig.UI.QuitShortcut.Ctrl
const shift = event.shiftKey === this.$appConfig.UI.QuitShortcut.Shift
const alt = event.altKey === this.$appConfig.UI.QuitShortcut.Alt
const meta = event.metaKey === this.$appConfig.UI.QuitShortcut.Meta
let code = event.code.toLowerCase() === this.$appConfig.UI.QuitShortcut.Code.toLowerCase()
let ctrl = event.ctrlKey === this.$appConfig.UI.QuitShortcut.Ctrl
let shift = event.shiftKey === this.$appConfig.UI.QuitShortcut.Shift
let alt = event.altKey === this.$appConfig.UI.QuitShortcut.Alt
let meta = event.metaKey === this.$appConfig.UI.QuitShortcut.Meta
if (code && ctrl && shift && alt && meta) {
Shutdown()
}
code = event.code.toLowerCase() === this.$appConfig.Debug.RestartShortcut.Code.toLowerCase()
ctrl = event.ctrlKey === this.$appConfig.Debug.RestartShortcut.Ctrl
shift = event.shiftKey === this.$appConfig.Debug.RestartShortcut.Shift
alt = event.altKey === this.$appConfig.Debug.RestartShortcut.Alt
meta = event.metaKey === this.$appConfig.Debug.RestartShortcut.Meta
if (code && ctrl && shift && alt && meta) {
TriggerRestart()
}
},
opacityValue(isHovering: boolean | null): number {
switch (this.$appConfig.UI.Window.Translucent) {
52 changes: 45 additions & 7 deletions frontend/src/views/Home.vue
Original file line number Diff line number Diff line change
@@ -52,7 +52,14 @@
</template>

<script lang="ts">
import { AppMounted, LLMAsk, LLMInterrupt, LLMWait } from '../../wailsjs/go/controller/Controller'
import {
AppMounted,
GetLastState,
LLMAsk,
LLMInterrupt,
LLMWait,
Restart,
} from '../../wailsjs/go/controller/Controller'
import { EventsOn, WindowGetSize, WindowSetPosition, WindowSetSize } from '../../wailsjs/runtime'
import ChatMessage, { ContentType, Role } from '../components/ChatMessage.vue'
import ChatInput, { ChatInputType } from '../components/ChatInput.vue'
@@ -68,6 +75,11 @@ type HistoryEntry = {
Message: controller.LLMMessage
}
type State = {
input: ChatInputType
chatHistory: HistoryEntry[]
}
export default {
name: 'Home',
components: { UserScrollDetector, ZoomDetector, ChatInput, ChatMessage },
@@ -222,14 +234,40 @@ export default {
EventsOn('llm:stream:chunk', (chunk: string) => {
this.outputStream[0].Content += chunk
})
EventsOn('system:restart', () => {
// backend requested a restart
// so we have to save the current state and restart the app
// but we have to wait until the progress is done (if any)
const restartAfterProgress = () => {
if(this.progress) {
setTimeout(restartAfterProgress, 50)
} else {
const state = {
input: this.input,
chatHistory: this.chatHistory,
} as State
AppMounted()
.then(() => {
if (this.$appConfig.UI.Prompt.InitValue) {
this.waitForLLM()
Restart(JSON.stringify(state))
}
})
.then(() => this.adjustHeight())
}
restartAfterProgress()
})
GetLastState().then((stateAsString) => {
if (stateAsString) {
const state = JSON.parse(stateAsString) as State
this.input = state.input
this.chatHistory = state.chatHistory
}
AppMounted()
.then(() => {
if (this.$appConfig.UI.Prompt.InitValue && !stateAsString) {
this.waitForLLM()
}
})
.then(() => this.adjustHeight())
})
},
updated() {
this.$nextTick(() => {
8 changes: 8 additions & 0 deletions frontend/wailsjs/go/controller/Controller.d.ts
Original file line number Diff line number Diff line change
@@ -9,6 +9,10 @@ export function GetApplicationConfig():Promise<config.Config>;

export function GetAssetMeta(arg1:string):Promise<controller.AssetMeta>;

export function GetLastState():Promise<string>;

export function IsAppMounted():Promise<boolean>;

export function LLMAsk(arg1:controller.LLMAskArgs):Promise<string>;

export function LLMInterrupt():Promise<void>;
@@ -19,4 +23,8 @@ export function Log(arg1:string,arg2:string):Promise<void>;

export function OpenFileDialog(arg1:controller.OpenFileDialogArgs):Promise<Array<string>>;

export function Restart(arg1:string):Promise<void>;

export function Shutdown():Promise<void>;

export function TriggerRestart():Promise<void>;
16 changes: 16 additions & 0 deletions frontend/wailsjs/go/controller/Controller.js
Original file line number Diff line number Diff line change
@@ -14,6 +14,14 @@ export function GetAssetMeta(arg1) {
return window['go']['controller']['Controller']['GetAssetMeta'](arg1);
}

export function GetLastState() {
return window['go']['controller']['Controller']['GetLastState']();
}

export function IsAppMounted() {
return window['go']['controller']['Controller']['IsAppMounted']();
}

export function LLMAsk(arg1) {
return window['go']['controller']['Controller']['LLMAsk'](arg1);
}
@@ -34,6 +42,14 @@ export function OpenFileDialog(arg1) {
return window['go']['controller']['Controller']['OpenFileDialog'](arg1);
}

export function Restart(arg1) {
return window['go']['controller']['Controller']['Restart'](arg1);
}

export function Shutdown() {
return window['go']['controller']['Controller']['Shutdown']();
}

export function TriggerRestart() {
return window['go']['controller']['Controller']['TriggerRestart']();
}
4 changes: 4 additions & 0 deletions frontend/wailsjs/go/models.ts
Original file line number Diff line number Diff line change
@@ -33,6 +33,8 @@ export namespace config {
PprofAddress: string;
VueDevTools: VueDevToolsConfig;
WebKit: WebKitInspectorConfig;
EnableCrashDetection: boolean;
RestartShortcut: Shortcut;
PrintVersion: boolean;

static createFrom(source: any = {}) {
@@ -45,6 +47,8 @@ export namespace config {
this.PprofAddress = source["PprofAddress"];
this.VueDevTools = this.convertValues(source["VueDevTools"], VueDevToolsConfig);
this.WebKit = this.convertValues(source["WebKit"], WebKitInspectorConfig);
this.EnableCrashDetection = source["EnableCrashDetection"];
this.RestartShortcut = this.convertValues(source["RestartShortcut"], Shortcut);
this.PrintVersion = source["PrintVersion"];
}

13 changes: 10 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -6,8 +6,9 @@ require (
github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd
github.com/gabriel-vasile/mimetype v1.4.7
github.com/rainu/go-command-chain v0.4.0
github.com/shirou/gopsutil/v4 v4.24.12
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.9.0
github.com/stretchr/testify v1.10.0
github.com/tmc/langchaingo v0.1.12
github.com/wailsapp/wails/v2 v2.9.2
gopkg.in/yaml.v3 v3.0.1
@@ -17,6 +18,7 @@ require (
github.com/bep/debounce v1.2.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/ebitengine/purego v0.8.1 // indirect
github.com/gage-technologies/mistral-go v1.0.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
@@ -30,23 +32,28 @@ require (
github.com/leaanthony/gosod v1.0.3 // indirect
github.com/leaanthony/slicer v1.6.0 // indirect
github.com/leaanthony/u v1.1.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pkoukk/tiktoken-go v0.1.6 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/samber/lo v1.38.1 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/tkrajina/go-reflector v0.5.6 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/wailsapp/go-webview2 v1.0.16 // indirect
github.com/wailsapp/go-webview2 v1.0.18 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/crypto v0.29.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.31.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.20.0 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
)
31 changes: 25 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
@@ -11,6 +11,8 @@ github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yA
github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd h1:QMSNEh9uQkDjyPwu/J541GgSH+4hw+0skJDIj9HJ3mE=
github.com/dop251/goja v0.0.0-20241024094426-79f3a7efcdbd/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
github.com/ebitengine/purego v0.8.1 h1:sdRKd6plj7KYW33EH5As6YKfe8m9zbN9JMrOjNVF/BE=
github.com/ebitengine/purego v0.8.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/gabriel-vasile/mimetype v1.4.7 h1:SKFKl7kD0RiPdbht0s7hFtjl489WcQ1VyPW8ZzUMYCA=
github.com/gabriel-vasile/mimetype v1.4.7/go.mod h1:GDlAgAyIRT27BhFl53XNAFtfjzOkLaF35JdEG0P7LtU=
github.com/gage-technologies/mistral-go v1.0.0 h1:Hwk0uJO+Iq4kMX/EwbfGRUq9zkO36w7HZ/g53N4N73A=
@@ -21,6 +23,7 @@ github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyL
github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U=
@@ -48,6 +51,8 @@ github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/
github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8=
github.com/leaanthony/u v1.1.0 h1:2n0d2BwPVXSUq5yhe8lJPHdxevE2qK5G99PMStMZMaI=
github.com/leaanthony/u v1.1.0/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
@@ -66,6 +71,8 @@ github.com/pkoukk/tiktoken-go v0.1.6/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYde
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/rainu/go-command-chain v0.4.0 h1:qgrNbNsqkTfJHdwGzVuGPPK+p+XSnGAhAT/8x1A8SLE=
github.com/rainu/go-command-chain v0.4.0/go.mod h1:RvLsDKnTGD9XoUY7nmBz73ayffI0bFCDH/EVJPRgfks=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@@ -75,12 +82,18 @@ github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDN
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/shirou/gopsutil/v4 v4.24.12 h1:qvePBOk20e0IKA1QXrIIU+jmk+zEiYVVx06WjBRlZo4=
github.com/shirou/gopsutil/v4 v4.24.12/go.mod h1:DCtMPAad2XceTeIAbGyVfycbYQNBGk2P8cvDi7/VN9o=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
github.com/tkrajina/go-reflector v0.5.6 h1:hKQ0gyocG7vgMD2M3dRlYN6WBBOmdoOzJ6njQSepKdE=
github.com/tkrajina/go-reflector v0.5.6/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
github.com/tmc/langchaingo v0.1.12 h1:yXwSu54f3b1IKw0jJ5/DWu+qFVH1NBblwC0xddBzGJE=
@@ -90,12 +103,14 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/wailsapp/go-webview2 v1.0.16 h1:wffnvnkkLvhRex/aOrA3R7FP7rkvOqL/bir1br7BekU=
github.com/wailsapp/go-webview2 v1.0.16/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/go-webview2 v1.0.18 h1:SSSCoLA+MYikSp1U0WmvELF/4c3x5kH8Vi31TKyZ4yk=
github.com/wailsapp/go-webview2 v1.0.18/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wailsapp/wails/v2 v2.9.2 h1:Xb5YRTos1w5N7DTMyYegWaGukCP2fIaX9WF21kPPF2k=
github.com/wailsapp/wails/v2 v2.9.2/go.mod h1:uehvlCwJSFcBq7rMCGfk4rxca67QQGsbg5Nm4m9UnBs=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
@@ -106,20 +121,24 @@ golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
8 changes: 8 additions & 0 deletions health/process.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//go:build !linux

package health

import "context"

func ObserveProcess(ctx context.Context, pid int32, threshold float64, callback func()) {
}
39 changes: 39 additions & 0 deletions health/process_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//go:build linux

package health

import (
"context"
"github.com/shirou/gopsutil/v4/process"
"log/slog"
"time"
)

const observationInterval = 250 * time.Millisecond

func ObserveProcess(ctx context.Context, pid int32, threshold float64, callback func()) {
p, err := process.NewProcess(pid)
if err != nil {
slog.Error("Unable to get process. Observation is inactive!", "pid", pid, "error", err)
return
}

go func() {
for {
select {
case <-ctx.Done():
return
case <-time.After(observationInterval):
}

percent, err := p.Percent(observationInterval)
if err != nil {
slog.Error("Unable to get process usage.", "pid", pid, "error", err)
continue
}
if percent > threshold {
callback()
}
}
}()
}
37 changes: 36 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package main

import (
"context"
"embed"
"fmt"
"github.com/rainu/ask-mai/config"
"github.com/rainu/ask-mai/controller"
"github.com/rainu/ask-mai/health"
cmdchain "github.com/rainu/go-command-chain"
"github.com/wailsapp/wails/v2"
"log/slog"
"os"
"runtime"
"slices"
"strings"
"syscall"
)

const (
lastStateEnv = "_ASK_MAI_LAST_STATE"
)

//go:embed frontend/dist
@@ -58,7 +66,7 @@ func main() {
}
}

ctrl, err := controller.BuildFromConfig(cfg)
ctrl, err := controller.BuildFromConfig(cfg, os.Getenv(lastStateEnv))
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(2)
@@ -71,7 +79,34 @@ func main() {
os.Setenv("WEBKIT_INSPECTOR_HTTP_SERVER", cfg.Debug.WebKit.HttpServerAddress)
}

if cfg.Debug.EnableCrashDetection {
threadId, _, errno := syscall.Syscall(syscall.SYS_GETTID, 0, 0, 0)
if errno != 0 {
slog.Warn("Error getting thread ID. Process health observation is inactive!", "error", errno)
} else {
oCtx, oCancel := context.WithCancel(context.Background())
health.ObserveProcess(oCtx, int32(threadId), 98.0, func() {
if ctrl.IsAppMounted() {
slog.Warn("Restarting application because of high CPU usage: Seems like a freeze.")
ctrl.TriggerRestart()
oCancel() //prevent multiple restarts
}
})
}
}

err = wails.Run(controller.GetOptions(ctrl, icon, assets))
if !buildMode && ctrl.GetLastState() != "" {
ae := map[any]any{
lastStateEnv: ctrl.GetLastState(),
}

//TODO: dont know why stdout doesnt work properly (os.Stderr would work)
cmdchain.Builder().WithInput(os.Stdin).
Join(os.Args[0], os.Args[1:]...).WithAdditionalEnvironmentMap(ae).
Finalize().WithError(os.Stderr).WithOutput(os.Stdout).
Run()
}

if err != nil {
fmt.Fprintln(os.Stderr, err.Error())

0 comments on commit ceb07a7

Please sign in to comment.