"vscode:/vscode.git/clone" did not exist on "d137b800f739b66e253636404885f2c4f0b9254b"
index.ts 5.93 KB
Newer Older
1
2
import { spawn, ChildProcess } from 'child_process'
import { app, autoUpdater, dialog, Tray, Menu, BrowserWindow, MenuItemConstructorOptions } from 'electron'
Eva Ho's avatar
Eva Ho committed
3
import Store from 'electron-store'
Eva Ho's avatar
Eva Ho committed
4
5
import winston from 'winston'
import 'winston-daily-rotate-file'
Bruce MacDonald's avatar
Bruce MacDonald committed
6
import * as path from 'path'
Jeffrey Morgan's avatar
Jeffrey Morgan committed
7

Jeffrey Morgan's avatar
Jeffrey Morgan committed
8
import { analytics, id } from './telemetry'
Jeffrey Morgan's avatar
Jeffrey Morgan committed
9
import { installed } from './install'
Jeffrey Morgan's avatar
Jeffrey Morgan committed
10

Jeffrey Morgan's avatar
Jeffrey Morgan committed
11
12
require('@electron/remote/main').initialize()

13
14
15
16
if (require('electron-squirrel-startup')) {
  app.quit()
}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
17
const store = new Store()
18

19
20
21
let welcomeWindow: BrowserWindow | null = null

declare const MAIN_WINDOW_WEBPACK_ENTRY: string
22

23
24
25
26
27
28
29
30
31
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({
      filename: path.join(app.getPath('home'), '.ollama', 'logs', 'server.log'),
      maxsize: 1024 * 1024 * 20,
      maxFiles: 5,
    }),
  ],
Jeffrey Morgan's avatar
Jeffrey Morgan committed
32
  format: winston.format.printf(info => info.message),
Eva Ho's avatar
Eva Ho committed
33
34
})

35
36
37
38
app.on('ready', () => {
  const gotTheLock = app.requestSingleInstanceLock()
  if (!gotTheLock) {
    app.exit(0)
39
    return
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  }

  app.on('second-instance', () => {
    if (app.hasSingleInstanceLock()) {
      app.releaseSingleInstanceLock()
    }

    if (proc) {
      proc.off('exit', restart)
      proc.kill()
    }

    app.exit(0)
  })

  app.focus({ steal: true })

  init()
})

60
61
62
63
64
65
66
67
function firstRunWindow() {
  // Create the browser window.
  welcomeWindow = new BrowserWindow({
    width: 400,
    height: 500,
    frame: false,
    fullscreenable: false,
    resizable: false,
68
69
    movable: true,
    show: false,
70
71
72
73
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
74
    alwaysOnTop: true,
75
76
77
78
79
  })

  require('@electron/remote/main').enable(welcomeWindow.webContents)

  welcomeWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY)
80
  welcomeWindow.on('ready-to-show', () => welcomeWindow.show())
81
82
}

83
let tray: Tray | null = null
Eva Ho's avatar
Eva Ho committed
84

85
function setTray(updateAvailable: boolean) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
86
87
88
89
90
91
92
93
  const updateItems: MenuItemConstructorOptions[] = [
    { label: 'An update is available', enabled: false },
    {
      label: 'Restart to update',
      click: () => autoUpdater.quitAndInstall(),
    },
    { type: 'separator' },
  ]
94

95
  const menu = Menu.buildFromTemplate([
Jeffrey Morgan's avatar
Jeffrey Morgan committed
96
    ...(updateAvailable ? updateItems : []),
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    { role: 'quit', label: 'Quit Ollama', accelerator: 'Command+Q' },
  ])

  const iconPath = app.isPackaged
    ? updateAvailable
      ? path.join(process.resourcesPath, 'iconUpdateTemplate.png')
      : path.join(process.resourcesPath, 'iconTemplate.png')
    : updateAvailable
    ? path.join(__dirname, '..', '..', 'assets', 'iconUpdateTemplate.png')
    : path.join(__dirname, '..', '..', 'assets', 'iconTemplate.png')

  if (!tray) {
    tray = new Tray(iconPath)
  }
Jeffrey Morgan's avatar
Jeffrey Morgan committed
111

112
113
114
  tray.setToolTip(updateAvailable ? 'An update is available' : 'Ollama')
  tray.setContextMenu(menu)
  tray.setImage(iconPath)
115
116
}

117
let proc: ChildProcess = null
Jeffrey Morgan's avatar
Jeffrey Morgan committed
118

