oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/chat"
5 "amadan.net/oficina/equipo/internal/equipo/door"
6 "amadan.net/oficina/equipo/internal/equipo/notifications"
7 "amadan.net/oficina/equipo/internal/equipo/oficina"
8 "amadan.net/oficina/equipo/internal/equipo/oficinaid"
9 "amadan.net/oficina/equipo/internal/teamprobe"
10 "amadan.net/rastrillo/rastrillo/sessions"
11 "context"
12 "encoding/json"
13 "errors"
14 "gorm.io/gorm"
15 "log/slog"
16 "net/http"
17 "net/url"
18 "sync"
19 "time"
20
21 "github.com/go-chi/chi/v5"
22
23 "amadan.net/oficina/equipo/internal/equipo/personapi"
24 "amadan.net/oficina/equipo/internal/equipo/push"
25 "amadan.net/oficina/equipo/internal/release"
26 "amadan.net/oficina/equipo/internal/wire"
27 "amadan.net/rastrillo/rastrillo"
28 "amadan.net/rastrillo/rastrillo/auth"
29 "amadan.net/rastrillo/rastrillo/background"
30 "amadan.net/rastrillo/rastrillo/db"
31 "amadan.net/rastrillo/rastrillo/live"
32 _ "amadan.net/rastrillo/rastrillo/locales/en"
33 "amadan.net/rastrillo/rastrillo/mail"
34 "amadan.net/rastrillo/rastrillo/migrate"
35 "amadan.net/rastrillo/rastrillo/perf"
36 "amadan.net/rastrillo/rastrillo/pow"
37)
38
39type application struct {
40 // push is the push transport (Config.Push); nil, no sender runs.
41 push push.Transport
42 home *oficinaid.HTTP
43 installAssets *release.InstallAssets
44 executionEnabled bool
45 chi.Router
46 live *live.Hub
47 origin string
48 auth *auth.Auth
49 store *Store
50 logger *slog.Logger
51 nonces pow.NonceStore
52 background background.Group
53 start sync.Once
54}
55
56func (a *application) startBackground() *background.Group {
57 a.start.Do(func() {
58 a.background.Loop(context.Background(), 15*time.Second, func() {
59 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
60 defer cancel()
61 a.store.forge.API.Expire(ctx)
62 })
63 if a.executionEnabled && a.store.execution != nil {
64 execution := a.store.execution
65 a.background.Loop(context.Background(), 5*time.Second, func() {
66 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
67 defer cancel()
68 if err := execution.Reconcile(ctx); err != nil {
69 a.logger.Error(CopyExecutionReconcile, "err", err)
70 }
71 })
72 }
73 // The Assistant's calls to its providers, until the group stops.
74 calls, stop := context.WithCancel(context.Background())
75 done := a.background.Done()
76 a.background.Go(func() {
77 defer stop()
78 select {
79 case <-done:
80 case <-calls.Done():
81 }
82 })
83 a.background.Go(func() {
84 defer stop()
85 a.store.Chat().ServeRemoteCalls(calls)
86 })
87 // The push sender, only where serving built a transport.
88 if a.push != nil {
89 sender := a.store.Chat().PushSender(a.push)
90 a.background.Go(func() { sender.Serve(calls, a.store.Chat().PushWake(), pushEvery) })
91 }
92 a.background.Loop(context.Background(), time.Minute, func() {
93 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
94 defer cancel()
95 if err := a.store.forge.Sweep(ctx); err != nil {
96 logGitHubSweep(a.logger, err)
97 }
98 if err := a.store.personDevices().Sweep(ctx); err != nil {
99 a.logger.Error(copyAuthSweep, "err", err)
100 }
101 // Housekeeping's minute: quiet hours end, the sweep, the digest.
102 if err := a.store.Chat().HousekeepingTick(ctx); err != nil {
103 a.logger.Error(copyHousekeepingTick, "err", err)
104 }
105 if !a.executionEnabled {
106 return
107 }
108 // Steps waiting for a runner, and the offline rule.
109 if err := a.store.Chat().Place(ctx); err != nil {
110 a.logger.Error(copyChatSweep, "err", err)
111 }
112 })
113 // The instance's own addresses, at start and hourly: the
114 // inventory the guarded client checks.
115 a.background.Go(func() {
116 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
117 defer cancel()
118 if err := a.store.Chat().ScanInstanceAddresses(ctx); err != nil {
119 a.logger.Warn("instance inventory", "err", err)
120 }
121 })
122 a.background.Loop(context.Background(), time.Hour, func() {
123 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
124 defer cancel()
125 if err := a.store.Chat().ScanInstanceAddresses(ctx); err != nil {
126 a.logger.Warn("instance inventory", "err", err)
127 }
128 })
129 // The board of everyone with work under way, when a minute old
130 // (spec 2026-11-26-assistant-abilities §5.3).
131 a.background.Loop(context.Background(), time.Minute, func() {
132 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
133 defer cancel()
134 if err := a.store.Chat().RefreshActiveAbilities(ctx); err != nil {
135 a.logger.Warn("abilities refresh", "err", err)
136 }
137 })
138 a.background.Loop(context.Background(), time.Hour, func() {
139 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
140 defer cancel()
141 if err := a.store.Chat().Sweep(ctx); err != nil {
142 a.logger.Error(copyChatSweep, "err", err)
143 }
144 if err := a.auth.Sweep(time.Now()); err != nil {
145 a.logger.Error(copyAuthSweep, "err", err)
146 }
147 if err := a.nonces.Sweep(time.Now()); err != nil {
148 a.logger.Error(copyNonceSweep, "err", err)
149 }
150 })
151 })
152 return &a.background
153}
154
155// pushEvery is how often the push sender looks for due rows without a
156// wake (retries, another process's writes).
157const pushEvery = 5 * time.Second
158
159// App composes the router and embedded assets used by every harness.
160func App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.ServeMux, error) {
161 r, err := Router(d, cfg, mailer, logger)
162 if err != nil {
163 return nil, err
164 }
165 return Mux(r), nil
166}
167
168func AppWithExecution(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, execution *Execution) (*http.ServeMux, error) {
169 r, err := RouterWithExecution(d, cfg, mailer, logger, execution)
170 if err != nil {
171 return nil, err
172 }
173 return Mux(r), nil
174}
175func RouterWithExecution(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, execution *Execution) (chi.Router, error) {
176 if !cfg.ExecutionEnabled {
177 if execution != nil {
178 return nil, ErrInvalid
179 }
180 return Router(d, cfg, mailer, logger)
181 }
182 if execution == nil || execution.db != d || execution.store.execution != execution {
183 return nil, ErrInvalid
184 }
185 return RouterWithStore(d, cfg, mailer, logger, execution.store)
186}
187
188// Router applies the schema and builds the routes.
189func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.Router, error) {
190 return RouterWithStore(d, cfg, mailer, logger, NewStore(d))
191}
192
193// RouterWithStore composes the verified session routes with a startup-configured store.
194func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger, store *Store) (chi.Router, error) {
195 if store == nil || store.db != d {
196 return nil, ErrInvalid
197 }
198 if err := cfg.validate(); err != nil {
199 return nil, err
200 }
201 if mailer == nil {
202 //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
203 return nil, errors.New(copyMissingMailer)
204 }
205 if !mail.IsConfigured(mailer) && !cfg.AllowLoggedMail {
206 //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
207 return nil, errors.New(copyUnconfiguredMailer)
208 }
209 if logger == nil {
210 logger = slog.Default()
211 }
212 // Framework tables belong in BootSchema, outside the Models diff.
213 migrated, err := migrate.Apply(context.Background(), d, BootSchema)
214 if err != nil {
215 return nil, err
216 }
217 logger.Info(copyMigrate, "applied", migrated.Applied,
218 "skipped", migrated.Skipped, "adopted", migrated.Adopted)
219
220 store.chatExecution, store.chatTestPeople, store.chatOrigin, store.chatAssistantHosts = cfg.ExecutionEnabled, cfg.TestPeople, cfg.Origin, cfg.AssistantHosts
221 // The push outbox is written only where a sender will drain it.
222 store.Chat().SetPush(cfg.Push != nil)
223 store.Chat().SetNotificationActions(cfg.NotificationActions)
224 store.Chat().SetFixed(cfg.Abilities)
225 if err := store.Chat().SetInstancePrefixes(cfg.InstancePrefixes); err != nil {
226 return nil, err
227 }
228 store.Chat().SetMacEngineering(cfg.MacEngineering)
229 // What the Assistant's provider calls could not do, by call id only.
230 store.Chat().SetLogger(logger)
231 if err := store.setupLookups(cfg, logger); err != nil {
232 return nil, err
233 }
234 if cfg.OficinaConnectOrigin != "" {
235 // The Oficina apps, through oficina-connect.
236 if store.oficina, err = oficina.New(cfg.oficinaConfig(), oficinaStore{store}, oficinaSealer{store}); err != nil {
237 //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
238 return nil, errors.New(copyOficinaConfig)
239 }
240 store.Chat().SetOperations(store.assistRegistry(logger))
241 }
242 if err := store.Bootstrap(context.Background(), cfg.Owners); err != nil {
243 return nil, err
244 }
245 // Housekeeping claims a crash left behind are revalidated before the
246 // loop runs again: none silently stays claimed.
247 if released, expired, err := store.Chat().RecoverHousekeeping(context.Background(), false); err != nil {
248 logger.Warn(copyHousekeepingTick, "err", err)
249 } else if released+expired > 0 {
250 logger.Info(copyHousekeepingClaims, "released", released, "expired", expired)
251 }
252 // Needs-you triage over open tasks, once per start: the ledger keys
253 // make it act at most once per situation.
254 if n, err := store.Chat().Retriage(context.Background(), false); err != nil {
255 logger.Warn(copyRetriageFailed, "err", err)
256 } else if n > 0 {
257 logger.Info(copyRetriaged, "acted", n)
258 }
259 // Staging's mockups task, recorded as a change before explorations
260 // existed: an exploration, once ever.
261 if switched, err := store.Chat().ExploreOnce(context.Background(), chat.BarberTask); err != nil {
262 logger.Warn(copyExploreOnceFailed, "err", err)
263 } else if switched {
264 logger.Info(copyExploreOnce, "task", chat.BarberTask)
265 }
266 // Duplicates filed before Equipo tidied them, on every start.
267 if folded, err := store.Chat().TidyDuplicates(context.Background()); err != nil {
268 logger.Warn(copyTidyFailed, "err", err)
269 } else if folded > 0 {
270 logger.Info(copyTidied, "combined", folded)
271 }
272 authentication, err := NewAuth(d, cfg, mailer, store, logger)
273 if err != nil {
274 return nil, err
275 }
276 a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin, push: cfg.Push}
277 if cfg.Home != nil {
278 storeID, e := oficinaid.New(d.Writer(), cfg.Origin, cfg.Home)
279 if e != nil {
280 return nil, e
281 }
282 store.personNativeSession = func(tx *gorm.DB, hash string) (sessions.Session, error) {
283 return storeID.NativeSessionOn(tx.Statement.Context, tx.Statement.ConnPool, hash, store.runnerClock.Now())
284 }
285 a.home = &oficinaid.HTTP{Store: storeID, Auth: authentication, Render: a.renderID}
286 }
287 if verifier, e := validatedAgentConfig(cfg); e != nil {
288 return nil, e
289 } else if verifier != nil {
290 handler, e := newEquipoAgent(store, cfg, a.home.Store, verifier)
291 if e != nil {
292 return nil, e
293 }
294 a.Use(agentRoutes(handler))
295 }
296 // The live hub served the old always-on pages; the conversation now
297 // follows the person event stream (chat-stream.js), so it stays off.
298 a.Use(a.live.Middleware)
299 runner := a.store.runnerRouter()
300 store.personOrigin = cfg.Origin
301 store.personKey = cfg.InstanceKey
302 store.configureGitHub(cfg)
303 store.personCookie = func(r *http.Request) (personapi.PersonPrincipal, error) {
304 id, ok := a.sessionFrom(r)
305 if !ok {
306 return personapi.PersonPrincipal{}, personapi.ErrUnauthenticated
307 }
308 p := personapi.PersonPrincipal{Address: id.Address, SessionEpoch: id.At.Unix()}
309 if string(id.Method) == oficinaid.NativeMethod {
310 c, err := r.Cookie(authentication.SessionCookie())
311 if err != nil {
312 return p, personapi.ErrUnauthenticated
313 }
314 p.SessionHash = sessions.HashToken(c.Value)
315 }
316 return p, nil
317 }
318 person := store.personAPIRouter()
319 a.Use(personapi.Dispatcher(cfg.Origin, runner, person, func(w http.ResponseWriter) { runnerFailure(w, ErrForbidden) }, a.home != nil))
320 a.Mount("/api/v1", person)
321 a.Handle("/releases/*", a.installAssets)
322 a.Get("/install.sh", a.installScript)
323 a.Get("/api/team", teamprobe.Handler(cfg.Home, store.db.G))
324 a.Post("/api/enrolments", a.beginEnrolment)
325 a.Post("/api/enrolments/token", a.exchangeEnrolment)
326 a.Mount("/api/runner/v2", runner)
327 a.Get(wire.StreamPath, a.store.RunnerStreamHandler(a.logger).ServeHTTP)
328 a.Get("/github/connect/manifest", a.githubManifest)
329 a.Get("/github/connect/installation", a.githubInstallation)
330 a.Get(wire.RunnerProtocolPath, func(w http.ResponseWriter, r *http.Request) {
331 w.Header().Set("Content-Type", "application/json")
332 w.Header().Set("Cache-Control", "no-store")
333 _ = json.NewEncoder(w).Encode(wire.RunnerProtocol{Protocol: wire.ProtocolCurrent})
334 })
335 a.Post("/native/preview/exchange", a.exchangePreviewHTTP)
336 a.Get("/native/preview/exchange", a.exchangePreviewHTTP)
337 a.Get("/tasks/{id}/preview", a.previewGrantOrBrowser(a.requireMember(http.HandlerFunc(a.previewPage))).ServeHTTP)
338 a.Post("/tasks/{id}/preview", a.previewGrantOrBrowser(a.requireMember(http.HandlerFunc(a.allowUnsafePreview))).ServeHTTP)
339 a.Post("/auth/begin", a.auth.Begin)
340 a.Get("/auth/callback", a.rememberSignIn(a.auth.Callback))
341 a.Get("/auth/verify", a.rememberSignIn(a.auth.Verify))
342 a.Post("/auth/verify", a.rememberSignIn(a.auth.Verify))
343 // The sign-in door (package door), behind the admission probe.
344 signinDoor := &door.Routes{Look: signinLook, Auth: authentication, DB: d.Writer(), Origin: cfg.Origin, Guard: a.requireMember, Invited: store.MayVerifyInvitation, Signout: a.auth.Signout, Active: store.sessionHandler(nil).Active}
345 if a.home != nil {
346 signinDoor.Issuer, signinDoor.Signout, a.home.SignedIn, signinDoor.Address = cfg.Home.Issuer, a.home.Signout, signinDoor.SignedIn, a.home.Store.LinkedAddress
347 a.home.Routes(a)
348 }
349 signinDoor.Mount(a)
350 if store.oficina != nil {
351 // connect's redirect back: the state, not a session, says whose.
352 a.Get(oficinaCallbackPath, a.oficinaCallback)
353 }
354 ih := a.invitationHandler()
355 a.Get("/invites/{id}", ih.Page)
356 a.Post("/invites/{id}/accept", ih.Accept)
357 a.Group(func(r chi.Router) {
358 r.Use(a.requireMember)
359 r.Get("/auth/devices/{id}", a.deviceBrowser().Page)
360 r.Post("/auth/devices/{id}/approve", a.deviceBrowser().ApproveForm)
361 if a.live != nil {
362 r.Handle("/live", notifications.GuardLive(a.live.Handler(), a.allowNotification))
363 }
364 r.Get("/tasks", a.workTasks)
365 r.Get("/tasks/{id}/move", a.projectPlacement)
366 r.Post("/tasks/{id}/move", a.moveProject)
367 r.Post("/tasks/{id}/notes", a.workThread)
368 r.Post("/tasks/{id}/ask", a.workAsk)
369 r.Post("/conversation/tasks/{id}/retry", a.workTaskAction(true))
370 r.Post("/conversation/tasks/{id}/kind", a.workTaskKind)
371 r.Post("/conversation/tasks/{id}/round", a.workTaskRound)
372 r.Post("/conversation/tasks/{id}/continue-without-copy", a.workTaskContinueCopy)
373 r.Post("/conversation/tasks/{id}/cancel", a.workTaskAction(false))
374 r.Post("/conversation/tasks/{id}/recover", a.workTaskRecover)
375 r.Post("/conversation/tasks/{id}/unsandboxed", a.workTaskUnsandboxed)
376 r.Post("/conversation/tasks/{id}/priority", a.workTaskPriority)
377 r.Post("/conversation/tasks/{id}/run-now", a.workTaskRunNow)
378 r.Post("/conversation/settings/time-zone", a.settingsTimeZone)
379 r.Post("/tasks/{id}/duplicate", a.workDuplicate)
380 r.Post("/projects/{id}/star", a.workStar)
381 r.Post("/projects/add", a.workAddProject)
382 r.Post("/projects/{id}/details", a.workProjectDetails)
383 r.Post("/projects/{id}/names/remove", a.workForgetProjectName)
384 r.Post("/tasks/{id}/uncombine", a.workUncombine)
385 r.Post("/projects/{id}/merge-policy", a.workMergePolicy)
386 r.Post("/conversation/tasks/{id}/merge", a.workTaskMerge)
387 r.Get("/tasks/new", a.taskForm)
388 r.Get("/tasks/{id}", a.taskDetail)
389 r.Get("/tasks/{id}/rendered-change", a.renderedPage)
390 r.Get("/tasks/{id}/rendered-change/{hash}.png", a.renderedImage)
391 r.Get("/tasks/{id}/files/{file}", a.workTaskFile)
392 r.Post("/tasks/{id}/rendered-approval", a.approveRendered)
393 r.Get("/tasks/{id}/questions/{question}", a.questionPage)
394 r.Get("/tasks/{id}/merge", a.mergePage)
395 r.Post("/tasks/{id}/acknowledge-merge", a.acknowledgeMerge)
396 r.Get("/settings/recovery", a.recoveryPage)
397 r.Get("/settings/recovery/release", a.recoveryPage)
398 r.Post("/settings/recovery/release", a.releaseRecovery)
399 r.Get("/", a.preferenceHandler().Landing)
400 a.preferenceHandler().Routes(r)
401 a.teamLinkHandler().Routes(r)
402 a.onboardingHandler().Routes(r)
403 r.Get("/conversation", a.chatPage)
404 r.Post("/conversation", a.chatSend)
405 r.Post("/conversation/attachments", a.chatUpload)
406 r.Delete("/conversation/attachments/{id}", a.chatDeleteUpload)
407 r.Post("/conversation/draft", a.chatDraft)
408 r.Get("/conversation/attachments/{id}", a.chatAttachment(false))
409 r.Get("/conversation/attachments/{id}/preview", a.chatAttachment(true))
410 r.Post("/conversation/cards/{id}/answer", a.chatCardAnswer)
411 r.Post("/conversation/cards/{id}/visibility", a.chatCardVisibility)
412 r.Post("/conversation/cards/{id}/reply", a.chatCardReply)
413 r.Post("/conversation/turns/{id}/stop", a.chatTurnStop)
414 r.Post("/conversation/turns/{id}/retry", a.chatTurnRetry)
415 if store.oficina != nil {
416 r.Get(oficinaStartPath, a.oficinaStart)
417 r.Get(oficinaDonePath, a.oficinaDone)
418 r.Post(oficinaDisconnectPath, a.oficinaDisconnect)
419 }
420 r.Get("/jobs", a.jobsPage)
421 r.Get("/jobs/{id}", a.jobPage)
422 r.Post("/jobs/{id}/messages", a.jobSend)
423 r.Post("/conversation/projects/{id}/remove", a.chatProjectRemove)
424 r.Get("/conversation/notebook", movedTo("/conversation/settings/notebook"))
425 r.Get("/conversation/settings/notebook", a.chatNotebook)
426 r.Get("/usage", a.usage)
427 r.Post("/usage/advice/{id}/act", a.usageAdvice(true))
428 r.Post("/usage/advice/{id}/dismiss", a.usageAdvice(false))
429 r.Get("/housekeeping", a.housekeepingPage)
430 r.Post("/settings/copy/recover", a.recoverCopy)
431 r.Post("/settings/copy/wording", a.editCopyWording)
432 r.Post("/settings/autonomy", a.saveAutonomySetting)
433 r.Get("/conversation/settings/autonomy", a.settingsSectionHandler("autonomy"))
434 r.Post("/settings/copy", a.saveCopySetting)
435 r.Post("/settings/copy/import", a.importCopyReview)
436 r.Get("/conversation/settings/copy", a.settingsSectionHandler("copy"))
437 r.Post("/settings/housekeeping/pause", a.housekeepingPause)
438 r.Post("/settings/housekeeping/quiet", a.housekeepingQuiet)
439 r.Post("/housekeeping/detectors/{id}", a.housekeepingDetector)
440 r.Post("/housekeeping/actions/{id}/undo", a.housekeepingUndo)
441 r.Post("/conversation/notebook/reset", a.chatNotebookReset)
442 r.Post("/conversation/notebook/corrections/{id}/remove", a.removePlacementNote)
443 r.Get("/conversation/settings", a.settingsHub)
444 r.Get("/conversation/settings/thinking", a.settingsSectionHandler("thinking"))
445 r.Get("/conversation/settings/housekeeping", a.settingsSectionHandler("housekeeping"))
446 r.Get("/conversation/settings/places", a.settingsSectionHandler("places"))
447 r.Get("/conversation/connections", movedTo("/conversation/settings/connections"))
448 r.Get("/conversation/settings/connections", a.connectionsView)
449 a.githubRoutes(r)
450 r.Get("/conversation/settings/connections/add", a.connectionsAdd)
451 r.Get("/conversation/settings/machines", a.machinesList)
452 r.Get("/conversation/settings/machines/add", a.machinesAdd)
453 r.Post("/conversation/connections", a.connectionsStart)
454 r.Post("/conversation/connections/{id}/cancel", a.connectionsCancel)
455 r.Post("/conversation/connections/{id}/secret", a.connectionsSecret)
456 r.Post("/conversation/connections/{id}/sign-out", a.connectionsSignOut)
457 r.Post("/conversation/connections/{id}/forget", a.connectionsForget)
458 r.Post("/conversation/connections/{id}/check", a.connectionsCheck)
459 r.Post("/conversation/connections/{id}/model", a.connectionsModel)
460 r.Post("/conversation/connections/{id}/budget", a.connectionsBudget)
461 r.Post("/conversation/connections/{id}/models", a.connectionsModels)
462 r.Post("/conversation/connections/{id}/resume", a.connectionsResume)
463 r.Post("/conversation/connections/{id}/email", a.connectionsEmail)
464 r.Post("/conversation/connections/prefer", a.connectionsPrefer)
465 a.conversationHandler().Routes(r)
466 a.planHandler().Routes(r)
467 r.Post("/tasks/{id}/steps/{key}/selection", a.confirmPlanSelection)
468 r.Get("/work", a.index)
469 r.Get("/nav/rail", a.railFragment)
470 r.Get("/team/{specialist}", a.teamPage)
471 for _, path := range []string{"/needs-you", "/journey", "/connections"} {
472 r.Get(path, a.taskList)
473 }
474 r.Get("/projects", a.workProjects)
475 r.Get("/projects/accounts", a.projects)
476 r.Get("/projects/new", a.projectForm)
477 r.Get("/projects/{id}", a.project)
478 r.Get("/projects/{id}/edit", a.projectForm)
479 r.Get("/people", a.people)
480 r.Get("/invites/new", ih.New)
481 r.Post("/invites", ih.Create)
482 r.Post("/invites/{id}/revoke", ih.Revoke)
483 r.Get("/runners/enrol", a.enrolmentPage)
484 r.Post("/tasks", a.createBug)
485 r.Post("/tasks/{id}/cancel", a.cancelTask)
486 r.Post("/tasks/{id}/old-runner-stopped", a.oldRunnerStopped)
487 r.Post("/tasks/{id}/questions/{question}/answer", a.answerQuestion)
488 r.Post("/runners/enrol", a.approveEnrolment)
489 r.Post("/runners/{id}/revoke", a.revokeRunner)
490 r.Post("/runners/{id}/remove-now", a.removeRunnerNow)
491 r.Post("/projects/{id}/connections", a.saveConnectionChoice)
492 r.Get("/settings/thinking", movedTo("/conversation/settings/thinking"))
493 r.Post("/settings/thinking", a.thinkingSave)
494 r.Get("/settings", a.settings)
495 r.Get("/settings/devices", a.deviceBrowser().Devices)
496 r.Post("/settings/devices/{id}/revoke", a.deviceBrowser().RevokeForm)
497 lh := a.libraryHandler()
498 lh.Routes(r)
499 r.Post("/accounts", a.saveAccount)
500 r.Post("/projects", a.saveProject)
501 r.Post("/projects/{id}", a.saveProject)
502 r.Post("/team/members", a.saveMember)
503 r.Post("/team/budgets", a.saveBudgets)
504 r.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ErrorPage(w, r, http.StatusNotFound, "") }))
505 })
506 return a, nil
507}
508
509// Mux mounts the static files beside the router.
510func Mux(r http.Handler) *http.ServeMux {
511 mux := http.NewServeMux()
512 // The app serves its own static files — the framework never does.
513 // They are embedded (render.go) and fingerprinted: templates link
514 // them via {{asset ...}}, which returns a content-hashed URL the
515 // handler serves cacheable-forever.
516 mux.Handle("GET /static/", assets.Handler())
517 door.Static(mux)
518 mux.Handle("/", r)
519 return mux
520}
521
522// Configure is the one place the serving options are set, so main.go and
523// the perf test cannot drift apart: what the perf lane measures is what
524// production serves.
525//
526// ErrorPage is the page a handler's own error path renders, so a panic
527// and a handled failure look identical. perf.Middleware times every
528// request against 150ms to first byte (500ms for the first one after
529// start, counted from started) and logs what is over budget.
530func Configure(opts *rastrillo.Options, mux *http.ServeMux, started time.Time) {
531 opts.Mux = mux
532 // The root handler owns the auth instance. Start work only when serving
533 // is configured, so Router/App construction alone starts no goroutines.
534 handler, _ := mux.Handler(&http.Request{URL: &url.URL{Path: "/"}})
535 a, ok := handler.(*application)
536 if !ok || a == nil {
537 panic(copyInvalidRoot)
538 }
539 opts.Live = a.live
540 opts.Background = a.startBackground()
541 opts.ErrorPage = ErrorPage
542 var rec perf.Recorder
543 opts.Wrap = perf.Middleware(&rec, perf.Options{Started: started, Logger: opts.Logger})
544}
545