暂无描述

DashboardView.swift 104KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275
  1. //
  2. // DashboardView.swift
  3. // App for Indeed
  4. //
  5. import Cocoa
  6. import QuartzCore
  7. import Security
  8. private enum JobListingCardContext {
  9. case homeSearchResults
  10. case savedJobsPage
  11. }
  12. final class DashboardView: NSView, NSTextFieldDelegate {
  13. /// Indeed.com-inspired neutrals and brand blue (white surfaces, `#2557a7` accent, `#2d2d2d` / `#767676` text, `#d4d2d0` borders).
  14. private enum Theme {
  15. static let brandBlue = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  16. static let pageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  17. static let chromeBackground = NSColor(srgbRed: 247 / 255, green: 247 / 255, blue: 247 / 255, alpha: 1)
  18. static let sidebarBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  19. static let mainHostBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  20. /// Subtitle on the welcome hero: readable blue-gray aligned with brand.
  21. static let welcomeSubtitleText = NSColor(srgbRed: 52 / 255, green: 92 / 255, blue: 142 / 255, alpha: 1)
  22. static let selectionFill = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.12)
  23. static let cardBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  24. static let toggleBackground = NSColor(srgbRed: 232 / 255, green: 232 / 255, blue: 232 / 255, alpha: 1)
  25. static let primaryText = NSColor(srgbRed: 45 / 255, green: 45 / 255, blue: 45 / 255, alpha: 1)
  26. static let secondaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  27. static let tertiaryText = NSColor(srgbRed: 118 / 255, green: 118 / 255, blue: 118 / 255, alpha: 1)
  28. static let border = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  29. /// Job search bar outer stroke (charcoal).
  30. static let searchBarBorder = NSColor(srgbRed: 58 / 255, green: 58 / 255, blue: 58 / 255, alpha: 1)
  31. /// Search bar border on hover (brand-tinted, matches focus affordance elsewhere).
  32. static let searchBarBorderHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.45)
  33. static let proCardFill = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  34. static let proCardBorder = NSColor(srgbRed: 212 / 255, green: 210 / 255, blue: 208 / 255, alpha: 1)
  35. static let proAccent = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  36. static let proCTABackground = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 1)
  37. static let proCTAText = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  38. /// Slightly lighter blue for the top of the search-bar “Find jobs” pill (reads less flat than a solid fill).
  39. static let findJobsCTAHighlight = NSColor(srgbRed: 54 / 255, green: 110 / 255, blue: 198 / 255, alpha: 1)
  40. /// Hover states: darker brand blue, deeper gradient top, stronger tints, and subtle neutral fills used across CTAs, toggles, and the sidebar.
  41. static let brandBlueHover = NSColor(srgbRed: 28 / 255, green: 70 / 255, blue: 140 / 255, alpha: 1)
  42. static let findJobsCTAHighlightHover = NSColor(srgbRed: 44 / 255, green: 94 / 255, blue: 178 / 255, alpha: 1)
  43. static let selectionFillHover = NSColor(srgbRed: 37 / 255, green: 87 / 255, blue: 167 / 255, alpha: 0.2)
  44. static let neutralHoverFill = NSColor(srgbRed: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1)
  45. static let sidebarRowHoverFill = NSColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.04)
  46. static let settingsPageBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  47. static let settingsGroupBackground = NSColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
  48. static let settingsIconBackground = NSColor(srgbRed: 239 / 255, green: 244 / 255, blue: 252 / 255, alpha: 1)
  49. static let settingsDivider = NSColor(srgbRed: 228 / 255, green: 228 / 255, blue: 228 / 255, alpha: 1)
  50. }
  51. /// Multiline `NSTextField` often ignores `alignment` for wrapped runs; explicit paragraph alignment matches the title.
  52. private static func jobListingDescriptionAttributedString(_ plain: String) -> NSAttributedString {
  53. let paragraph = NSMutableParagraphStyle()
  54. paragraph.alignment = .left
  55. paragraph.lineBreakMode = .byWordWrapping
  56. paragraph.baseWritingDirection = .leftToRight
  57. let font = NSFont.systemFont(ofSize: 13, weight: .regular)
  58. return NSAttributedString(string: plain, attributes: [
  59. .font: font,
  60. .foregroundColor: Theme.secondaryText,
  61. .paragraphStyle: paragraph
  62. ])
  63. }
  64. private let contentStack = NSStackView()
  65. private let chromeContainer = NSView()
  66. private let sidebar = NSStackView()
  67. private let mainHost = NSView()
  68. private let mainOverlay = NSStackView()
  69. private let greetingLabel = NSTextField(labelWithString: "")
  70. private let subtitleLabel = NSTextField(labelWithString: "")
  71. private let searchBarShadowHost = NSView()
  72. private let searchCard = HoverableView()
  73. private let jobSearchIcon = NSImageView()
  74. private let jobKeywordsField = NSTextField()
  75. private let findJobsButton = HoverableButton()
  76. private let findJobsCTAHost = NSView()
  77. private let findJobsCTAChrome = HoverableView()
  78. private var findJobsCTAGradientLayer: CAGradientLayer?
  79. private let chatStatusStack = NSStackView()
  80. private let chatStatusIcon = NSImageView()
  81. private let chatStatusLabel = NSTextField(labelWithString: "Opening the vault...")
  82. private let chatScrollView = NSScrollView()
  83. private let chatDocumentView = JobListingsDocumentView()
  84. private let chatStack = NSStackView()
  85. /// Shown when a sidebar item other than Home is selected.
  86. private let nonHomeHost = NSView()
  87. private let nonHomeGenericContainer = NSView()
  88. private let nonHomeTitleLabel = NSTextField(labelWithString: "")
  89. private let nonHomeSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  90. private let savedJobsPageContainer = NSView()
  91. private let savedJobsPageTitleLabel = NSTextField(labelWithString: "Saved Jobs")
  92. private let savedJobsPageSubtitleLabel = NSTextField(wrappingLabelWithString: "")
  93. private let savedJobsScrollView = NSScrollView()
  94. private let savedJobsDocumentView = JobListingsDocumentView()
  95. private let savedJobsStack = NSStackView()
  96. private let settingsPageContainer = NSView()
  97. private let themeControl = NSSegmentedControl(labels: ["System", "Light", "Dark"], trackingMode: .selectOne, target: nil, action: nil)
  98. private var currentSidebarItems: [SidebarItem] = []
  99. private var selectedSidebarIndex: Int = 0
  100. /// All jobs that have been shown in the current chat session, oldest first. Used to deduplicate continuation searches so "show more" doesn't re-display the same listings.
  101. private var lastSearchResults: [JobListing] = []
  102. /// Most recently saved jobs appear first; persisted across launches.
  103. private var savedJobOrder: [JobListing] = []
  104. private var chatMessages: [ChatMessage] = []
  105. private var isAwaitingResponse = false
  106. private let jobSearchService = OpenAIJobSearchService()
  107. override init(frame frameRect: NSRect) {
  108. super.init(frame: frameRect)
  109. setupLayout()
  110. }
  111. required init?(coder: NSCoder) {
  112. super.init(coder: coder)
  113. setupLayout()
  114. }
  115. override func layout() {
  116. super.layout()
  117. updateSearchBarShadowPath()
  118. findJobsCTAGradientLayer?.frame = findJobsCTAChrome.bounds
  119. updateFindJobsCTAShadowPath()
  120. updateJobListingDescriptionWidths()
  121. updateChatBubbleWidths()
  122. }
  123. func render(_ data: DashboardData) {
  124. greetingLabel.stringValue = "Welcome"
  125. subtitleLabel.stringValue = data.subtitle
  126. currentSidebarItems = data.sidebarItems
  127. if selectedSidebarIndex >= currentSidebarItems.count {
  128. selectedSidebarIndex = max(0, currentSidebarItems.count - 1)
  129. }
  130. configureSidebar()
  131. savedJobOrder = Self.normalizedSavedJobs(SavedJobsStore.load())
  132. resetChatState()
  133. updateMainContentVisibility()
  134. }
  135. private func setupLayout() {
  136. wantsLayer = true
  137. layer?.backgroundColor = Theme.pageBackground.cgColor
  138. contentStack.orientation = .horizontal
  139. contentStack.spacing = 10
  140. contentStack.distribution = .fill
  141. contentStack.translatesAutoresizingMaskIntoConstraints = false
  142. contentStack.alignment = .height
  143. // Tighter chrome insets so panels sit closer to the window edges (especially leading / top under the title bar).
  144. contentStack.edgeInsets = NSEdgeInsets(top: 10, left: 12, bottom: 20, right: 20)
  145. chromeContainer.translatesAutoresizingMaskIntoConstraints = false
  146. chromeContainer.wantsLayer = true
  147. chromeContainer.layer?.backgroundColor = Theme.chromeBackground.cgColor
  148. chromeContainer.layer?.cornerRadius = 0
  149. addSubview(chromeContainer)
  150. chromeContainer.addSubview(contentStack)
  151. sidebar.orientation = .vertical
  152. sidebar.spacing = 10
  153. sidebar.distribution = .fill
  154. sidebar.alignment = .leading
  155. sidebar.wantsLayer = true
  156. sidebar.layer?.backgroundColor = Theme.sidebarBackground.cgColor
  157. sidebar.layer?.cornerRadius = 16
  158. sidebar.edgeInsets = NSEdgeInsets(top: 16, left: 12, bottom: 16, right: 12)
  159. sidebar.translatesAutoresizingMaskIntoConstraints = false
  160. mainHost.translatesAutoresizingMaskIntoConstraints = false
  161. mainHost.wantsLayer = true
  162. mainHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  163. mainHost.layer?.cornerRadius = 16
  164. mainHost.layer?.masksToBounds = true
  165. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  166. mainHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  167. mainHost.addSubview(mainOverlay)
  168. configureNonHomePlaceholder()
  169. mainHost.addSubview(nonHomeHost)
  170. mainOverlay.orientation = .vertical
  171. mainOverlay.spacing = 0
  172. mainOverlay.alignment = .centerX
  173. mainOverlay.distribution = .fill
  174. mainOverlay.translatesAutoresizingMaskIntoConstraints = false
  175. mainOverlay.setContentHuggingPriority(.defaultLow, for: .vertical)
  176. greetingLabel.font = .systemFont(ofSize: 32, weight: .bold)
  177. greetingLabel.textColor = Theme.brandBlue
  178. greetingLabel.alignment = .center
  179. greetingLabel.maximumNumberOfLines = 1
  180. subtitleLabel.font = .systemFont(ofSize: 15, weight: .regular)
  181. subtitleLabel.textColor = Theme.welcomeSubtitleText
  182. subtitleLabel.alignment = .center
  183. subtitleLabel.maximumNumberOfLines = 2
  184. let topInset = NSView()
  185. topInset.translatesAutoresizingMaskIntoConstraints = false
  186. topInset.heightAnchor.constraint(equalToConstant: 18).isActive = true
  187. configureSearchBar()
  188. configureChatViews()
  189. let titleBlock = NSStackView(views: [greetingLabel, subtitleLabel])
  190. titleBlock.orientation = .vertical
  191. titleBlock.spacing = 10
  192. titleBlock.alignment = .centerX
  193. let midSpacer = NSView()
  194. midSpacer.translatesAutoresizingMaskIntoConstraints = false
  195. midSpacer.heightAnchor.constraint(equalToConstant: 18).isActive = true
  196. let chatTopSpacer = NSView()
  197. chatTopSpacer.translatesAutoresizingMaskIntoConstraints = false
  198. chatTopSpacer.heightAnchor.constraint(equalToConstant: 14).isActive = true
  199. let chatBottomSpacer = NSView()
  200. chatBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  201. chatBottomSpacer.heightAnchor.constraint(equalToConstant: 14).isActive = true
  202. mainOverlay.addArrangedSubview(topInset)
  203. mainOverlay.addArrangedSubview(titleBlock)
  204. mainOverlay.addArrangedSubview(midSpacer)
  205. mainOverlay.addArrangedSubview(chatStatusStack)
  206. mainOverlay.addArrangedSubview(chatTopSpacer)
  207. mainOverlay.addArrangedSubview(chatScrollView)
  208. mainOverlay.addArrangedSubview(chatBottomSpacer)
  209. mainOverlay.addArrangedSubview(searchBarShadowHost)
  210. contentStack.addArrangedSubview(sidebar)
  211. contentStack.addArrangedSubview(mainHost)
  212. NSLayoutConstraint.activate([
  213. chromeContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
  214. chromeContainer.trailingAnchor.constraint(equalTo: trailingAnchor),
  215. chromeContainer.topAnchor.constraint(equalTo: topAnchor),
  216. chromeContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
  217. contentStack.leadingAnchor.constraint(equalTo: chromeContainer.leadingAnchor),
  218. contentStack.trailingAnchor.constraint(equalTo: chromeContainer.trailingAnchor),
  219. contentStack.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
  220. contentStack.bottomAnchor.constraint(equalTo: chromeContainer.bottomAnchor),
  221. sidebar.widthAnchor.constraint(equalToConstant: 218),
  222. mainHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 720),
  223. mainOverlay.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  224. mainOverlay.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  225. mainOverlay.topAnchor.constraint(equalTo: mainHost.topAnchor),
  226. mainOverlay.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  227. nonHomeHost.leadingAnchor.constraint(equalTo: mainHost.leadingAnchor),
  228. nonHomeHost.trailingAnchor.constraint(equalTo: mainHost.trailingAnchor),
  229. nonHomeHost.topAnchor.constraint(equalTo: mainHost.topAnchor),
  230. nonHomeHost.bottomAnchor.constraint(equalTo: mainHost.bottomAnchor, constant: -24),
  231. searchBarShadowHost.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  232. chatStatusStack.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  233. chatScrollView.widthAnchor.constraint(equalTo: mainOverlay.widthAnchor, multiplier: 0.92),
  234. greetingLabel.leadingAnchor.constraint(equalTo: mainOverlay.leadingAnchor, constant: 16),
  235. greetingLabel.trailingAnchor.constraint(equalTo: mainOverlay.trailingAnchor, constant: -16),
  236. subtitleLabel.leadingAnchor.constraint(equalTo: greetingLabel.leadingAnchor),
  237. subtitleLabel.trailingAnchor.constraint(equalTo: greetingLabel.trailingAnchor)
  238. ])
  239. }
  240. private func configureChatViews() {
  241. chatStatusStack.orientation = .vertical
  242. chatStatusStack.spacing = 6
  243. chatStatusStack.alignment = .centerX
  244. chatStatusStack.translatesAutoresizingMaskIntoConstraints = false
  245. chatStatusIcon.translatesAutoresizingMaskIntoConstraints = false
  246. chatStatusIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 36, weight: .regular)
  247. chatStatusIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "Assistant status")
  248. chatStatusIcon.contentTintColor = Theme.brandBlue
  249. chatStatusLabel.font = .systemFont(ofSize: 20, weight: .semibold)
  250. chatStatusLabel.textColor = Theme.primaryText
  251. chatStatusLabel.alignment = .center
  252. chatStatusLabel.maximumNumberOfLines = 1
  253. chatStatusStack.addArrangedSubview(chatStatusIcon)
  254. chatStatusStack.addArrangedSubview(chatStatusLabel)
  255. chatDocumentView.translatesAutoresizingMaskIntoConstraints = false
  256. chatStack.orientation = .vertical
  257. chatStack.spacing = 18
  258. chatStack.alignment = .width
  259. chatStack.distribution = .fill
  260. chatStack.translatesAutoresizingMaskIntoConstraints = false
  261. chatDocumentView.addSubview(chatStack)
  262. NSLayoutConstraint.activate([
  263. chatStack.leadingAnchor.constraint(equalTo: chatDocumentView.leadingAnchor, constant: 4),
  264. chatStack.trailingAnchor.constraint(equalTo: chatDocumentView.trailingAnchor, constant: -4),
  265. chatStack.topAnchor.constraint(equalTo: chatDocumentView.topAnchor, constant: 8),
  266. chatStack.bottomAnchor.constraint(equalTo: chatDocumentView.bottomAnchor, constant: -8)
  267. ])
  268. chatScrollView.translatesAutoresizingMaskIntoConstraints = false
  269. chatScrollView.hasVerticalScroller = true
  270. chatScrollView.hasHorizontalScroller = false
  271. chatScrollView.autohidesScrollers = true
  272. chatScrollView.drawsBackground = false
  273. chatScrollView.borderType = .noBorder
  274. chatScrollView.documentView = chatDocumentView
  275. chatScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  276. chatScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  277. chatScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 320).isActive = true
  278. }
  279. private func updateJobListingDescriptionWidths() {
  280. updateDescriptionColumnWidths(in: savedJobsStack, containerWidth: savedJobsDocumentView.bounds.width)
  281. walkChatJobStacks { stack in
  282. updateDescriptionColumnWidths(in: stack, containerWidth: stack.bounds.width)
  283. }
  284. }
  285. private func walkChatJobStacks(_ visitor: (ChatJobsStackView) -> Void) {
  286. func walk(_ view: NSView) {
  287. if let stack = view as? ChatJobsStackView {
  288. visitor(stack)
  289. }
  290. for sub in view.subviews { walk(sub) }
  291. }
  292. walk(chatStack)
  293. }
  294. /// Chat bubble text fields are wrapping labels whose `preferredMaxLayoutWidth` needs to track the available row width so long strings reflow correctly when the window resizes.
  295. private func updateChatBubbleWidths() {
  296. func walk(_ view: NSView) {
  297. if let label = view as? ChatBubbleLabel,
  298. let bubble = label.superview, bubble.bounds.width > 1 {
  299. let target = max(40, bubble.bounds.width - 28)
  300. if abs(label.preferredMaxLayoutWidth - target) > 0.5 {
  301. label.preferredMaxLayoutWidth = target
  302. label.invalidateIntrinsicContentSize()
  303. }
  304. }
  305. for sub in view.subviews { walk(sub) }
  306. }
  307. walk(chatStack)
  308. }
  309. private func updateDescriptionColumnWidths(in stack: NSStackView, containerWidth: CGFloat) {
  310. guard containerWidth > 1 else { return }
  311. // Matches `contentColumn` insets on the card (16 leading + 16 trailing). The description spans the full row below the buttons, so never subtract a “button strip” here — a too-narrow `preferredMaxLayoutWidth` inside a wider field makes wrapped `NSTextField` text lay out like a trailing-aligned band after resizes.
  312. let contentHorizontalInset: CGFloat = 32
  313. var didChange = false
  314. for card in stack.arrangedSubviews {
  315. guard let desc = card.viewWithTag(502) as? NSTextField else { continue }
  316. let cardWidth = card.bounds.width > 1 ? card.bounds.width : containerWidth
  317. let fallbackColumn = max(1, cardWidth - contentHorizontalInset)
  318. let columnWidth: CGFloat
  319. if desc.bounds.width > 1 {
  320. columnWidth = desc.bounds.width
  321. } else if let column = desc.superview, column.bounds.width > 1 {
  322. columnWidth = column.bounds.width
  323. } else {
  324. columnWidth = fallbackColumn
  325. }
  326. if abs(desc.preferredMaxLayoutWidth - columnWidth) > 0.5 {
  327. desc.preferredMaxLayoutWidth = columnWidth
  328. desc.invalidateIntrinsicContentSize()
  329. didChange = true
  330. }
  331. }
  332. if didChange {
  333. stack.needsLayout = true
  334. }
  335. }
  336. private static func normalizedSavedJobs(_ jobs: [JobListing]) -> [JobListing] {
  337. var seen = Set<JobListing>()
  338. var out: [JobListing] = []
  339. for job in jobs where seen.insert(job).inserted {
  340. out.append(job)
  341. }
  342. return out
  343. }
  344. private func isJobSaved(_ job: JobListing) -> Bool {
  345. savedJobOrder.contains(job)
  346. }
  347. private func persistSavedJobs() {
  348. SavedJobsStore.save(savedJobOrder)
  349. }
  350. private func applySavedState(_ saved: Bool, for job: JobListing) {
  351. if saved {
  352. savedJobOrder.removeAll { $0 == job }
  353. savedJobOrder.insert(job, at: 0)
  354. } else {
  355. savedJobOrder.removeAll { $0 == job }
  356. }
  357. persistSavedJobs()
  358. }
  359. private func makeJobListingCard(_ job: JobListing, context: JobListingCardContext) -> NSView {
  360. let card = NSView()
  361. card.translatesAutoresizingMaskIntoConstraints = false
  362. card.wantsLayer = true
  363. card.layer?.backgroundColor = Theme.cardBackground.cgColor
  364. card.layer?.cornerRadius = 12
  365. card.layer?.borderWidth = 1
  366. card.layer?.borderColor = Theme.border.cgColor
  367. card.layer?.masksToBounds = true
  368. let titleField = NSTextField(labelWithString: job.title)
  369. titleField.font = .systemFont(ofSize: 16, weight: .semibold)
  370. titleField.textColor = Theme.primaryText
  371. titleField.maximumNumberOfLines = 2
  372. titleField.lineBreakMode = .byWordWrapping
  373. titleField.alignment = .left
  374. titleField.translatesAutoresizingMaskIntoConstraints = false
  375. let descriptionField = NSTextField(wrappingLabelWithString: job.description)
  376. descriptionField.font = .systemFont(ofSize: 13, weight: .regular)
  377. descriptionField.textColor = Theme.secondaryText
  378. descriptionField.maximumNumberOfLines = 0
  379. descriptionField.alignment = .left
  380. descriptionField.lineBreakMode = .byWordWrapping
  381. descriptionField.baseWritingDirection = .leftToRight
  382. descriptionField.attributedStringValue = Self.jobListingDescriptionAttributedString(job.description)
  383. if let cell = descriptionField.cell as? NSTextFieldCell {
  384. cell.alignment = .left
  385. cell.wraps = true
  386. }
  387. descriptionField.setContentHuggingPriority(.defaultLow, for: .horizontal)
  388. descriptionField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  389. descriptionField.tag = 502
  390. descriptionField.translatesAutoresizingMaskIntoConstraints = false
  391. let applyButton = JobPayloadButton(title: "Apply", target: self, action: #selector(didTapJobApply(_:)))
  392. applyButton.jobPayload = job
  393. applyButton.cardContext = context
  394. applyButton.isBordered = false
  395. applyButton.bezelStyle = .rounded
  396. applyButton.font = .systemFont(ofSize: 13, weight: .semibold)
  397. applyButton.wantsLayer = true
  398. applyButton.layer?.cornerRadius = 6
  399. applyButton.layer?.backgroundColor = Theme.brandBlue.cgColor
  400. applyButton.contentTintColor = Theme.proCTAText
  401. applyButton.focusRingType = .none
  402. applyButton.pointerCursor = true
  403. applyButton.hoverHandler = { [weak applyButton] hovering in
  404. applyButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.brandBlue).cgColor
  405. }
  406. applyButton.setContentHuggingPriority(.required, for: .horizontal)
  407. applyButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  408. let savedOn = isJobSaved(job)
  409. let savedButton = JobPayloadButton(title: savedOn ? "Saved" : "Save", target: self, action: #selector(didTapJobSaved(_:)))
  410. savedButton.jobPayload = job
  411. savedButton.cardContext = context
  412. savedButton.setButtonType(.toggle)
  413. savedButton.isBordered = false
  414. savedButton.bezelStyle = .rounded
  415. savedButton.font = .systemFont(ofSize: 13, weight: .semibold)
  416. savedButton.focusRingType = .none
  417. savedButton.state = savedOn ? .on : .off
  418. savedButton.pointerCursor = true
  419. savedButton.hoverHandler = { [weak self, weak savedButton] _ in
  420. guard let savedButton = savedButton else { return }
  421. self?.styleJobSavedButton(savedButton)
  422. }
  423. styleJobSavedButton(savedButton)
  424. savedButton.setContentHuggingPriority(.required, for: .horizontal)
  425. savedButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  426. let dismissButton = JobPayloadButton()
  427. dismissButton.jobPayload = job
  428. dismissButton.cardContext = context
  429. dismissButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Dismiss")
  430. dismissButton.imagePosition = .imageOnly
  431. dismissButton.imageScaling = .scaleProportionallyDown
  432. dismissButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 11, weight: .semibold)
  433. dismissButton.isBordered = false
  434. dismissButton.bezelStyle = .rounded
  435. dismissButton.contentTintColor = Theme.secondaryText
  436. dismissButton.target = self
  437. dismissButton.action = #selector(didTapJobDismiss(_:))
  438. dismissButton.toolTip = context == .savedJobsPage ? "Remove from saved" : "Dismiss"
  439. dismissButton.focusRingType = .none
  440. dismissButton.wantsLayer = true
  441. dismissButton.layer?.cornerRadius = 14
  442. dismissButton.layer?.backgroundColor = NSColor.clear.cgColor
  443. dismissButton.pointerCursor = true
  444. dismissButton.hoverHandler = { [weak dismissButton] hovering in
  445. dismissButton?.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : NSColor.clear).cgColor
  446. dismissButton?.contentTintColor = hovering ? Theme.primaryText : Theme.secondaryText
  447. }
  448. dismissButton.setContentHuggingPriority(.required, for: .horizontal)
  449. let buttonRow = NSStackView(views: [applyButton, savedButton, dismissButton])
  450. buttonRow.orientation = .horizontal
  451. buttonRow.spacing = 8
  452. buttonRow.alignment = .centerY
  453. buttonRow.translatesAutoresizingMaskIntoConstraints = false
  454. buttonRow.setContentHuggingPriority(.required, for: .horizontal)
  455. buttonRow.setContentCompressionResistancePriority(.required, for: .horizontal)
  456. // Title hugs the leading edge; a low–hugging-priority spacer absorbs remaining width so buttons stay trailing.
  457. titleField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  458. titleField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  459. let titleRowSpacer = NSView()
  460. titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  461. titleRowSpacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  462. titleRowSpacer.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  463. let titleAndActionsRow = NSStackView(views: [titleField, titleRowSpacer, buttonRow])
  464. titleAndActionsRow.orientation = .horizontal
  465. titleAndActionsRow.spacing = 0
  466. titleAndActionsRow.setCustomSpacing(14, after: titleRowSpacer)
  467. titleAndActionsRow.alignment = .centerY
  468. titleAndActionsRow.distribution = .fill
  469. titleAndActionsRow.userInterfaceLayoutDirection = .leftToRight
  470. titleAndActionsRow.translatesAutoresizingMaskIntoConstraints = false
  471. let contentColumn = NSStackView(views: [titleAndActionsRow, descriptionField])
  472. contentColumn.orientation = .vertical
  473. contentColumn.spacing = 6
  474. contentColumn.alignment = .width
  475. contentColumn.translatesAutoresizingMaskIntoConstraints = false
  476. card.addSubview(contentColumn)
  477. NSLayoutConstraint.activate([
  478. contentColumn.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 16),
  479. contentColumn.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -16),
  480. contentColumn.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  481. contentColumn.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14),
  482. applyButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  483. applyButton.heightAnchor.constraint(equalToConstant: 28),
  484. savedButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 72),
  485. savedButton.heightAnchor.constraint(equalToConstant: 28),
  486. dismissButton.widthAnchor.constraint(equalToConstant: 28),
  487. dismissButton.heightAnchor.constraint(equalToConstant: 28),
  488. descriptionField.widthAnchor.constraint(equalTo: contentColumn.widthAnchor)
  489. ])
  490. return card
  491. }
  492. private func styleJobSavedButton(_ button: NSButton) {
  493. button.wantsLayer = true
  494. button.layer?.cornerRadius = 6
  495. let on = button.state == .on
  496. let hovering = (button as? HoverableButton)?.isHovering ?? false
  497. if on {
  498. button.layer?.backgroundColor = (hovering ? Theme.selectionFillHover : Theme.selectionFill).cgColor
  499. button.layer?.borderWidth = 1
  500. button.layer?.borderColor = Theme.brandBlue.cgColor
  501. button.contentTintColor = Theme.brandBlue
  502. } else {
  503. button.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  504. button.layer?.borderWidth = 1
  505. button.layer?.borderColor = Theme.border.cgColor
  506. button.contentTintColor = Theme.primaryText
  507. }
  508. }
  509. @objc private func didTapJobApply(_ sender: NSButton) {
  510. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  511. if let rawURL = job.url, let url = URL(string: rawURL), !rawURL.isEmpty {
  512. NSWorkspace.shared.open(url)
  513. return
  514. }
  515. let allowed = CharacterSet.urlQueryAllowed
  516. let q = job.title.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
  517. guard let url = URL(string: "https://www.indeed.com/jobs?q=\(q)") else { return }
  518. NSWorkspace.shared.open(url)
  519. }
  520. @objc private func didTapJobSaved(_ sender: NSButton) {
  521. guard let job = (sender as? JobPayloadButton)?.jobPayload else { return }
  522. let willSave = !isJobSaved(job)
  523. applySavedState(willSave, for: job)
  524. sender.state = willSave ? .on : .off
  525. sender.title = willSave ? "Saved" : "Save"
  526. styleJobSavedButton(sender)
  527. if isSavedJobsSidebarIndex(selectedSidebarIndex) {
  528. reloadSavedJobsListings()
  529. }
  530. }
  531. @objc private func didTapJobDismiss(_ sender: NSButton) {
  532. guard let button = sender as? JobPayloadButton, let job = button.jobPayload else { return }
  533. switch button.cardContext {
  534. case .homeSearchResults:
  535. removeJobCardFromChat(originating: button, job: job)
  536. case .savedJobsPage:
  537. applySavedState(false, for: job)
  538. reloadSavedJobsListings()
  539. }
  540. }
  541. /// Walks up from a dismiss button until it finds the enclosing chat job stack, then removes only the card that owns the button. Other chat history (older searches, the assistant summary text) is untouched.
  542. private func removeJobCardFromChat(originating button: NSView, job: JobListing) {
  543. var node: NSView? = button
  544. var card: NSView?
  545. var stack: ChatJobsStackView?
  546. while let v = node {
  547. if let parent = v.superview as? ChatJobsStackView {
  548. card = v
  549. stack = parent
  550. break
  551. }
  552. node = v.superview
  553. }
  554. guard let card, let stack else { return }
  555. stack.removeArrangedSubview(card)
  556. card.removeFromSuperview()
  557. lastSearchResults.removeAll { $0 == job }
  558. }
  559. private func configureSearchBar() {
  560. let pillCorner: CGFloat = 27
  561. let barHeight: CGFloat = 54
  562. searchBarShadowHost.translatesAutoresizingMaskIntoConstraints = false
  563. searchBarShadowHost.wantsLayer = true
  564. searchBarShadowHost.layer?.masksToBounds = false
  565. searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(0.18).cgColor
  566. searchBarShadowHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  567. searchBarShadowHost.layer?.shadowRadius = 10
  568. searchBarShadowHost.layer?.shadowOpacity = 1
  569. searchBarShadowHost.setContentHuggingPriority(.defaultHigh, for: .vertical)
  570. searchCard.translatesAutoresizingMaskIntoConstraints = false
  571. searchCard.wantsLayer = true
  572. searchCard.layer?.backgroundColor = Theme.cardBackground.cgColor
  573. searchCard.layer?.cornerRadius = pillCorner
  574. searchCard.layer?.borderWidth = 1
  575. searchCard.layer?.borderColor = Theme.searchBarBorder.cgColor
  576. searchCard.layer?.masksToBounds = true
  577. searchCard.hoverHandler = { [weak self] hovering in
  578. guard let self else { return }
  579. CATransaction.begin()
  580. CATransaction.setAnimationDuration(0.15)
  581. self.searchCard.layer?.backgroundColor = (hovering ? Theme.neutralHoverFill : Theme.cardBackground).cgColor
  582. self.searchCard.layer?.borderColor = (hovering ? Theme.searchBarBorderHover : Theme.searchBarBorder).cgColor
  583. self.searchBarShadowHost.layer?.shadowColor = NSColor.black.withAlphaComponent(hovering ? 0.24 : 0.18).cgColor
  584. self.searchBarShadowHost.layer?.shadowRadius = hovering ? 12 : 10
  585. CATransaction.commit()
  586. }
  587. searchBarShadowHost.addSubview(searchCard)
  588. func configureField(_ field: NSTextField, placeholder: String) {
  589. field.translatesAutoresizingMaskIntoConstraints = false
  590. field.isBordered = false
  591. field.drawsBackground = false
  592. field.focusRingType = .none
  593. field.font = .systemFont(ofSize: 14, weight: .regular)
  594. field.textColor = Theme.primaryText
  595. field.delegate = self
  596. field.placeholderAttributedString = NSAttributedString(
  597. string: placeholder,
  598. attributes: [
  599. .foregroundColor: Theme.secondaryText,
  600. .font: NSFont.systemFont(ofSize: 14, weight: .regular)
  601. ]
  602. )
  603. field.cell?.usesSingleLineMode = true
  604. field.cell?.wraps = false
  605. field.cell?.isScrollable = true
  606. field.target = self
  607. field.action = #selector(didSubmitSearch)
  608. }
  609. jobSearchIcon.translatesAutoresizingMaskIntoConstraints = false
  610. jobSearchIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .medium)
  611. jobSearchIcon.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: "Job search")
  612. jobSearchIcon.contentTintColor = Theme.primaryText
  613. configureField(jobKeywordsField, placeholder: "Ask for roles, skills, salary, or job descriptions...")
  614. let ctaHeight: CGFloat = 42
  615. let ctaCorner = ctaHeight / 2
  616. findJobsCTAHost.translatesAutoresizingMaskIntoConstraints = false
  617. findJobsCTAHost.wantsLayer = true
  618. findJobsCTAHost.layer?.masksToBounds = false
  619. findJobsCTAHost.layer?.shadowColor = NSColor.black.cgColor
  620. findJobsCTAHost.layer?.shadowOpacity = 0.16
  621. findJobsCTAHost.layer?.shadowOffset = CGSize(width: 0, height: 2)
  622. findJobsCTAHost.layer?.shadowRadius = 6
  623. findJobsCTAChrome.translatesAutoresizingMaskIntoConstraints = false
  624. findJobsCTAChrome.wantsLayer = true
  625. findJobsCTAChrome.layer?.masksToBounds = true
  626. findJobsCTAChrome.layer?.cornerRadius = ctaCorner
  627. if #available(macOS 11.0, *) {
  628. findJobsCTAChrome.layer?.cornerCurve = .continuous
  629. }
  630. let gradient = CAGradientLayer()
  631. gradient.colors = [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  632. gradient.startPoint = CGPoint(x: 0.5, y: 1)
  633. gradient.endPoint = CGPoint(x: 0.5, y: 0)
  634. findJobsCTAChrome.layer?.addSublayer(gradient)
  635. findJobsCTAGradientLayer = gradient
  636. // Tracks hover over the full pill (the button only covers an inset area), so the gradient darkens whenever the mouse is anywhere over the CTA.
  637. findJobsCTAChrome.pointerCursor = true
  638. findJobsCTAChrome.hoverHandler = { [weak self] hovering in
  639. guard let layer = self?.findJobsCTAGradientLayer else { return }
  640. CATransaction.begin()
  641. CATransaction.setAnimationDuration(0.15)
  642. layer.colors = hovering
  643. ? [Theme.findJobsCTAHighlightHover.cgColor, Theme.brandBlueHover.cgColor]
  644. : [Theme.findJobsCTAHighlight.cgColor, Theme.brandBlue.cgColor]
  645. CATransaction.commit()
  646. }
  647. findJobsButton.translatesAutoresizingMaskIntoConstraints = false
  648. findJobsButton.title = ""
  649. findJobsButton.attributedTitle = NSAttributedString(
  650. string: "Send",
  651. attributes: [
  652. .font: NSFont.systemFont(ofSize: 14, weight: .semibold),
  653. .foregroundColor: Theme.proCTAText,
  654. .kern: 0.35
  655. ]
  656. )
  657. findJobsButton.isBordered = false
  658. findJobsButton.bezelStyle = .rounded
  659. findJobsButton.wantsLayer = true
  660. findJobsButton.layer?.backgroundColor = NSColor.clear.cgColor
  661. findJobsButton.focusRingType = .none
  662. findJobsButton.target = self
  663. findJobsButton.action = #selector(didSubmitSearch)
  664. findJobsButton.setContentHuggingPriority(.required, for: .horizontal)
  665. findJobsButton.setContentCompressionResistancePriority(.required, for: .horizontal)
  666. findJobsCTAHost.addSubview(findJobsCTAChrome)
  667. findJobsCTAHost.addSubview(findJobsButton)
  668. NSLayoutConstraint.activate([
  669. findJobsCTAChrome.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor),
  670. findJobsCTAChrome.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor),
  671. findJobsCTAChrome.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  672. findJobsCTAChrome.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor),
  673. findJobsButton.leadingAnchor.constraint(equalTo: findJobsCTAHost.leadingAnchor, constant: 14),
  674. findJobsButton.trailingAnchor.constraint(equalTo: findJobsCTAHost.trailingAnchor, constant: -14),
  675. findJobsButton.topAnchor.constraint(equalTo: findJobsCTAHost.topAnchor),
  676. findJobsButton.bottomAnchor.constraint(equalTo: findJobsCTAHost.bottomAnchor)
  677. ])
  678. let keywordsStack = NSStackView(views: [jobSearchIcon, jobKeywordsField])
  679. keywordsStack.orientation = .horizontal
  680. keywordsStack.spacing = 10
  681. keywordsStack.alignment = .centerY
  682. keywordsStack.translatesAutoresizingMaskIntoConstraints = false
  683. keywordsStack.edgeInsets = NSEdgeInsets(top: 0, left: 18, bottom: 0, right: 10)
  684. keywordsStack.setContentHuggingPriority(.defaultLow, for: .horizontal)
  685. let row = NSStackView(views: [keywordsStack, findJobsCTAHost])
  686. row.orientation = .horizontal
  687. row.spacing = 0
  688. row.alignment = .centerY
  689. row.distribution = .fill
  690. row.translatesAutoresizingMaskIntoConstraints = false
  691. row.edgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 7)
  692. searchCard.addSubview(row)
  693. NSLayoutConstraint.activate([
  694. searchCard.leadingAnchor.constraint(equalTo: searchBarShadowHost.leadingAnchor),
  695. searchCard.trailingAnchor.constraint(equalTo: searchBarShadowHost.trailingAnchor),
  696. searchCard.topAnchor.constraint(equalTo: searchBarShadowHost.topAnchor),
  697. searchCard.bottomAnchor.constraint(equalTo: searchBarShadowHost.bottomAnchor),
  698. searchBarShadowHost.heightAnchor.constraint(equalToConstant: barHeight),
  699. row.leadingAnchor.constraint(equalTo: searchCard.leadingAnchor),
  700. row.trailingAnchor.constraint(equalTo: searchCard.trailingAnchor),
  701. row.topAnchor.constraint(equalTo: searchCard.topAnchor),
  702. row.bottomAnchor.constraint(equalTo: searchCard.bottomAnchor),
  703. jobSearchIcon.widthAnchor.constraint(equalToConstant: 18),
  704. jobSearchIcon.heightAnchor.constraint(equalToConstant: 18),
  705. findJobsCTAHost.heightAnchor.constraint(equalToConstant: ctaHeight),
  706. findJobsCTAHost.widthAnchor.constraint(greaterThanOrEqualToConstant: 112)
  707. ])
  708. searchCard.hoverHandler = nil
  709. }
  710. private func updateFindJobsCTAShadowPath() {
  711. guard findJobsCTAHost.bounds.width > 0, findJobsCTAHost.bounds.height > 0 else { return }
  712. let r = findJobsCTAHost.bounds
  713. let radius = min(r.height / 2, r.width / 2)
  714. findJobsCTAHost.layer?.shadowPath = CGPath(
  715. roundedRect: r,
  716. cornerWidth: radius,
  717. cornerHeight: radius,
  718. transform: nil
  719. )
  720. }
  721. private func configureNonHomePlaceholder() {
  722. nonHomeHost.translatesAutoresizingMaskIntoConstraints = false
  723. nonHomeHost.wantsLayer = true
  724. nonHomeHost.layer?.backgroundColor = Theme.mainHostBackground.cgColor
  725. nonHomeHost.isHidden = true
  726. nonHomeGenericContainer.translatesAutoresizingMaskIntoConstraints = false
  727. savedJobsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  728. settingsPageContainer.translatesAutoresizingMaskIntoConstraints = false
  729. nonHomeHost.addSubview(nonHomeGenericContainer)
  730. nonHomeHost.addSubview(savedJobsPageContainer)
  731. nonHomeHost.addSubview(settingsPageContainer)
  732. NSLayoutConstraint.activate([
  733. nonHomeGenericContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  734. nonHomeGenericContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  735. nonHomeGenericContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  736. nonHomeGenericContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  737. savedJobsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  738. savedJobsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  739. savedJobsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  740. savedJobsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor),
  741. settingsPageContainer.leadingAnchor.constraint(equalTo: nonHomeHost.leadingAnchor),
  742. settingsPageContainer.trailingAnchor.constraint(equalTo: nonHomeHost.trailingAnchor),
  743. settingsPageContainer.topAnchor.constraint(equalTo: nonHomeHost.topAnchor),
  744. settingsPageContainer.bottomAnchor.constraint(equalTo: nonHomeHost.bottomAnchor)
  745. ])
  746. nonHomeTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  747. nonHomeTitleLabel.textColor = Theme.primaryText
  748. nonHomeTitleLabel.alignment = .center
  749. nonHomeTitleLabel.maximumNumberOfLines = 1
  750. nonHomeSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  751. nonHomeSubtitleLabel.textColor = Theme.secondaryText
  752. nonHomeSubtitleLabel.alignment = .center
  753. nonHomeSubtitleLabel.maximumNumberOfLines = 0
  754. nonHomeSubtitleLabel.stringValue = "This area is not available in the preview build. Use Home to search jobs."
  755. let genericStack = NSStackView(views: [nonHomeTitleLabel, nonHomeSubtitleLabel])
  756. genericStack.orientation = .vertical
  757. genericStack.spacing = 10
  758. genericStack.alignment = .centerX
  759. genericStack.translatesAutoresizingMaskIntoConstraints = false
  760. nonHomeGenericContainer.addSubview(genericStack)
  761. NSLayoutConstraint.activate([
  762. genericStack.centerXAnchor.constraint(equalTo: nonHomeGenericContainer.centerXAnchor),
  763. genericStack.centerYAnchor.constraint(equalTo: nonHomeGenericContainer.centerYAnchor),
  764. genericStack.leadingAnchor.constraint(greaterThanOrEqualTo: nonHomeGenericContainer.leadingAnchor, constant: 32),
  765. genericStack.trailingAnchor.constraint(lessThanOrEqualTo: nonHomeGenericContainer.trailingAnchor, constant: -32),
  766. nonHomeSubtitleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 420)
  767. ])
  768. savedJobsPageTitleLabel.font = .systemFont(ofSize: 22, weight: .bold)
  769. savedJobsPageTitleLabel.textColor = Theme.primaryText
  770. savedJobsPageTitleLabel.alignment = .left
  771. savedJobsPageTitleLabel.maximumNumberOfLines = 1
  772. savedJobsPageSubtitleLabel.font = .systemFont(ofSize: 14, weight: .regular)
  773. savedJobsPageSubtitleLabel.textColor = Theme.secondaryText
  774. savedJobsPageSubtitleLabel.alignment = .left
  775. savedJobsPageSubtitleLabel.maximumNumberOfLines = 0
  776. savedJobsDocumentView.translatesAutoresizingMaskIntoConstraints = false
  777. savedJobsStack.orientation = .vertical
  778. savedJobsStack.spacing = 14
  779. savedJobsStack.alignment = .leading
  780. savedJobsStack.distribution = .fill
  781. savedJobsStack.translatesAutoresizingMaskIntoConstraints = false
  782. savedJobsStack.setContentHuggingPriority(.defaultHigh, for: .vertical)
  783. savedJobsStack.setHuggingPriority(.defaultLow, for: .horizontal)
  784. savedJobsDocumentView.addSubview(savedJobsStack)
  785. NSLayoutConstraint.activate([
  786. savedJobsStack.leadingAnchor.constraint(equalTo: savedJobsDocumentView.leadingAnchor),
  787. savedJobsStack.trailingAnchor.constraint(equalTo: savedJobsDocumentView.trailingAnchor),
  788. savedJobsStack.topAnchor.constraint(equalTo: savedJobsDocumentView.topAnchor),
  789. savedJobsStack.bottomAnchor.constraint(equalTo: savedJobsDocumentView.bottomAnchor)
  790. ])
  791. savedJobsScrollView.translatesAutoresizingMaskIntoConstraints = false
  792. savedJobsScrollView.hasVerticalScroller = true
  793. savedJobsScrollView.hasHorizontalScroller = false
  794. savedJobsScrollView.autohidesScrollers = true
  795. savedJobsScrollView.drawsBackground = false
  796. savedJobsScrollView.borderType = .noBorder
  797. savedJobsScrollView.documentView = savedJobsDocumentView
  798. savedJobsScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
  799. savedJobsScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  800. let savedHeaderStack = NSStackView(views: [savedJobsPageTitleLabel, savedJobsPageSubtitleLabel])
  801. savedHeaderStack.orientation = .vertical
  802. savedHeaderStack.spacing = 6
  803. savedHeaderStack.alignment = .leading
  804. savedHeaderStack.translatesAutoresizingMaskIntoConstraints = false
  805. let savedOuterStack = NSStackView(views: [savedHeaderStack, savedJobsScrollView])
  806. savedOuterStack.orientation = .vertical
  807. savedOuterStack.spacing = 16
  808. // Leading alignment plus explicit column width keeps the title and subtitle on the same edge as the cards.
  809. savedOuterStack.alignment = .leading
  810. savedOuterStack.translatesAutoresizingMaskIntoConstraints = false
  811. savedJobsPageContainer.userInterfaceLayoutDirection = .leftToRight
  812. savedJobsPageContainer.addSubview(savedOuterStack)
  813. NSLayoutConstraint.activate([
  814. savedOuterStack.leadingAnchor.constraint(equalTo: savedJobsPageContainer.leadingAnchor, constant: 32),
  815. savedOuterStack.trailingAnchor.constraint(equalTo: savedJobsPageContainer.trailingAnchor, constant: -32),
  816. savedOuterStack.topAnchor.constraint(equalTo: savedJobsPageContainer.topAnchor, constant: 8),
  817. savedOuterStack.bottomAnchor.constraint(equalTo: savedJobsPageContainer.bottomAnchor),
  818. savedHeaderStack.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  819. savedJobsScrollView.widthAnchor.constraint(equalTo: savedOuterStack.widthAnchor),
  820. savedJobsDocumentView.topAnchor.constraint(equalTo: savedJobsScrollView.contentView.topAnchor),
  821. savedJobsDocumentView.leadingAnchor.constraint(equalTo: savedJobsScrollView.contentView.leadingAnchor),
  822. savedJobsDocumentView.widthAnchor.constraint(equalTo: savedJobsScrollView.contentView.widthAnchor)
  823. ])
  824. configureSettingsPage()
  825. }
  826. private func configureSettingsPage() {
  827. settingsPageContainer.wantsLayer = true
  828. settingsPageContainer.layer?.backgroundColor = Theme.settingsPageBackground.cgColor
  829. settingsPageContainer.isHidden = true
  830. let contentStack = NSStackView()
  831. contentStack.orientation = .vertical
  832. contentStack.spacing = 26
  833. contentStack.alignment = .leading
  834. contentStack.translatesAutoresizingMaskIntoConstraints = false
  835. let settingsSection = makeSettingsSection(rows: [
  836. makeSettingsRow(title: "Share App", systemImage: "square.and.arrow.up", accessory: nil),
  837. makeSettingsRow(title: "Theme", systemImage: "circle.lefthalf.filled", accessory: makeThemeControl()),
  838. makeSettingsRow(title: "More Apps", systemImage: "square.grid.2x2", accessory: nil)
  839. ])
  840. let aboutTitle = NSTextField(labelWithString: "About")
  841. aboutTitle.font = .systemFont(ofSize: 12, weight: .semibold)
  842. aboutTitle.textColor = Theme.secondaryText
  843. aboutTitle.alignment = .left
  844. let aboutSection = makeSettingsSection(rows: [
  845. makeSettingsRow(title: "Support", systemImage: "questionmark.circle", accessory: nil),
  846. makeSettingsRow(title: "Terms of Use", systemImage: "doc.text", accessory: nil),
  847. makeSettingsRow(title: "Privacy Policy", systemImage: "shield", accessory: nil)
  848. ])
  849. let aboutStack = NSStackView(views: [aboutTitle, aboutSection])
  850. aboutStack.orientation = .vertical
  851. aboutStack.spacing = 14
  852. aboutStack.alignment = .leading
  853. aboutStack.translatesAutoresizingMaskIntoConstraints = false
  854. contentStack.addArrangedSubview(settingsSection)
  855. contentStack.addArrangedSubview(aboutStack)
  856. settingsPageContainer.addSubview(contentStack)
  857. NSLayoutConstraint.activate([
  858. contentStack.leadingAnchor.constraint(equalTo: settingsPageContainer.leadingAnchor, constant: 42),
  859. contentStack.trailingAnchor.constraint(lessThanOrEqualTo: settingsPageContainer.trailingAnchor, constant: -42),
  860. contentStack.topAnchor.constraint(equalTo: settingsPageContainer.topAnchor, constant: 48),
  861. settingsSection.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  862. aboutStack.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  863. aboutSection.widthAnchor.constraint(equalTo: aboutStack.widthAnchor),
  864. contentStack.widthAnchor.constraint(equalTo: settingsPageContainer.widthAnchor, constant: -84)
  865. ])
  866. }
  867. private func makeThemeControl() -> NSSegmentedControl {
  868. themeControl.target = self
  869. themeControl.action = #selector(didChangeThemeSelection(_:))
  870. themeControl.selectedSegment = 0
  871. themeControl.segmentStyle = .rounded
  872. themeControl.controlSize = .large
  873. themeControl.font = .systemFont(ofSize: 13, weight: .semibold)
  874. themeControl.translatesAutoresizingMaskIntoConstraints = false
  875. themeControl.widthAnchor.constraint(equalToConstant: 204).isActive = true
  876. themeControl.heightAnchor.constraint(equalToConstant: 30).isActive = true
  877. return themeControl
  878. }
  879. private func makeSettingsSection(rows: [NSView]) -> NSView {
  880. let section = NSStackView()
  881. section.orientation = .vertical
  882. section.spacing = 0
  883. section.alignment = .leading
  884. section.translatesAutoresizingMaskIntoConstraints = false
  885. section.wantsLayer = true
  886. section.layer?.backgroundColor = Theme.settingsGroupBackground.cgColor
  887. section.layer?.cornerRadius = 14
  888. section.layer?.borderWidth = 1
  889. section.layer?.borderColor = Theme.border.cgColor
  890. section.layer?.masksToBounds = true
  891. for (index, row) in rows.enumerated() {
  892. section.addArrangedSubview(row)
  893. row.widthAnchor.constraint(equalTo: section.widthAnchor).isActive = true
  894. if index < rows.count - 1 {
  895. let divider = NSView()
  896. divider.translatesAutoresizingMaskIntoConstraints = false
  897. divider.wantsLayer = true
  898. divider.layer?.backgroundColor = Theme.settingsDivider.cgColor
  899. section.addArrangedSubview(divider)
  900. NSLayoutConstraint.activate([
  901. divider.heightAnchor.constraint(equalToConstant: 1),
  902. divider.leadingAnchor.constraint(equalTo: section.leadingAnchor),
  903. divider.trailingAnchor.constraint(equalTo: section.trailingAnchor)
  904. ])
  905. }
  906. }
  907. return section
  908. }
  909. private func makeSettingsRow(title: String, systemImage: String, accessory: NSView?) -> NSView {
  910. let row = NSView()
  911. row.translatesAutoresizingMaskIntoConstraints = false
  912. row.wantsLayer = true
  913. let iconTile = NSView()
  914. iconTile.translatesAutoresizingMaskIntoConstraints = false
  915. iconTile.wantsLayer = true
  916. iconTile.layer?.backgroundColor = Theme.settingsIconBackground.cgColor
  917. iconTile.layer?.cornerRadius = 9
  918. let icon = NSImageView()
  919. icon.translatesAutoresizingMaskIntoConstraints = false
  920. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  921. icon.image = NSImage(systemSymbolName: systemImage, accessibilityDescription: title)
  922. icon.contentTintColor = Theme.brandBlue
  923. let titleLabel = NSTextField(labelWithString: title)
  924. titleLabel.font = .systemFont(ofSize: 14, weight: .medium)
  925. titleLabel.textColor = Theme.secondaryText
  926. titleLabel.alignment = .left
  927. let rowStack = NSStackView()
  928. rowStack.orientation = .horizontal
  929. rowStack.spacing = 16
  930. rowStack.alignment = .centerY
  931. rowStack.translatesAutoresizingMaskIntoConstraints = false
  932. let spacer = NSView()
  933. spacer.translatesAutoresizingMaskIntoConstraints = false
  934. spacer.setContentHuggingPriority(NSLayoutConstraint.Priority(1), for: .horizontal)
  935. iconTile.addSubview(icon)
  936. rowStack.addArrangedSubview(iconTile)
  937. rowStack.addArrangedSubview(titleLabel)
  938. rowStack.addArrangedSubview(spacer)
  939. if let accessory {
  940. rowStack.addArrangedSubview(accessory)
  941. }
  942. row.addSubview(rowStack)
  943. NSLayoutConstraint.activate([
  944. row.heightAnchor.constraint(equalToConstant: 68),
  945. iconTile.widthAnchor.constraint(equalToConstant: 38),
  946. iconTile.heightAnchor.constraint(equalToConstant: 38),
  947. icon.centerXAnchor.constraint(equalTo: iconTile.centerXAnchor),
  948. icon.centerYAnchor.constraint(equalTo: iconTile.centerYAnchor),
  949. icon.widthAnchor.constraint(equalToConstant: 20),
  950. icon.heightAnchor.constraint(equalToConstant: 20),
  951. rowStack.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 16),
  952. rowStack.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -16),
  953. rowStack.topAnchor.constraint(equalTo: row.topAnchor),
  954. rowStack.bottomAnchor.constraint(equalTo: row.bottomAnchor)
  955. ])
  956. return row
  957. }
  958. private func reloadSavedJobsListings() {
  959. savedJobsStack.arrangedSubviews.forEach {
  960. savedJobsStack.removeArrangedSubview($0)
  961. $0.removeFromSuperview()
  962. }
  963. if savedJobOrder.isEmpty {
  964. savedJobsPageSubtitleLabel.stringValue = "Save jobs from Home to see them here."
  965. let empty = NSTextField(wrappingLabelWithString: "No saved jobs yet. Search on Home, then tap Save on a listing.")
  966. empty.font = .systemFont(ofSize: 14, weight: .regular)
  967. empty.textColor = Theme.secondaryText
  968. empty.alignment = .left
  969. empty.maximumNumberOfLines = 0
  970. empty.translatesAutoresizingMaskIntoConstraints = false
  971. savedJobsStack.addArrangedSubview(empty)
  972. empty.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  973. return
  974. }
  975. savedJobsPageSubtitleLabel.stringValue = "\(savedJobOrder.count) saved \(savedJobOrder.count == 1 ? "position" : "positions")"
  976. for job in savedJobOrder {
  977. let card = makeJobListingCard(job, context: .savedJobsPage)
  978. savedJobsStack.addArrangedSubview(card)
  979. card.widthAnchor.constraint(equalTo: savedJobsStack.widthAnchor).isActive = true
  980. }
  981. }
  982. private func isSavedJobsSidebarIndex(_ index: Int) -> Bool {
  983. guard index >= 0, index < currentSidebarItems.count else { return false }
  984. return currentSidebarItems[index].title == "Saved Jobs"
  985. }
  986. private func isHomeSidebarIndex(_ index: Int) -> Bool {
  987. guard index >= 0, index < currentSidebarItems.count else { return false }
  988. return currentSidebarItems[index].title == "Home"
  989. }
  990. private func isSettingsSidebarIndex(_ index: Int) -> Bool {
  991. guard index >= 0, index < currentSidebarItems.count else { return false }
  992. return currentSidebarItems[index].title == "Settings"
  993. }
  994. private func updateMainContentVisibility() {
  995. let home = isHomeSidebarIndex(selectedSidebarIndex)
  996. let savedJobs = isSavedJobsSidebarIndex(selectedSidebarIndex)
  997. let settings = isSettingsSidebarIndex(selectedSidebarIndex)
  998. mainOverlay.isHidden = !home
  999. nonHomeHost.isHidden = home
  1000. nonHomeGenericContainer.isHidden = savedJobs || settings
  1001. savedJobsPageContainer.isHidden = !savedJobs
  1002. settingsPageContainer.isHidden = !settings
  1003. if !home, selectedSidebarIndex < currentSidebarItems.count {
  1004. if savedJobs {
  1005. reloadSavedJobsListings()
  1006. } else if settings {
  1007. window?.makeFirstResponder(nil)
  1008. } else {
  1009. nonHomeTitleLabel.stringValue = currentSidebarItems[selectedSidebarIndex].title
  1010. }
  1011. }
  1012. }
  1013. /// Restores the main job-search experience: cleared query and a fresh chat history.
  1014. private func applyHomeState() {
  1015. jobKeywordsField.stringValue = ""
  1016. resetChatState()
  1017. window?.makeFirstResponder(nil)
  1018. }
  1019. private func updateSearchBarShadowPath() {
  1020. guard searchBarShadowHost.bounds.width > 0, searchBarShadowHost.bounds.height > 0 else { return }
  1021. let r = searchBarShadowHost.bounds
  1022. let radius = min(r.height / 2, 27)
  1023. searchBarShadowHost.layer?.shadowPath = CGPath(
  1024. roundedRect: r,
  1025. cornerWidth: radius,
  1026. cornerHeight: radius,
  1027. transform: nil
  1028. )
  1029. }
  1030. @objc private func didSubmitSearch() {
  1031. let prompt = jobKeywordsField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
  1032. guard !prompt.isEmpty, !isAwaitingResponse else { return }
  1033. let isContinuation = isContinuationPrompt(prompt)
  1034. let effectiveQuery = resolvedSearchQuery(for: prompt)
  1035. appendChatBubble(text: prompt, isUser: true)
  1036. chatMessages.append(ChatMessage(role: "user", content: prompt))
  1037. jobKeywordsField.stringValue = ""
  1038. isAwaitingResponse = true
  1039. chatStatusLabel.stringValue = "Thinking..."
  1040. setInputEnabled(false)
  1041. let contextMessages = chatMessages
  1042. jobSearchService.searchJobs(query: effectiveQuery, conversation: contextMessages) { [weak self] result in
  1043. DispatchQueue.main.async {
  1044. guard let self else { return }
  1045. self.isAwaitingResponse = false
  1046. self.setInputEnabled(true)
  1047. switch result {
  1048. case .success(let output):
  1049. let normalizedJobs = self.normalizedJobs(output.jobs)
  1050. let freshJobs: [JobListing]
  1051. if isContinuation {
  1052. // Continuations append only the *new* matches; previous cards already live in their own assistant message above.
  1053. let alreadySeen = Set(self.lastSearchResults)
  1054. freshJobs = normalizedJobs.filter { !alreadySeen.contains($0) }
  1055. } else {
  1056. freshJobs = normalizedJobs
  1057. }
  1058. self.lastSearchResults.append(contentsOf: freshJobs)
  1059. let reply = self.makeAssistantSearchReply(
  1060. query: effectiveQuery,
  1061. newJobsCount: freshJobs.count,
  1062. isContinuation: isContinuation
  1063. )
  1064. self.chatMessages.append(ChatMessage(role: "assistant", content: reply))
  1065. self.appendChatBubble(text: reply, isUser: false, jobs: freshJobs)
  1066. self.chatStatusLabel.stringValue = "Ask for another role, company, or skill match"
  1067. case .failure(let error):
  1068. self.appendChatBubble(text: error.localizedDescription, isUser: false)
  1069. if error is URLError {
  1070. self.chatStatusLabel.stringValue = "Could not reach API. Try again."
  1071. } else {
  1072. self.chatStatusLabel.stringValue = "Search did not finish. Try again."
  1073. }
  1074. }
  1075. }
  1076. }
  1077. window?.makeFirstResponder(nil)
  1078. }
  1079. private func normalizedJobs(_ jobs: [JobListing]) -> [JobListing] {
  1080. let trimmed = jobs.map {
  1081. JobListing(
  1082. title: $0.title.trimmingCharacters(in: .whitespacesAndNewlines),
  1083. description: $0.description.trimmingCharacters(in: .whitespacesAndNewlines),
  1084. url: $0.url?.trimmingCharacters(in: .whitespacesAndNewlines)
  1085. )
  1086. }
  1087. return trimmed.filter { !$0.title.isEmpty && !$0.description.isEmpty }
  1088. }
  1089. private func makeAssistantSearchReply(query: String, newJobsCount: Int, isContinuation: Bool) -> String {
  1090. if newJobsCount == 0 {
  1091. if isContinuation {
  1092. return "I couldn't find new matches for \u{201C}\(query)\u{201D}. Try a different angle or a more specific keyword."
  1093. }
  1094. return "No jobs found for \u{201C}\(query)\u{201D}. Try another title, skill, company, or location."
  1095. }
  1096. let plural = newJobsCount == 1 ? "match" : "matches"
  1097. if isContinuation {
  1098. return "Here are \(newJobsCount) more \(plural) for \u{201C}\(query)\u{201D}."
  1099. }
  1100. return "Found \(newJobsCount) \(plural) for \u{201C}\(query)\u{201D}. Tap Apply to open the listing or Save to revisit later."
  1101. }
  1102. private func resolvedSearchQuery(for prompt: String) -> String {
  1103. let anchor = anchorUserJobQuery(excludingLatestUserMessage: prompt)
  1104. if isContinuationPrompt(prompt), !isRefinementPrompt(prompt) {
  1105. if let anchor { return anchor }
  1106. return prompt
  1107. }
  1108. if isRefinementPrompt(prompt), let anchor {
  1109. return "\(anchor). User follow-up (apply on top of the same search topic): \(prompt)"
  1110. }
  1111. return prompt
  1112. }
  1113. /// First prior user message that looks like an original job query (skips short continuations and refinements so follow-ups keep a stable topic anchor).
  1114. private func anchorUserJobQuery(excludingLatestUserMessage latest: String) -> String? {
  1115. let prior = Array(chatMessages.dropLast())
  1116. for message in prior.reversed() where message.role == "user" {
  1117. let candidate = message.content.trimmingCharacters(in: .whitespacesAndNewlines)
  1118. guard !candidate.isEmpty, candidate != latest else { continue }
  1119. if isContinuationPrompt(candidate) { continue }
  1120. if isRefinementPrompt(candidate) { continue }
  1121. return candidate
  1122. }
  1123. return nil
  1124. }
  1125. private func isContinuationPrompt(_ prompt: String) -> Bool {
  1126. let normalized = prompt.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
  1127. let continuationPhrases: Set<String> = [
  1128. "more",
  1129. "show more",
  1130. "more jobs",
  1131. "more results",
  1132. "do more searches",
  1133. "more searches",
  1134. "search more",
  1135. "continue",
  1136. "next"
  1137. ]
  1138. if continuationPhrases.contains(normalized) {
  1139. return true
  1140. }
  1141. return normalized.contains("more search") || normalized.contains("more job")
  1142. }
  1143. /// Follow-ups that narrow, re-rank, or re-frame results rather than starting a brand-new role search.
  1144. /// Strong phrases always count. Single-word cues (e.g. "remote") only count after we already showed results, so first searches like "Senior iOS remote" stay anchored as primary queries.
  1145. private func isRefinementPrompt(_ prompt: String) -> Bool {
  1146. let n = prompt.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
  1147. if n.isEmpty { return false }
  1148. let strongPhrases = [
  1149. "higher pay", "high pay", "better pay", "more pay", "top pay", "best pay",
  1150. "higher salary", "better salary", "more salary", "pay rate", "hourly rate",
  1151. "paid more", "paying more", "earn more", "better paid", "paying better",
  1152. "work from home", "in office", "in-office", "on-site only", "remote only",
  1153. "hybrid only", "onsite only", "visa sponsorship", "h1b",
  1154. "entry level", "entry-level", "mid level", "mid-level", "full time", "full-time",
  1155. "part time", "part-time",
  1156. "closer to", "nearer", "different city", "different state", "relocate",
  1157. "filter", "only show", "just show", "exclude", "without", "sort by", "rank by",
  1158. "cheaper", "lower pay", "less travel",
  1159. "better benefits", "equity", "bonus", "overtime",
  1160. "get me the jobs", "show me the jobs", "give me the jobs", "narrow", "refine"
  1161. ]
  1162. if strongPhrases.contains(where: { n.contains($0) }) { return true }
  1163. if n.hasPrefix("only ") || n.hasPrefix("just ") { return true }
  1164. guard !lastSearchResults.isEmpty, n.count <= 52 else { return false }
  1165. let softAfterResults = [
  1166. "remote", "hybrid", "onsite", "on-site", "senior", "junior", "staff", "lead",
  1167. "principal", "intern", "contract", "location"
  1168. ]
  1169. return softAfterResults.contains(where: { n.contains($0) })
  1170. }
  1171. func controlTextDidBeginEditing(_ obj: Notification) {
  1172. applySearchFieldInsertionPoint(obj.object)
  1173. if (obj.object as? NSTextField) === jobKeywordsField {
  1174. chatStatusLabel.stringValue = "Opening the vault..."
  1175. }
  1176. }
  1177. func controlTextDidChange(_ obj: Notification) {
  1178. applySearchFieldInsertionPoint(obj.object)
  1179. }
  1180. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  1181. guard control === jobKeywordsField, commandSelector == #selector(NSResponder.insertNewline(_:)) else {
  1182. return false
  1183. }
  1184. didSubmitSearch()
  1185. return true
  1186. }
  1187. private func applySearchFieldInsertionPoint(_ object: Any?) {
  1188. guard let field = object as? NSTextField,
  1189. field === jobKeywordsField,
  1190. let textView = field.window?.fieldEditor(true, for: field) as? NSTextView else { return }
  1191. textView.insertionPointColor = Theme.primaryText
  1192. }
  1193. private func resetChatState() {
  1194. chatMessages.removeAll()
  1195. lastSearchResults.removeAll()
  1196. chatStack.arrangedSubviews.forEach {
  1197. chatStack.removeArrangedSubview($0)
  1198. $0.removeFromSuperview()
  1199. }
  1200. let welcome = "Tell me what role you want and I will return job descriptions, key skills, and a quick fit summary."
  1201. chatMessages.append(ChatMessage(role: "assistant", content: welcome))
  1202. appendChatBubble(text: welcome, isUser: false)
  1203. chatStatusLabel.stringValue = "Ask me to find jobs"
  1204. }
  1205. private func appendChatBubble(text: String, isUser: Bool, jobs: [JobListing]? = nil) {
  1206. let host = NSView()
  1207. host.translatesAutoresizingMaskIntoConstraints = false
  1208. if isUser {
  1209. installUserBubble(text: text, into: host)
  1210. } else {
  1211. installAssistantBubble(text: text, jobs: jobs, into: host)
  1212. }
  1213. chatStack.addArrangedSubview(host)
  1214. host.widthAnchor.constraint(equalTo: chatStack.widthAnchor).isActive = true
  1215. DispatchQueue.main.async { [weak self] in
  1216. self?.updateChatBubbleWidths()
  1217. self?.scrollChatToBottom()
  1218. }
  1219. }
  1220. private func installUserBubble(text: String, into host: NSView) {
  1221. let bubble = makeChatBubbleContainer(text: text, isUser: true)
  1222. host.addSubview(bubble)
  1223. NSLayoutConstraint.activate([
  1224. bubble.topAnchor.constraint(equalTo: host.topAnchor),
  1225. bubble.bottomAnchor.constraint(equalTo: host.bottomAnchor),
  1226. bubble.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  1227. bubble.leadingAnchor.constraint(greaterThanOrEqualTo: host.leadingAnchor, constant: 64),
  1228. bubble.widthAnchor.constraint(lessThanOrEqualTo: host.widthAnchor, multiplier: 0.78)
  1229. ])
  1230. }
  1231. private func installAssistantBubble(text: String, jobs: [JobListing]?, into host: NSView) {
  1232. let avatar = makeAssistantAvatarView()
  1233. let nameLabel = NSTextField(labelWithString: "AI Job Finder")
  1234. nameLabel.font = .systemFont(ofSize: 11, weight: .semibold)
  1235. nameLabel.textColor = Theme.secondaryText
  1236. nameLabel.translatesAutoresizingMaskIntoConstraints = false
  1237. let bubble = makeChatBubbleContainer(text: text, isUser: false)
  1238. let column = NSStackView(views: [nameLabel, bubble])
  1239. column.orientation = .vertical
  1240. column.spacing = 6
  1241. column.alignment = .leading
  1242. column.translatesAutoresizingMaskIntoConstraints = false
  1243. if let jobs, !jobs.isEmpty {
  1244. let jobsStack = makeChatJobsStackView(jobs: jobs)
  1245. column.addArrangedSubview(jobsStack)
  1246. jobsStack.widthAnchor.constraint(equalTo: column.widthAnchor).isActive = true
  1247. }
  1248. host.addSubview(avatar)
  1249. host.addSubview(column)
  1250. NSLayoutConstraint.activate([
  1251. avatar.leadingAnchor.constraint(equalTo: host.leadingAnchor),
  1252. avatar.topAnchor.constraint(equalTo: host.topAnchor),
  1253. avatar.widthAnchor.constraint(equalToConstant: 36),
  1254. avatar.heightAnchor.constraint(equalToConstant: 36),
  1255. column.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 12),
  1256. column.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  1257. column.topAnchor.constraint(equalTo: host.topAnchor),
  1258. column.bottomAnchor.constraint(equalTo: host.bottomAnchor)
  1259. ])
  1260. }
  1261. private func makeChatBubbleContainer(text: String, isUser: Bool) -> NSView {
  1262. let container = NSView()
  1263. container.translatesAutoresizingMaskIntoConstraints = false
  1264. container.wantsLayer = true
  1265. container.layer?.cornerRadius = 14
  1266. if #available(macOS 11.0, *) {
  1267. container.layer?.cornerCurve = .continuous
  1268. }
  1269. container.layer?.masksToBounds = true
  1270. if isUser {
  1271. container.layer?.backgroundColor = Theme.brandBlue.cgColor
  1272. } else {
  1273. container.layer?.backgroundColor = Theme.chromeBackground.cgColor
  1274. container.layer?.borderWidth = 1
  1275. container.layer?.borderColor = Theme.border.cgColor
  1276. }
  1277. let label = ChatBubbleLabel(wrappingLabelWithString: text)
  1278. label.font = .systemFont(ofSize: 13.5, weight: .regular)
  1279. label.textColor = isUser ? .white : Theme.primaryText
  1280. label.maximumNumberOfLines = 0
  1281. label.lineBreakMode = .byWordWrapping
  1282. label.alignment = .left
  1283. label.translatesAutoresizingMaskIntoConstraints = false
  1284. label.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1285. label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  1286. container.addSubview(label)
  1287. NSLayoutConstraint.activate([
  1288. label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 14),
  1289. label.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -14),
  1290. label.topAnchor.constraint(equalTo: container.topAnchor, constant: 10),
  1291. label.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -10)
  1292. ])
  1293. return container
  1294. }
  1295. private func makeAssistantAvatarView() -> NSView {
  1296. let view = NSView()
  1297. view.translatesAutoresizingMaskIntoConstraints = false
  1298. view.wantsLayer = true
  1299. view.layer?.cornerRadius = 18
  1300. if #available(macOS 11.0, *) {
  1301. view.layer?.cornerCurve = .continuous
  1302. }
  1303. view.layer?.backgroundColor = Theme.settingsIconBackground.cgColor
  1304. view.layer?.borderWidth = 1
  1305. view.layer?.borderColor = Theme.proCardBorder.cgColor
  1306. let icon = NSImageView()
  1307. icon.translatesAutoresizingMaskIntoConstraints = false
  1308. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 15, weight: .semibold)
  1309. icon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: "AI Job Finder")
  1310. icon.contentTintColor = Theme.brandBlue
  1311. view.addSubview(icon)
  1312. NSLayoutConstraint.activate([
  1313. icon.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  1314. icon.centerYAnchor.constraint(equalTo: view.centerYAnchor)
  1315. ])
  1316. return view
  1317. }
  1318. private func makeChatJobsStackView(jobs: [JobListing]) -> ChatJobsStackView {
  1319. let stack = ChatJobsStackView()
  1320. stack.orientation = .vertical
  1321. stack.spacing = 10
  1322. stack.alignment = .leading
  1323. stack.distribution = .fill
  1324. stack.translatesAutoresizingMaskIntoConstraints = false
  1325. for job in jobs {
  1326. let card = makeJobListingCard(job, context: .homeSearchResults)
  1327. stack.addArrangedSubview(card)
  1328. card.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  1329. }
  1330. return stack
  1331. }
  1332. private func scrollChatToBottom() {
  1333. let maxY = max(0, chatDocumentView.bounds.height - chatScrollView.contentView.bounds.height)
  1334. chatScrollView.contentView.scroll(to: NSPoint(x: 0, y: maxY))
  1335. chatScrollView.reflectScrolledClipView(chatScrollView.contentView)
  1336. }
  1337. private func setInputEnabled(_ enabled: Bool) {
  1338. jobKeywordsField.isEnabled = enabled
  1339. findJobsButton.isEnabled = enabled
  1340. findJobsButton.alphaValue = enabled ? 1 : 0.65
  1341. }
  1342. private func configureSidebar() {
  1343. let items = currentSidebarItems
  1344. sidebar.arrangedSubviews.forEach {
  1345. sidebar.removeArrangedSubview($0)
  1346. $0.removeFromSuperview()
  1347. }
  1348. let brand = NSTextField(labelWithString: "Indeed AI\nJob Finder")
  1349. brand.font = .systemFont(ofSize: 18, weight: .bold)
  1350. brand.textColor = Theme.brandBlue
  1351. brand.alignment = .left
  1352. brand.maximumNumberOfLines = 2
  1353. // Tight multiline height in the sidebar stack (zero width makes intrinsic height unreliable).
  1354. brand.preferredMaxLayoutWidth = 194
  1355. sidebar.addArrangedSubview(brand)
  1356. sidebar.setCustomSpacing(10, after: brand)
  1357. items.enumerated().forEach { index, item in
  1358. let isSelected = index == selectedSidebarIndex
  1359. let rowHost = SidebarNavRowView { [weak self] in
  1360. self?.selectSidebarItem(at: index)
  1361. }
  1362. rowHost.translatesAutoresizingMaskIntoConstraints = false
  1363. rowHost.wantsLayer = true
  1364. rowHost.layer?.cornerRadius = 8
  1365. rowHost.restingBackgroundColor = isSelected ? Theme.selectionFill : nil
  1366. rowHost.hoverBackgroundColor = isSelected ? Theme.selectionFillHover : Theme.sidebarRowHoverFill
  1367. rowHost.setAccessibilityLabel(item.title)
  1368. rowHost.setAccessibilityRole(.button)
  1369. rowHost.setAccessibilitySelected(isSelected)
  1370. let row = NSStackView()
  1371. row.orientation = .horizontal
  1372. row.spacing = 8
  1373. row.alignment = .centerY
  1374. row.translatesAutoresizingMaskIntoConstraints = false
  1375. let icon = NSImageView()
  1376. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .medium)
  1377. icon.image = NSImage(systemSymbolName: item.systemImage, accessibilityDescription: item.title)
  1378. icon.contentTintColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1379. let text = NSTextField(labelWithString: item.title)
  1380. text.font = .systemFont(ofSize: 14, weight: .medium)
  1381. text.textColor = isSelected ? Theme.brandBlue : Theme.secondaryText
  1382. text.refusesFirstResponder = true
  1383. row.addArrangedSubview(icon)
  1384. row.addArrangedSubview(text)
  1385. if let badge = item.badge {
  1386. let badgeField = NSTextField(labelWithString: badge)
  1387. badgeField.font = .systemFont(ofSize: 11, weight: .semibold)
  1388. badgeField.textColor = Theme.primaryText
  1389. badgeField.wantsLayer = true
  1390. badgeField.layer?.backgroundColor = Theme.toggleBackground.cgColor
  1391. badgeField.layer?.cornerRadius = 8
  1392. badgeField.alignment = .center
  1393. badgeField.maximumNumberOfLines = 1
  1394. badgeField.lineBreakMode = .byClipping
  1395. badgeField.refusesFirstResponder = true
  1396. badgeField.translatesAutoresizingMaskIntoConstraints = false
  1397. badgeField.widthAnchor.constraint(equalToConstant: 42).isActive = true
  1398. row.addArrangedSubview(NSView())
  1399. row.addArrangedSubview(badgeField)
  1400. }
  1401. rowHost.addSubview(row)
  1402. NSLayoutConstraint.activate([
  1403. row.leadingAnchor.constraint(equalTo: rowHost.leadingAnchor, constant: 10),
  1404. row.trailingAnchor.constraint(equalTo: rowHost.trailingAnchor, constant: -10),
  1405. row.topAnchor.constraint(equalTo: rowHost.topAnchor, constant: 8),
  1406. row.bottomAnchor.constraint(equalTo: rowHost.bottomAnchor, constant: -8)
  1407. ])
  1408. rowHost.setContentHuggingPriority(.defaultLow, for: .horizontal)
  1409. sidebar.addArrangedSubview(rowHost)
  1410. let sidebarHorizontalInset = sidebar.edgeInsets.left + sidebar.edgeInsets.right
  1411. rowHost.widthAnchor.constraint(equalTo: sidebar.widthAnchor, constant: -sidebarHorizontalInset).isActive = true
  1412. }
  1413. let sidebarBottomSpacer = NSView()
  1414. sidebarBottomSpacer.translatesAutoresizingMaskIntoConstraints = false
  1415. sidebarBottomSpacer.setContentHuggingPriority(.defaultLow, for: .vertical)
  1416. sidebarBottomSpacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
  1417. sidebar.addArrangedSubview(sidebarBottomSpacer)
  1418. let upgradeCard = NSView()
  1419. upgradeCard.translatesAutoresizingMaskIntoConstraints = false
  1420. upgradeCard.wantsLayer = true
  1421. upgradeCard.layer?.backgroundColor = Theme.proCardFill.cgColor
  1422. upgradeCard.layer?.cornerRadius = 14
  1423. upgradeCard.layer?.borderWidth = 1
  1424. upgradeCard.layer?.borderColor = Theme.proCardBorder.cgColor
  1425. upgradeCard.layer?.masksToBounds = true
  1426. let accentBar = NSView()
  1427. accentBar.translatesAutoresizingMaskIntoConstraints = false
  1428. accentBar.wantsLayer = true
  1429. accentBar.layer?.backgroundColor = Theme.proAccent.cgColor
  1430. let inner = NSStackView()
  1431. inner.translatesAutoresizingMaskIntoConstraints = false
  1432. inner.orientation = .vertical
  1433. inner.spacing = 10
  1434. inner.alignment = .centerX
  1435. let proIcon = NSImageView()
  1436. proIcon.translatesAutoresizingMaskIntoConstraints = false
  1437. proIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  1438. proIcon.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)
  1439. proIcon.contentTintColor = Theme.proAccent
  1440. let proEyebrow = NSTextField(labelWithString: "Premium")
  1441. proEyebrow.font = .systemFont(ofSize: 11, weight: .heavy)
  1442. proEyebrow.textColor = Theme.proAccent
  1443. proEyebrow.alignment = .center
  1444. let eyebrowRow = NSStackView(views: [proIcon, proEyebrow])
  1445. eyebrowRow.orientation = .horizontal
  1446. eyebrowRow.spacing = 6
  1447. eyebrowRow.alignment = .centerY
  1448. let headline = NSTextField(labelWithString: "Upgrade to Pro")
  1449. headline.font = .systemFont(ofSize: 16, weight: .bold)
  1450. headline.textColor = Theme.primaryText
  1451. headline.alignment = .center
  1452. let upgradeDescription = NSTextField(wrappingLabelWithString: "Unlimited AI matches, smart alerts, and interview prep—all in one place.")
  1453. upgradeDescription.font = .systemFont(ofSize: 12, weight: .regular)
  1454. upgradeDescription.textColor = Theme.secondaryText
  1455. upgradeDescription.alignment = .center
  1456. // Sidebar content width is the fixed sidebar width minus horizontal edge insets; card must stay within that band.
  1457. let cardWidth: CGFloat = 186
  1458. let innerContentWidth = cardWidth - 28
  1459. upgradeDescription.preferredMaxLayoutWidth = innerContentWidth
  1460. let upgradeButton = HoverableButton(title: "Upgrade to Pro", target: self, action: #selector(didTapUpgradeToPro))
  1461. upgradeButton.isBordered = false
  1462. upgradeButton.bezelStyle = .rounded
  1463. upgradeButton.font = .systemFont(ofSize: 13, weight: .bold)
  1464. upgradeButton.contentTintColor = Theme.proCTAText
  1465. upgradeButton.alignment = .center
  1466. upgradeButton.wantsLayer = true
  1467. upgradeButton.layer?.backgroundColor = Theme.proCTABackground.cgColor
  1468. upgradeButton.layer?.cornerRadius = 20
  1469. upgradeButton.translatesAutoresizingMaskIntoConstraints = false
  1470. upgradeButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
  1471. upgradeButton.pointerCursor = true
  1472. upgradeButton.hoverHandler = { [weak upgradeButton] hovering in
  1473. upgradeButton?.layer?.backgroundColor = (hovering ? Theme.brandBlueHover : Theme.proCTABackground).cgColor
  1474. }
  1475. inner.addArrangedSubview(eyebrowRow)
  1476. inner.addArrangedSubview(headline)
  1477. inner.addArrangedSubview(upgradeDescription)
  1478. inner.addArrangedSubview(upgradeButton)
  1479. upgradeCard.addSubview(accentBar)
  1480. upgradeCard.addSubview(inner)
  1481. NSLayoutConstraint.activate([
  1482. upgradeCard.widthAnchor.constraint(equalToConstant: cardWidth),
  1483. accentBar.topAnchor.constraint(equalTo: upgradeCard.topAnchor),
  1484. accentBar.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor),
  1485. accentBar.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor),
  1486. accentBar.heightAnchor.constraint(equalToConstant: 2),
  1487. inner.leadingAnchor.constraint(equalTo: upgradeCard.leadingAnchor, constant: 14),
  1488. inner.trailingAnchor.constraint(equalTo: upgradeCard.trailingAnchor, constant: -14),
  1489. inner.topAnchor.constraint(equalTo: accentBar.bottomAnchor, constant: 12),
  1490. inner.bottomAnchor.constraint(equalTo: upgradeCard.bottomAnchor, constant: -14),
  1491. upgradeButton.widthAnchor.constraint(equalTo: inner.widthAnchor)
  1492. ])
  1493. sidebar.addArrangedSubview(upgradeCard)
  1494. }
  1495. @objc private func didTapUpgradeToPro() {
  1496. guard let url = URL(string: "https://www.indeed.com") else { return }
  1497. NSWorkspace.shared.open(url)
  1498. }
  1499. @objc private func didChangeThemeSelection(_ sender: NSSegmentedControl) {
  1500. switch sender.selectedSegment {
  1501. case 1:
  1502. NSApp.appearance = NSAppearance(named: .aqua)
  1503. case 2:
  1504. NSApp.appearance = NSAppearance(named: .darkAqua)
  1505. default:
  1506. NSApp.appearance = nil
  1507. }
  1508. }
  1509. private func selectSidebarItem(at index: Int) {
  1510. guard index >= 0, index < currentSidebarItems.count else { return }
  1511. let selectingHome = isHomeSidebarIndex(index)
  1512. if index == selectedSidebarIndex {
  1513. if selectingHome {
  1514. applyHomeState()
  1515. }
  1516. return
  1517. }
  1518. selectedSidebarIndex = index
  1519. configureSidebar()
  1520. updateMainContentVisibility()
  1521. if selectingHome {
  1522. applyHomeState()
  1523. }
  1524. }
  1525. }
  1526. private struct ChatMessage: Codable {
  1527. let role: String
  1528. let content: String
  1529. }
  1530. private final class OpenAIJobSearchService {
  1531. private let endpoint = URL(string: "https://api.openai.com/v1/responses")!
  1532. private let session = URLSession(configuration: .ephemeral)
  1533. func searchJobs(query: String, conversation: [ChatMessage], completion: @escaping (Result<JobSearchOutput, Error>) -> Void) {
  1534. let apiKey = OpenAIConfiguration.apiKey
  1535. guard OpenAIConfiguration.hasAPIKey else {
  1536. completion(.failure(NSError(
  1537. domain: "OpenAIJobSearchService",
  1538. code: 1,
  1539. userInfo: [NSLocalizedDescriptionKey: "Missing API key. Set OPENAI_API_KEY in Xcode Build Settings."]
  1540. )))
  1541. return
  1542. }
  1543. var request = URLRequest(url: endpoint)
  1544. request.httpMethod = "POST"
  1545. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  1546. request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
  1547. request.timeoutInterval = 45
  1548. let recentContext = conversation.suffix(8)
  1549. .map { "\($0.role.uppercased()): \($0.content)" }
  1550. .joined(separator: "\n")
  1551. let contextBlock: String
  1552. if recentContext.isEmpty {
  1553. contextBlock = "No prior conversation context."
  1554. } else {
  1555. contextBlock = recentContext
  1556. }
  1557. let instructions = """
  1558. Continue this same job-search conversation. Use prior context when useful. The line "Latest user query" is the primary task; earlier USER/ASSISTANT lines are context (previous role, location, or results).
  1559. Conversation context:
  1560. \(contextBlock)
  1561. Latest user query: "\(query)"
  1562. Use web search to find currently posted jobs that satisfy this query. If the user refines pay, seniority, work location, or similar, run a new search that applies those constraints to the same career topic as in the context.
  1563. CRITICAL OUTPUT RULES:
  1564. - Reply with NOTHING except one JSON object. No markdown, no code fences, no prose before or after, no labels like "Here is the JSON".
  1565. - The JSON must match exactly this shape (lowercase key "jobs"):
  1566. {"jobs":[{"title":"...","description":"...","url":"https://..."}]}
  1567. - If you find no suitable listings, return {"jobs":[]} — still valid JSON only.
  1568. Keep each description to one sentence; prefer real listing URLs; at most 8 jobs.
  1569. """
  1570. let payload = OpenAIResponsesRequest(
  1571. model: "gpt-4o-mini",
  1572. input: instructions,
  1573. tools: [OpenAIResponsesTool(type: "web_search_preview")]
  1574. )
  1575. do {
  1576. request.httpBody = try JSONEncoder().encode(payload)
  1577. } catch {
  1578. completion(.failure(error))
  1579. return
  1580. }
  1581. session.dataTask(with: request) { data, response, error in
  1582. if let error {
  1583. completion(.failure(error))
  1584. return
  1585. }
  1586. guard let data else {
  1587. completion(.failure(NSError(
  1588. domain: "OpenAIJobSearchService",
  1589. code: 2,
  1590. userInfo: [NSLocalizedDescriptionKey: "API returned an empty response."]
  1591. )))
  1592. return
  1593. }
  1594. if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
  1595. if let apiError = try? JSONDecoder().decode(OpenAIAPIErrorResponse.self, from: data) {
  1596. completion(.failure(NSError(
  1597. domain: "OpenAIJobSearchService",
  1598. code: http.statusCode,
  1599. userInfo: [NSLocalizedDescriptionKey: apiError.error.message]
  1600. )))
  1601. } else {
  1602. completion(.failure(NSError(
  1603. domain: "OpenAIJobSearchService",
  1604. code: http.statusCode,
  1605. userInfo: [NSLocalizedDescriptionKey: "Job search request failed with status \(http.statusCode)."]
  1606. )))
  1607. }
  1608. return
  1609. }
  1610. do {
  1611. let modelText = try Self.extractModelTextFromResponsesBody(data)
  1612. let trimmed = modelText.trimmingCharacters(in: .whitespacesAndNewlines)
  1613. guard !trimmed.isEmpty else {
  1614. throw NSError(
  1615. domain: "OpenAIJobSearchService",
  1616. code: 4,
  1617. userInfo: [NSLocalizedDescriptionKey: "The API returned an empty text payload."]
  1618. )
  1619. }
  1620. let jobs = try Self.parseJobListings(fromModelText: trimmed)
  1621. completion(.success(JobSearchOutput(jobs: jobs)))
  1622. } catch {
  1623. completion(.failure(error))
  1624. }
  1625. }.resume()
  1626. }
  1627. /// Walks the `/v1/responses` JSON without strict Codable so tool calls, refusals, and future output item types do not break decoding. Collects only `output_text` segments from assistant `message` items (and any other output items that expose a `content` array).
  1628. private static func extractModelTextFromResponsesBody(_ data: Data) throws -> String {
  1629. let rootObject: Any
  1630. do {
  1631. rootObject = try JSONSerialization.jsonObject(with: data, options: [])
  1632. } catch {
  1633. throw NSError(
  1634. domain: "OpenAIJobSearchService",
  1635. code: 5,
  1636. userInfo: [NSLocalizedDescriptionKey: "The job search service returned data that was not valid JSON."]
  1637. )
  1638. }
  1639. guard let root = rootObject as? [String: Any] else {
  1640. throw NSError(
  1641. domain: "OpenAIJobSearchService",
  1642. code: 5,
  1643. userInfo: [NSLocalizedDescriptionKey: "Unexpected response shape from the job search service."]
  1644. )
  1645. }
  1646. if let status = root["status"] as? String {
  1647. if status == "failed" {
  1648. let message = (root["error"] as? [String: Any])?["message"] as? String ?? "The search request failed."
  1649. throw NSError(domain: "OpenAIJobSearchService", code: 7, userInfo: [NSLocalizedDescriptionKey: message])
  1650. }
  1651. if status == "incomplete",
  1652. let details = root["incomplete_details"] as? [String: Any],
  1653. let reason = details["reason"] as? String {
  1654. throw NSError(
  1655. domain: "OpenAIJobSearchService",
  1656. code: 8,
  1657. userInfo: [NSLocalizedDescriptionKey: "Search stopped early (\(reason)). Try a simpler query or try again."]
  1658. )
  1659. }
  1660. }
  1661. if let direct = root["output_text"] as? String {
  1662. let trimmed = direct.trimmingCharacters(in: .whitespacesAndNewlines)
  1663. if !trimmed.isEmpty { return trimmed }
  1664. }
  1665. guard let output = root["output"] as? [Any] else {
  1666. throw NSError(
  1667. domain: "OpenAIJobSearchService",
  1668. code: 9,
  1669. userInfo: [NSLocalizedDescriptionKey: "The search service returned no assistant text. Try again in a moment."]
  1670. )
  1671. }
  1672. var segments: [String] = []
  1673. for case let item as [String: Any] in output where (item["type"] as? String) == "message" {
  1674. collectOutputTextSegments(fromOutputItem: item, into: &segments)
  1675. }
  1676. if segments.isEmpty {
  1677. for case let item as [String: Any] in output {
  1678. collectOutputTextSegments(fromOutputItem: item, into: &segments)
  1679. }
  1680. }
  1681. let combined = segments.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
  1682. if !combined.isEmpty {
  1683. return combined
  1684. }
  1685. throw NSError(
  1686. domain: "OpenAIJobSearchService",
  1687. code: 9,
  1688. userInfo: [NSLocalizedDescriptionKey: "The model did not return readable job-search text. Try again."]
  1689. )
  1690. }
  1691. private static func collectOutputTextSegments(fromOutputItem item: [String: Any], into segments: inout [String]) {
  1692. guard let content = item["content"] as? [Any] else { return }
  1693. for case let part as [String: Any] in content {
  1694. guard (part["type"] as? String) == "output_text" else { continue }
  1695. if let s = part["text"] as? String {
  1696. segments.append(s)
  1697. } else if let nested = part["text"] as? [String: Any], let value = nested["value"] as? String {
  1698. segments.append(value)
  1699. }
  1700. }
  1701. }
  1702. private static func parseJobListings(fromModelText text: String) throws -> [JobListing] {
  1703. let jsonString = extractJobJSONObjectString(from: text) ?? extractJSONObject(from: text)
  1704. let jsonData = Data(jsonString.utf8)
  1705. if let payload = try? JSONDecoder().decode(JobSearchResultsPayload.self, from: jsonData) {
  1706. return payload.jobs
  1707. }
  1708. if let listings = try? JSONDecoder().decode([JobListing].self, from: jsonData) {
  1709. return listings
  1710. }
  1711. if let obj = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
  1712. if let dict = obj as? [String: Any], let jobs = jobListings(fromFlexibleJSONObject: dict) {
  1713. return jobs
  1714. }
  1715. if let arr = obj as? [[String: Any]], let jobs = jobListings(fromFlexibleJobArray: arr) {
  1716. return jobs
  1717. }
  1718. }
  1719. throw NSError(
  1720. domain: "OpenAIJobSearchService",
  1721. code: 10,
  1722. userInfo: [NSLocalizedDescriptionKey: "The assistant reply did not include job listings in the expected JSON format. Try your search again."]
  1723. )
  1724. }
  1725. private static func jobListings(fromFlexibleJSONObject dict: [String: Any]) -> [JobListing]? {
  1726. for (key, value) in dict {
  1727. guard key.caseInsensitiveCompare("jobs") == .orderedSame, let arr = value as? [[String: Any]] else { continue }
  1728. if let jobs = jobListings(fromFlexibleJobArray: arr) { return jobs }
  1729. }
  1730. for wrapKey in ["data", "result", "results", "payload"] {
  1731. if let inner = dict[wrapKey] as? [String: Any], let nested = jobListings(fromFlexibleJSONObject: inner) {
  1732. return nested
  1733. }
  1734. }
  1735. return nil
  1736. }
  1737. private static func jobListings(fromFlexibleJobArray jobs: [[String: Any]]) -> [JobListing]? {
  1738. var out: [JobListing] = []
  1739. for item in jobs {
  1740. guard let title = firstString(valuesForKeys: ["title", "job_title", "name", "position"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines),
  1741. !title.isEmpty,
  1742. let desc = firstString(valuesForKeys: ["description", "snippet", "summary", "desc"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines),
  1743. !desc.isEmpty else { continue }
  1744. let urlRaw = firstString(valuesForKeys: ["url", "link", "apply_url", "job_url"], in: item)?.trimmingCharacters(in: .whitespacesAndNewlines)
  1745. let url: String? = (urlRaw?.isEmpty == true) ? nil : urlRaw
  1746. out.append(JobListing(title: title, description: desc, url: url))
  1747. }
  1748. return out.isEmpty ? nil : out
  1749. }
  1750. private static func firstString(valuesForKeys keys: [String], in dict: [String: Any]) -> String? {
  1751. for wanted in keys {
  1752. for (dk, dv) in dict {
  1753. guard dk.caseInsensitiveCompare(wanted) == .orderedSame, let s = dv as? String else { continue }
  1754. return s
  1755. }
  1756. }
  1757. return nil
  1758. }
  1759. private static func stripMarkdownCodeFence(_ text: String) -> String {
  1760. var s = text.trimmingCharacters(in: .whitespacesAndNewlines)
  1761. guard s.hasPrefix("```") else { return s }
  1762. s.removeFirst(3)
  1763. if s.lowercased().hasPrefix("json") {
  1764. s.removeFirst(4)
  1765. }
  1766. s = s.trimmingCharacters(in: .whitespacesAndNewlines)
  1767. if let fence = s.range(of: "```", options: .backwards) {
  1768. s = String(s[..<fence.lowerBound])
  1769. }
  1770. return s.trimmingCharacters(in: .whitespacesAndNewlines)
  1771. }
  1772. private static func balancedJSONObject(from openBrace: String.Index, in s: String) -> String? {
  1773. var depth = 0
  1774. var inString = false
  1775. var escaped = false
  1776. var i = openBrace
  1777. while i < s.endIndex {
  1778. let ch = s[i]
  1779. if inString {
  1780. if escaped {
  1781. escaped = false
  1782. } else if ch == "\\" {
  1783. escaped = true
  1784. } else if ch == "\"" {
  1785. inString = false
  1786. }
  1787. } else {
  1788. switch ch {
  1789. case "\"":
  1790. inString = true
  1791. case "{":
  1792. depth += 1
  1793. case "}":
  1794. depth -= 1
  1795. if depth == 0 {
  1796. return String(s[openBrace...i])
  1797. }
  1798. default:
  1799. break
  1800. }
  1801. }
  1802. i = s.index(after: i)
  1803. }
  1804. return nil
  1805. }
  1806. /// Prefers the JSON object that contains a `"jobs"` key so prose before/after the payload does not confuse the decoder.
  1807. private static func extractJobJSONObjectString(from text: String) -> String? {
  1808. let s = stripMarkdownCodeFence(text)
  1809. guard let jobsRange = s.range(of: "\"jobs\"", options: .caseInsensitive) else { return nil }
  1810. let head = s[..<jobsRange.lowerBound]
  1811. guard let open = head.lastIndex(of: "{") else { return nil }
  1812. return balancedJSONObject(from: open, in: s)
  1813. }
  1814. private static func extractJSONObject(from text: String) -> String {
  1815. if let extracted = extractJobJSONObjectString(from: text) {
  1816. return extracted
  1817. }
  1818. let stripped = stripMarkdownCodeFence(text)
  1819. if let first = stripped.firstIndex(of: "{"), let balanced = balancedJSONObject(from: first, in: stripped) {
  1820. return balanced
  1821. }
  1822. if let range = text.range(of: "\\{[\\s\\S]*\\}", options: .regularExpression) {
  1823. return String(text[range])
  1824. }
  1825. return text
  1826. }
  1827. }
  1828. private struct OpenAIResponsesRequest: Codable {
  1829. let model: String
  1830. let input: String
  1831. let tools: [OpenAIResponsesTool]
  1832. }
  1833. private struct OpenAIResponsesTool: Codable {
  1834. let type: String
  1835. }
  1836. private struct JobSearchResultsPayload: Codable {
  1837. let jobs: [JobListing]
  1838. }
  1839. private struct JobSearchOutput {
  1840. let jobs: [JobListing]
  1841. }
  1842. private struct OpenAIAPIErrorResponse: Codable {
  1843. let error: APIError
  1844. struct APIError: Codable {
  1845. let message: String
  1846. }
  1847. }
  1848. /// `NSButton` that carries a `JobListing` for card actions (`representedObject` is unavailable on `NSButton` in this target).
  1849. private final class JobPayloadButton: HoverableButton {
  1850. var jobPayload: JobListing?
  1851. var cardContext: JobListingCardContext = .homeSearchResults
  1852. }
  1853. /// `NSButton` with a tracking area that reports hover transitions and (optionally) swaps in a pointing-hand cursor while hovered.
  1854. private class HoverableButton: NSButton {
  1855. var hoverHandler: ((Bool) -> Void)?
  1856. var pointerCursor: Bool = false
  1857. private(set) var isHovering: Bool = false
  1858. private var trackingArea: NSTrackingArea?
  1859. private var didPushCursor: Bool = false
  1860. override func updateTrackingAreas() {
  1861. super.updateTrackingAreas()
  1862. if let area = trackingArea { removeTrackingArea(area) }
  1863. let area = NSTrackingArea(
  1864. rect: bounds,
  1865. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1866. owner: self,
  1867. userInfo: nil
  1868. )
  1869. addTrackingArea(area)
  1870. trackingArea = area
  1871. }
  1872. override func mouseEntered(with event: NSEvent) {
  1873. super.mouseEntered(with: event)
  1874. isHovering = true
  1875. hoverHandler?(true)
  1876. if pointerCursor, !didPushCursor {
  1877. NSCursor.pointingHand.push()
  1878. didPushCursor = true
  1879. }
  1880. }
  1881. override func mouseExited(with event: NSEvent) {
  1882. super.mouseExited(with: event)
  1883. isHovering = false
  1884. hoverHandler?(false)
  1885. if didPushCursor {
  1886. NSCursor.pop()
  1887. didPushCursor = false
  1888. }
  1889. }
  1890. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1891. super.viewWillMove(toWindow: newWindow)
  1892. // Guard against an unbalanced cursor stack if the button is removed mid-hover (e.g. job card replaced after a search).
  1893. if newWindow == nil, didPushCursor {
  1894. NSCursor.pop()
  1895. didPushCursor = false
  1896. isHovering = false
  1897. }
  1898. }
  1899. }
  1900. /// `NSView` companion to `HoverableButton`: emits hover transitions and can manage a pointing-hand cursor. Used to track hover over composite controls like the gradient "Find jobs" pill.
  1901. private class HoverableView: NSView {
  1902. var hoverHandler: ((Bool) -> Void)?
  1903. var pointerCursor: Bool = false
  1904. private(set) var isHovering: Bool = false
  1905. private var trackingArea: NSTrackingArea?
  1906. private var didPushCursor: Bool = false
  1907. override func updateTrackingAreas() {
  1908. super.updateTrackingAreas()
  1909. if let area = trackingArea { removeTrackingArea(area) }
  1910. let area = NSTrackingArea(
  1911. rect: bounds,
  1912. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1913. owner: self,
  1914. userInfo: nil
  1915. )
  1916. addTrackingArea(area)
  1917. trackingArea = area
  1918. }
  1919. override func mouseEntered(with event: NSEvent) {
  1920. super.mouseEntered(with: event)
  1921. isHovering = true
  1922. hoverHandler?(true)
  1923. if pointerCursor, !didPushCursor {
  1924. NSCursor.pointingHand.push()
  1925. didPushCursor = true
  1926. }
  1927. }
  1928. override func mouseExited(with event: NSEvent) {
  1929. super.mouseExited(with: event)
  1930. isHovering = false
  1931. hoverHandler?(false)
  1932. if didPushCursor {
  1933. NSCursor.pop()
  1934. didPushCursor = false
  1935. }
  1936. }
  1937. override func viewWillMove(toWindow newWindow: NSWindow?) {
  1938. super.viewWillMove(toWindow: newWindow)
  1939. if newWindow == nil, didPushCursor {
  1940. NSCursor.pop()
  1941. didPushCursor = false
  1942. isHovering = false
  1943. }
  1944. }
  1945. }
  1946. /// Document view for the job list `NSScrollView`; flipped coordinates keep short result sets aligned to the top of the clip (avoids a large empty band above the cards on macOS).
  1947. private final class JobListingsDocumentView: NSView {
  1948. override var isFlipped: Bool { true }
  1949. }
  1950. /// Marker subclass for the per-assistant-message job stack embedded inside a chat bubble. `NSView.tag` is read-only on macOS, so a typed subclass is the cleanest way to identify these stacks during dismiss and layout passes.
  1951. private final class ChatJobsStackView: NSStackView {}
  1952. /// Marker subclass for the wrapping label inside a chat bubble. Lets the layout pass find each bubble label to update its `preferredMaxLayoutWidth` when the chat width changes.
  1953. private final class ChatBubbleLabel: NSTextField {}
  1954. /// Captures clicks for the full sidebar pill so icon, label, and padding behave as one tab. Manages its own hover background so non-selected rows highlight subtly on hover without disturbing the selected-row fill.
  1955. private final class SidebarNavRowView: NSView {
  1956. private let onSelect: () -> Void
  1957. var restingBackgroundColor: NSColor? {
  1958. didSet { applyBackground() }
  1959. }
  1960. var hoverBackgroundColor: NSColor?
  1961. private var isHovering: Bool = false
  1962. private var didPushCursor: Bool = false
  1963. init(onSelect: @escaping () -> Void) {
  1964. self.onSelect = onSelect
  1965. super.init(frame: .zero)
  1966. }
  1967. @available(*, unavailable)
  1968. required init?(coder: NSCoder) {
  1969. fatalError("init(coder:) has not been implemented")
  1970. }
  1971. override func hitTest(_ point: NSPoint) -> NSView? {
  1972. guard let superview else { return super.hitTest(point) }
  1973. let local = convert(point, from: superview)
  1974. return bounds.contains(local) ? self : nil
  1975. }
  1976. override func mouseDown(with event: NSEvent) {
  1977. onSelect()
  1978. }
  1979. override func updateTrackingAreas() {
  1980. super.updateTrackingAreas()
  1981. trackingAreas.forEach { removeTrackingArea($0) }
  1982. addTrackingArea(NSTrackingArea(
  1983. rect: bounds,
  1984. options: [.activeInKeyWindow, .mouseEnteredAndExited, .inVisibleRect],
  1985. owner: self,
  1986. userInfo: nil
  1987. ))
  1988. }
  1989. override func mouseEntered(with event: NSEvent) {
  1990. super.mouseEntered(with: event)
  1991. isHovering = true
  1992. applyBackground()
  1993. if !didPushCursor {
  1994. NSCursor.pointingHand.push()
  1995. didPushCursor = true
  1996. }
  1997. }
  1998. override func mouseExited(with event: NSEvent) {
  1999. super.mouseExited(with: event)
  2000. isHovering = false
  2001. applyBackground()
  2002. if didPushCursor {
  2003. NSCursor.pop()
  2004. didPushCursor = false
  2005. }
  2006. }
  2007. override func viewWillMove(toWindow newWindow: NSWindow?) {
  2008. super.viewWillMove(toWindow: newWindow)
  2009. if newWindow == nil, didPushCursor {
  2010. NSCursor.pop()
  2011. didPushCursor = false
  2012. isHovering = false
  2013. }
  2014. }
  2015. private func applyBackground() {
  2016. let color = isHovering ? (hoverBackgroundColor ?? restingBackgroundColor) : restingBackgroundColor
  2017. layer?.backgroundColor = color?.cgColor
  2018. }
  2019. }