Jeffrey Morgan's avatar
Jeffrey Morgan committed
119
120
function server() {
  const binary = app.isPackaged
Eva Ho's avatar
Eva Ho committed
121
122
    ? path.join(process.resourcesPath, 'ollama')
    : path.resolve(process.cwd(), '..', 'ollama')
Jeffrey Morgan's avatar
Jeffrey Morgan committed
123

124
  proc = spawn(binary, ['serve'])
Jeffrey Morgan's avatar
Jeffrey Morgan committed
125

Jeffrey Morgan's avatar
Jeffrey Morgan committed
126
  proc.stdout.on('data', data => {
Eva Ho's avatar
Eva Ho committed
127
128
    logger.info(data.toString().trim())
  })
Jeffrey Morgan's avatar
Jeffrey Morgan committed
129

Jeffrey Morgan's avatar
Jeffrey Morgan committed
130
  proc.stderr.on('data', data => {
Eva Ho's avatar
Eva Ho committed
131
132
    logger.error(data.toString().trim())
  })
133

Eva Ho's avatar
Eva Ho committed
134
  proc.on('exit', restart)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
135
136
}

137
138
function restart() {
  setTimeout(server, 1000)
139
140
}

141
142
143
144
145
146
147
148
app.on('before-quit', () => {
  if (proc) {
    proc.off('exit', restart)
    proc.kill()
  }
})

function init() {
149
150
151
152
153
154
155
156
157
  if (app.isPackaged) {
    heartbeat()
    autoUpdater.checkForUpdates()
    setInterval(() => {
      heartbeat()
      autoUpdater.checkForUpdates()
    }, 60 * 60 * 1000)
  }

Jeffrey Morgan's avatar
Jeffrey Morgan committed
158
159
  setTray(false)

160
  if (process.platform === 'darwin') {
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    if (app.isPackaged) {
      if (!app.isInApplicationsFolder()) {
        const chosen = dialog.showMessageBoxSync({
          type: 'question',
          buttons: ['Move to Applications', 'Do Not Move'],
          message: 'Ollama works best when run from the Applications directory.',
          defaultId: 0,
          cancelId: 1,
        })

        if (chosen === 0) {
          try {
            app.moveToApplicationsFolder({
              conflictHandler: conflictType => {
                if (conflictType === 'existsAndRunning') {
                  dialog.showMessageBoxSync({
                    type: 'info',
                    message: 'Cannot move to Applications directory',
                    detail:
                      'Another version of Ollama is currently running from your Applications directory. Close it first and try again.',
                  })
                }
                return true
              },
            })
            return
          } catch (e) {
Eva Ho's avatar
Eva Ho committed
188
            logger.error(`[Move to Applications] Failed to move to applications folder - ${e.message}}`)
189
          }
190
191
192
        }
      }
    }
193
  }
Jeffrey Morgan's avatar
Jeffrey Morgan committed
194

195
  server()
196

197
  if (store.get('first-time-run') && installed()) {
198
199
200
201
    if (process.platform === 'darwin') {
      app.dock.hide()
    }

202
    app.setLoginItemSettings({ openAtLogin: app.getLoginItemSettings().openAtLogin })
203
    return
204
  }
205
206
207
208

  // This is the first run or the CLI is no longer installed
  app.setLoginItemSettings({ openAtLogin: true })
  firstRunWindow()
209
}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
210

Jeffrey Morgan's avatar
Jeffrey Morgan committed
211
212
213
214
215
216
217
218
219
220
221
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
Jeffrey Morgan's avatar
Jeffrey Morgan committed
222
223
224
autoUpdater.setFeedURL({
  url: `https://ollama.ai/api/update?os=${process.platform}&arch=${process.arch}&version=${app.getVersion()}`,
})
225

Jeffrey Morgan's avatar
Jeffrey Morgan committed
226
227
228
229
async function heartbeat() {
  analytics.track({
    anonymousId: id(),
    event: 'heartbeat',
Jeffrey Morgan's avatar
Jeffrey Morgan committed
230
231
232
    properties: {
      version: app.getVersion(),
    },
Jeffrey Morgan's avatar
Jeffrey Morgan committed
233
234
235
  })
}

236
autoUpdater.on('error', e => {
237
  console.error(`update check failed - ${e.message}`)
238
239
})

240
241
autoUpdater.on('update-downloaded', () => {
  setTray(true)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
242
})