repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
Odin
github_2023
others
83
odtheking
freebonsai
@@ -115,4 +127,14 @@ object EtherWarpHelper : Module( smoothRotateTo(yaw, pitch, rotTime) } } + + @SubscribeEvent + fun onSoundPacket(event: PacketReceivedEvent) { + with(event.packet) { + if (this !is S29PacketSoundEffect || soundName != "mob.enderdragon.hit" || !sounds || volume != 1f || pitch != 0.53968257f || customSound == "mob.enderdragon.hit") return + val packet = S29PacketSoundEffect("minecraft:${if (sound == defaultSounds.size - 1) customSound else defaultSounds[sound]}", x, y, z, soundVolume, soundPitch) + mc.addScheduledTask { mc.netHandler.handleSoundEffect(packet) } + event.isCanceled = true + }
what the fuck pt. 2
Odin
github_2023
others
83
odtheking
freebonsai
@@ -16,13 +17,14 @@ import net.minecraft.tileentity.TileEntitySkull import net.minecraft.util.BlockPos import net.minecraftforge.event.world.WorldEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent +import java.util.concurrent.CopyOnWriteArrayList import kotlin.math.ceil import kotlin.math.floor object DungeonUtils { inline val inDungeons: Boolean get() = - LocationUtils.currentArea.isArea(Island.Dungeon) + LocationUtils.currentArea.isArea(Island.Dungeon) || LocationUtils.currentArea.isArea(Island.SinglePlayer)
remove this before i merge
Odin
github_2023
others
83
odtheking
freebonsai
@@ -107,14 +118,31 @@ object DungeonUtils { var score = 0 score += cryptCount.coerceAtMost(5) if (mimicKilled) score += 2 - if (isPaul) score += 10 + if ((isPaul && togglePaul == 0) || togglePaul == 2) score += 10 return score } + inline val bloodDone: Boolean get() = + currentDungeon?.dungeonStats?.bloodDone ?: false + + inline val score: Int get() { + val completed: Float = completedRoomCount.toFloat() + (if (!bloodDone) 1f else 0f) + (if (!inBoss) 1f else 0f) + val total: Float = if (totalRooms != 0) totalRooms.toFloat() else 36f + + val exploration = floor((secretPercentage/floor.secretPercentage)/100f * 40f).coerceIn(0f, 40f).toInt() + + floor(completed/total * 60f).coerceIn(0f, 60f).toInt() + + val skillRooms = floor(completed/total * 80f).coerceIn(0f, 80f).toInt() + val puzzlePenalty = puzzles.filter { it.status != PuzzleStatus.Completed }.size * 10 + val skill = (20 + skillRooms - puzzlePenalty - (deathCount * 2 - 1).coerceAtLeast(0)).coerceIn(20, 100) + + return exploration + skill + getBonusScore + 100 + } + inline val neededSecretsAmount: Int get() { - val deathModifier = deathCount * 2 - 1 + val deathModifier = (deathCount * 2 - 1).coerceAtLeast(0) val scoreFactor = 40 - getBonusScore + deathModifier - return ceil(totalSecrets * scoreFactor / 40.0).toInt() + return ceil((totalSecrets * floor.secretPercentage) * scoreFactor / 40.0).toInt() }
all of these things should realistically not be in this class but its fine for now someone will refactor later
Odin
github_2023
others
80
odtheking
freebonsai
@@ -54,6 +55,17 @@ object ChocolateFactory : Module( if (!isInChocolateFactory()) return@execute if (clickFactory) windowClick(13, PlayerUtils.ClickType.Right) + + if (claimStray) { + val container = mc.thePlayer.openContainer as? ContainerChest ?: return@execute + for (slot in container.inventorySlots) {
use container.inventorySlots.find { // logic } instead
Odin
github_2023
others
76
odtheking
freebonsai
@@ -5,37 +5,31 @@ import me.odinmain.config.Config import me.odinmain.features.impl.skyblock.ChatCommands.blacklist import me.odinmain.utils.skyblock.modMessage -val blacklistCommand = commodore("blacklist") { - runs { - modMessage("Usage:\n /blacklist <add/remove> <name>\n /blacklist <clear/list>") - } - +val chatCommandsCommand = commodore("chatcommandslist", "cclist", "chatclist", "ccommandslist") { literal("add").runs { name: String -> val lowercase = name.lowercase() - if (lowercase in blacklist) return@runs modMessage("$name is already in the Blacklist.") - - modMessage("Added $name to Blacklist.") + if (lowercase in blacklist) return@runs modMessage("$name is already in the list.") + modMessage("Added $name to list.") blacklist.add(lowercase) Config.save() } literal("remove").runs { name: String -> val lowercase = name.lowercase() - if (lowercase !in blacklist) return@runs modMessage("$name isn't in the Blacklist.") - - modMessage("Removed $name from Blacklist.") + if (lowercase !in blacklist) return@runs modMessage("$name isn't in the list.") + modMessage("Removed $name from list.") blacklist.remove(lowercase) Config.save() } literal("clear").runs { - modMessage("Blacklist cleared.") + modMessage("list cleared.") blacklist.clear() Config.save() } literal("list").runs { - if (blacklist.size == 0) return@runs modMessage("Blacklist is empty") - modMessage("Blacklist:\n${blacklist.joinToString("\n")}") + if (blacklist.size == 0) return@runs modMessage("list is empty") + modMessage("list:\n${blacklist.joinToString("\n")}") } -} +}
fix capitilization in these messages
Odin
github_2023
others
78
odtheking
freebonsai
@@ -64,21 +74,92 @@ object DungeonWaypoints : Module( val filled: Boolean, val depth: Boolean, val aabb: AxisAlignedBB, - val title: String? + val title: String?, + val secret: Boolean, + var clicked: Boolean = false ) override fun onKeybind() { allowEdits = !allowEdits modMessage("Dungeon Waypoint editing ${if (allowEdits) "§aenabled" else "§cdisabled"}§r!") } + private val secretEntities = mutableMapOf<Int, Vec3>() + + private val drops = listOf( + "Health Potion VIII Splash Potion", "Healing Potion 8 Splash Potion", "Healing Potion VIII Splash Potion", + "Decoy", "Inflatable Jerry", "Spirit Leap", "Trap", "Training Weights", "Defuse Kit", "Dungeon Chest Key", "Treasure Talisman", "Revive Stone", + ) + + fun resetSecrets() { + val room = DungeonUtils.currentRoom + for ((_, waypointsList) in DungeonWaypointConfigCLAY.waypoints.filter { waypoints -> waypoints.value.any { it.clicked } }) { + waypointsList.filter { it.clicked }.forEach { it.clicked = false } + } + + if (room != null) DungeonUtils.setWaypoints(room) + glList = -1 + secretEntities.clear() + } + + init { + onWorldLoad { + resetSecrets() + } + + onMessage(Regex("(?s).*(\\d+)/\\1 Secrets.*")) {
What is this?
Odin
github_2023
others
78
odtheking
freebonsai
@@ -64,21 +74,92 @@ object DungeonWaypoints : Module( val filled: Boolean, val depth: Boolean, val aabb: AxisAlignedBB, - val title: String? + val title: String?, + val secret: Boolean, + var clicked: Boolean = false ) override fun onKeybind() { allowEdits = !allowEdits modMessage("Dungeon Waypoint editing ${if (allowEdits) "§aenabled" else "§cdisabled"}§r!") } + private val secretEntities = mutableMapOf<Int, Vec3>() + + private val drops = listOf( + "Health Potion VIII Splash Potion", "Healing Potion 8 Splash Potion", "Healing Potion VIII Splash Potion", + "Decoy", "Inflatable Jerry", "Spirit Leap", "Trap", "Training Weights", "Defuse Kit", "Dungeon Chest Key", "Treasure Talisman", "Revive Stone", + ) + + fun resetSecrets() { + val room = DungeonUtils.currentRoom + for ((_, waypointsList) in DungeonWaypointConfigCLAY.waypoints.filter { waypoints -> waypoints.value.any { it.clicked } }) { + waypointsList.filter { it.clicked }.forEach { it.clicked = false } + } + + if (room != null) DungeonUtils.setWaypoints(room) + glList = -1 + secretEntities.clear() + } + + init { + onWorldLoad { + resetSecrets() + } + + onMessage(Regex("(?s).*(\\d+)/\\1 Secrets.*")) { + val room = DungeonUtils.currentRoom ?: return@onMessage + val waypoints = DungeonWaypointConfigCLAY.waypoints.getOrPut(room.room.data.name) { mutableListOf() } + if (waypoints.any { it.secret && !it.clicked}) { + for (wp in waypoints.filter { it.secret && !it.clicked }) { wp.clicked = true } + DungeonUtils.setWaypoints(room) + glList = -1 + } + } + } + + @SubscribeEvent + fun onMetaData(event: PostEntityMetadata) { + val entity = mc.theWorld.getEntityByID(event.packet.entityId) ?: return + if (entity is EntityItem && entity.entityItem.displayName.noControlCodes.containsOneOf(drops, true) && DungeonUtils.inDungeons) { + secretEntities[event.packet.entityId] = entity.positionVector + } + } + + @SubscribeEvent + fun onEntityJoinWorldEvent(event: EntityJoinWorldEvent) { + if (event.entity is EntityBat && DungeonUtils.inDungeons) { + secretEntities[event.entity.entityId] = event.entity.positionVector + } + } + + @SubscribeEvent + fun onEntityLeaveWorld(event: EntityLeaveWorldEvent) { + val pos = secretEntities[event.entity.entityId] ?: return + if ((event.entity is EntityItem && event.entity.entityItem.displayName.noControlCodes.containsOneOf(drops, true)) || event.entity is EntityBat) { + clickSecret(pos, 3) + } + }
these three events are so chaotic, try to either use something to merge the detection with secret chime, or atleast use the same logic as it
Odin
github_2023
others
78
odtheking
freebonsai
@@ -41,6 +43,7 @@ class Dungeon { } private fun getCurrentFloor() { + if (currentArea.isArea(Island.SinglePlayer)) { runCatching { floor = Floor.E } }
why runCatching? thats only needed for scoreboard substring functions
Odin
github_2023
others
78
odtheking
freebonsai
@@ -0,0 +1,59 @@ +package me.odinmain.features.impl.dungeon.dungeonwaypoints + +import me.odinmain.config.DungeonWaypointConfigCLAY +import me.odinmain.events.impl.SecretPickupEvent +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.glList +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.setWaypoints +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.toVec3 +import me.odinmain.utils.equal +import me.odinmain.utils.pos +import me.odinmain.utils.rotateToNorth +import me.odinmain.utils.skyblock.devMessage +import me.odinmain.utils.skyblock.dungeon.DungeonUtils +import me.odinmain.utils.skyblock.dungeon.ScanUtils +import me.odinmain.utils.subtractVec +import net.minecraft.util.Vec3 + +object SecretWaypoints { + + fun onSecret(event: SecretPickupEvent) { + when (event) { + is SecretPickupEvent.Interact -> clickSecret(Vec3(event.blockPos), 0) + is SecretPickupEvent.Bat -> clickSecret(event.packet.pos, 5) + is SecretPickupEvent.Item -> clickSecret(event.entity.positionVector, 3) + } + } + + private fun clickSecret(pos: Vec3, distance: Int) { + val room = DungeonUtils.currentRoom ?: return + val vec = Vec3(pos.xCoord, pos.yCoord, pos.zCoord).subtractVec(x = room.clayPos.x, z = room.clayPos.z).rotateToNorth(room.room.rotation) + val waypoints = DungeonWaypointConfigCLAY.waypoints.getOrPut(room.room.data.name) { mutableListOf() } + waypoints.find { wp -> (if (distance == 0) wp.toVec3().equal(vec) else wp.toVec3().distanceTo(vec) <= distance) && wp.secret && !wp.clicked}?.let { + it.clicked = true + setWaypoints(room) + devMessage("clicked ${it.toVec3()}") + glList = -1 + } + } + + fun resetSecrets() { + val room = DungeonUtils.currentRoom + for ((_, waypointsList) in DungeonWaypointConfigCLAY.waypoints.filter { waypoints -> waypoints.value.any { it.clicked } }) {
you could do .filter { //logic }.values instead of having to do (_, waypointsList)
Odin
github_2023
others
78
odtheking
freebonsai
@@ -0,0 +1,59 @@ +package me.odinmain.features.impl.dungeon.dungeonwaypoints + +import me.odinmain.config.DungeonWaypointConfigCLAY +import me.odinmain.events.impl.SecretPickupEvent +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.glList +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.setWaypoints +import me.odinmain.features.impl.dungeon.dungeonwaypoints.DungeonWaypoints.toVec3 +import me.odinmain.utils.equal +import me.odinmain.utils.pos +import me.odinmain.utils.rotateToNorth +import me.odinmain.utils.skyblock.devMessage +import me.odinmain.utils.skyblock.dungeon.DungeonUtils +import me.odinmain.utils.skyblock.dungeon.ScanUtils +import me.odinmain.utils.subtractVec +import net.minecraft.util.Vec3 + +object SecretWaypoints { + + fun onSecret(event: SecretPickupEvent) { + when (event) { + is SecretPickupEvent.Interact -> clickSecret(Vec3(event.blockPos), 0) + is SecretPickupEvent.Bat -> clickSecret(event.packet.pos, 5) + is SecretPickupEvent.Item -> clickSecret(event.entity.positionVector, 3) + } + } + + private fun clickSecret(pos: Vec3, distance: Int) { + val room = DungeonUtils.currentRoom ?: return + val vec = Vec3(pos.xCoord, pos.yCoord, pos.zCoord).subtractVec(x = room.clayPos.x, z = room.clayPos.z).rotateToNorth(room.room.rotation) + val waypoints = DungeonWaypointConfigCLAY.waypoints.getOrPut(room.room.data.name) { mutableListOf() } + waypoints.find { wp -> (if (distance == 0) wp.toVec3().equal(vec) else wp.toVec3().distanceTo(vec) <= distance) && wp.secret && !wp.clicked}?.let { + it.clicked = true + setWaypoints(room) + devMessage("clicked ${it.toVec3()}") + glList = -1 + } + } + + fun resetSecrets() { + val room = DungeonUtils.currentRoom + for ((_, waypointsList) in DungeonWaypointConfigCLAY.waypoints.filter { waypoints -> waypoints.value.any { it.clicked } }) { + waypointsList.filter { it.clicked }.forEach { it.clicked = false } + } + + if (room != null) setWaypoints(room) + glList = -1 + } + + fun clearSecrets() { + val room = DungeonUtils.currentRoom ?: return + val waypoints = DungeonWaypointConfigCLAY.waypoints.getOrPut(room.room.data.name) { mutableListOf() }
could make this a function since its done a lot in DungeonWaypoints.kt too
Odin
github_2023
others
78
odtheking
freebonsai
@@ -43,6 +43,16 @@ object ClickedSecrets : Module( } } + @SubscribeEvent + fun onSecret(event: SecretPickupEvent.Interact) { + if ((DungeonUtils.inBoss && disableInBoss) || secrets.any{ it.pos == event.blockPos }) return
MISSING A SPACE OMG
Odin
github_2023
others
78
odtheking
freebonsai
@@ -1,24 +1,62 @@ package me.odinmain.events import kotlinx.coroutines.* +import me.odinmain.OdinMain.mc import me.odinmain.events.impl.* import me.odinmain.utils.* import me.odinmain.utils.clock.Clock +import me.odinmain.utils.skyblock.dungeon.DungeonUtils.inDungeons +import me.odinmain.utils.skyblock.dungeon.DungeonUtils.isSecret +import net.minecraft.block.state.IBlockState import net.minecraft.client.gui.inventory.GuiChest +import net.minecraft.entity.item.EntityItem +import net.minecraft.entity.passive.EntityBat import net.minecraft.inventory.ContainerChest +import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement import net.minecraft.network.play.server.S02PacketChat +import net.minecraft.network.play.server.S29PacketSoundEffect import net.minecraft.network.play.server.S32PacketConfirmTransaction +import net.minecraft.util.BlockPos import net.minecraftforge.client.event.GuiOpenEvent import net.minecraftforge.client.event.RenderWorldLastEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object EventDispatcher { + + private val drops = listOf( + "Health Potion VIII Splash Potion", "Healing Potion 8 Splash Potion", "Healing Potion VIII Splash Potion", "Healing VIII Splash Potion", + "Decoy", "Inflatable Jerry", "Spirit Leap", "Trap", "Training Weights", "Defuse Kit", "Dungeon Chest Key", "Treasure Talisman", "Revive Stone", + ) + + /** + * Dispatches [SecretPickupEvent.Item] + */ + @SubscribeEvent + fun onRemoveEntity(event: EntityLeaveWorldEvent) { + if (!inDungeons) return + if (event.entity is EntityItem && event.entity.entityItem.displayName.noControlCodes.containsOneOf(drops, true)) SecretPickupEvent.Item(event.entity).postAndCatch()
merge the if statements so there is only one with a return
Odin
github_2023
others
78
odtheking
freebonsai
@@ -1,24 +1,62 @@ package me.odinmain.events import kotlinx.coroutines.* +import me.odinmain.OdinMain.mc import me.odinmain.events.impl.* import me.odinmain.utils.* import me.odinmain.utils.clock.Clock +import me.odinmain.utils.skyblock.dungeon.DungeonUtils.inDungeons +import me.odinmain.utils.skyblock.dungeon.DungeonUtils.isSecret +import net.minecraft.block.state.IBlockState import net.minecraft.client.gui.inventory.GuiChest +import net.minecraft.entity.item.EntityItem +import net.minecraft.entity.passive.EntityBat import net.minecraft.inventory.ContainerChest +import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement import net.minecraft.network.play.server.S02PacketChat +import net.minecraft.network.play.server.S29PacketSoundEffect import net.minecraft.network.play.server.S32PacketConfirmTransaction +import net.minecraft.util.BlockPos import net.minecraftforge.client.event.GuiOpenEvent import net.minecraftforge.client.event.RenderWorldLastEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object EventDispatcher { + + private val drops = listOf( + "Health Potion VIII Splash Potion", "Healing Potion 8 Splash Potion", "Healing Potion VIII Splash Potion", "Healing VIII Splash Potion", + "Decoy", "Inflatable Jerry", "Spirit Leap", "Trap", "Training Weights", "Defuse Kit", "Dungeon Chest Key", "Treasure Talisman", "Revive Stone", + ) + + /** + * Dispatches [SecretPickupEvent.Item] + */ + @SubscribeEvent + fun onRemoveEntity(event: EntityLeaveWorldEvent) { + if (!inDungeons) return + if (event.entity is EntityItem && event.entity.entityItem.displayName.noControlCodes.containsOneOf(drops, true)) SecretPickupEvent.Item(event.entity).postAndCatch() + } + /** - * Dispatches [ChatPacketEvent] and [RealServerTick]. + * Dispatches [SecretPickupEvent.Interact] + */ + @SubscribeEvent + fun onPacket(event: PacketSentEvent) { + if (!inDungeons) return + val packet = event.packet
use with(event.packet) {} that gives you the packet as _this_ instead of it being a variable, this should be done other places in the mod too but here for now.
Odin
github_2023
others
50
odtheking
freebonsai
@@ -0,0 +1,52 @@ +package me.odinmain.commands.impl + +import me.odinmain.OdinMain.mc +import me.odinmain.commands.commodore +import me.odinmain.config.Config +import me.odinmain.features.impl.skyblock.PetKeybinds.petList +import me.odinmain.utils.skyblock.itemID +import me.odinmain.utils.skyblock.modMessage +import me.odinmain.utils.skyblock.uuid + +val petCommand = commodore("petkeys") { + + literal("add").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("You can only add pets to the pet list!")
just do this in the assignment of the variable
Odin
github_2023
others
50
odtheking
freebonsai
@@ -0,0 +1,52 @@ +package me.odinmain.commands.impl + +import me.odinmain.OdinMain.mc +import me.odinmain.commands.commodore +import me.odinmain.config.Config +import me.odinmain.features.impl.skyblock.PetKeybinds.petList +import me.odinmain.utils.skyblock.itemID +import me.odinmain.utils.skyblock.modMessage +import me.odinmain.utils.skyblock.uuid + +val petCommand = commodore("petkeys") { + + literal("add").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("You can only add pets to the pet list!") + if (petList.size >= 9) return@runs modMessage("You cannot add more than 9 pets to the list. Remove a pet using /petkeys remove or clear the list using /petkeys clear.") + if (petID in petList) return@runs modMessage("This pet is already in the list!") + + petList.add(petID) + modMessage("Added this pet to the pet list in position ${petList.indexOf(petID) +1}!") + Config.save() + } + + literal("petpos").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("This is not a pet!")
again
Odin
github_2023
others
50
odtheking
freebonsai
@@ -0,0 +1,52 @@ +package me.odinmain.commands.impl + +import me.odinmain.OdinMain.mc +import me.odinmain.commands.commodore +import me.odinmain.config.Config +import me.odinmain.features.impl.skyblock.PetKeybinds.petList +import me.odinmain.utils.skyblock.itemID +import me.odinmain.utils.skyblock.modMessage +import me.odinmain.utils.skyblock.uuid + +val petCommand = commodore("petkeys") { + + literal("add").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("You can only add pets to the pet list!") + if (petList.size >= 9) return@runs modMessage("You cannot add more than 9 pets to the list. Remove a pet using /petkeys remove or clear the list using /petkeys clear.") + if (petID in petList) return@runs modMessage("This pet is already in the list!") + + petList.add(petID) + modMessage("Added this pet to the pet list in position ${petList.indexOf(petID) +1}!") + Config.save() + } + + literal("petpos").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("This is not a pet!") + if (petID !in petList) return@runs modMessage("This pet is not in the list!") + modMessage("This pet is position ${petList.indexOf(petID) +1} in the list.") + } + + literal("remove").runs { + val petID = if (mc.thePlayer?.heldItem.itemID == "PET") mc.thePlayer?.heldItem.uuid else null + if (petID == null) return@runs modMessage("This is not a pet!") + if (petID !in petList) return@runs modMessage("This pet is not in the list!") + + petList.remove(petID) + modMessage("Removed this pet from the pet list!") + Config.save() + } + + literal("clear").runs { + petList.clear() + modMessage("Cleared the pet list!") + Config.save() + } + + literal("list").runs { + if (petList.size == 0) return@runs modMessage("pet list is empty")
big P
Odin
github_2023
others
50
odtheking
freebonsai
@@ -29,6 +30,11 @@ object ItemsHighlight : Module( } private fun getEntityOutlineColor(entity: EntityItem): Color { - return getRarity(entity.entityItem.lore)?.color ?: Color.WHITE + return if (!colorStyle) getRarity(entity.entityItem.lore)?.color ?: Color.WHITE + else if (entity.getDistanceToEntity(mc.thePlayer) <= 3.5) { + Color.GREEN + } else { + Color.RED + }
do this in one line
Odin
github_2023
others
50
odtheking
freebonsai
@@ -0,0 +1,70 @@ +package me.odinmain.features.impl.skyblock + +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.Setting.Companion.withDependency +import me.odinmain.features.settings.impl.* +import me.odinmain.utils.clock.Clock +import me.odinmain.utils.name +import me.odinmain.utils.skyblock.getItemIndexInContainerChestByLore +import me.odinmain.utils.skyblock.getItemIndexInContainerChestByUUID +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.client.gui.inventory.GuiChest +import net.minecraft.inventory.ContainerChest +import net.minecraftforge.client.event.GuiScreenEvent +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent +import org.lwjgl.input.Keyboard + +object PetKeybinds : Module( + "Pet Keybinds", + description = "keybinds for pets (/petkeys)", + category = Category.SKYBLOCK +) { + private val unequipKeybind: Keybinding by KeybindSetting("Unequip Keybind", Keyboard.KEY_NONE, "Unequips the current Pet.") + private val nextPageKeybind: Keybinding by KeybindSetting("Next Page Keybind", Keyboard.KEY_NONE, "Goes to the next page.") + private val previousPageKeybind: Keybinding by KeybindSetting("Previous Page Keybind", Keyboard.KEY_NONE, "Goes to the previous page.") + private val delay: Long by NumberSetting("Delay", 0, 0.0, 10000.0, 10.0, description = "The delay between each click .") + private val advanced: Boolean by DropdownSetting("Show Settings", false) + + private val pet1: Keybinding by KeybindSetting("Pet 1", Keyboard.KEY_1, "Pet 1 on the list.").withDependency { advanced } + private val pet2: Keybinding by KeybindSetting("Pet 2", Keyboard.KEY_2, "Pet 2 on the list.").withDependency { advanced } + private val pet3: Keybinding by KeybindSetting("Pet 3", Keyboard.KEY_3, "Pet 3 on the list.").withDependency { advanced } + private val pet4: Keybinding by KeybindSetting("Pet 4", Keyboard.KEY_4, "Pet 4 on the list.").withDependency { advanced } + private val pet5: Keybinding by KeybindSetting("Pet 5", Keyboard.KEY_5, "Pet 5 on the list.").withDependency { advanced } + private val pet6: Keybinding by KeybindSetting("Pet 6", Keyboard.KEY_6, "Pet 6 on the list.").withDependency { advanced } + private val pet7: Keybinding by KeybindSetting("Pet 7", Keyboard.KEY_7, "Pet 7 on the list.").withDependency { advanced } + private val pet8: Keybinding by KeybindSetting("Pet 8", Keyboard.KEY_8, "Pet 8 on the list.").withDependency { advanced } + private val pet9: Keybinding by KeybindSetting("Pet 9", Keyboard.KEY_9, "Pet 9 on the list.").withDependency { advanced } + + private val pets = arrayOf(pet1, pet2, pet3, pet4, pet5, pet6, pet7, pet8, pet9) + private val clickCoolDown = Clock(delay) + + val petList: MutableList<String> by ListSetting("List", mutableListOf()) + + @SubscribeEvent + fun checkKeybinds(event: GuiScreenEvent.KeyboardInputEvent.Pre) { + val chest = (event.gui as? GuiChest)?.inventorySlots ?: return + if (chest !is ContainerChest) return + + val matchResult = Regex("Pets \\((\\d)/(\\d)\\)").find(chest.name) ?: return + val (current, total) = matchResult.destructured
you sure this works, i would think the first part of the destructured is just the matched string, but if it works its fine
Odin
github_2023
others
72
odtheking
freebonsai
@@ -205,11 +206,17 @@ object BloodCamp : Module( currVector.zCoord + speedVectors.zCoord * ping ) - val boxOffset: Vec3 = Vec3((boxSize/2).unaryMinus(),1.5,(boxSize/2).unaryMinus()) - val pingAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(pingPoint) - val endAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(endPoint) + val renderEndPoint = getRenderVector(endPoint, event.partialTicks, renderData.lastEndPoint) + val renderPingPoint = getRenderVector(pingPoint, event.partialTicks, renderData.lastPingPoint) - val time = data.time ?: return@forEach + renderData.lastEndPoint = endPoint + renderData.lastPingPoint = pingPoint + + val boxOffset = Vec3((boxSize/2).unaryMinus(),1.5,(boxSize/2).unaryMinus())
unaryminus is the same as just typing -(boxSize/2)
Odin
github_2023
others
72
odtheking
freebonsai
@@ -177,15 +178,15 @@ object BloodCamp : Module( val ping = ServerUtils.averagePing - forRender.filter { (entity) -> !entity.isDead }.forEach { (entity, data) -> + forRender.filter { (entity) -> !entity.isDead }.forEach { (entity, renderData) ->
just use it in the filter
Odin
github_2023
others
72
odtheking
freebonsai
@@ -177,15 +178,15 @@ object BloodCamp : Module( val ping = ServerUtils.averagePing
why?
Odin
github_2023
others
72
odtheking
freebonsai
@@ -205,11 +206,17 @@ object BloodCamp : Module( currVector.zCoord + speedVectors.zCoord * ping ) - val boxOffset: Vec3 = Vec3((boxSize/2).unaryMinus(),1.5,(boxSize/2).unaryMinus()) - val pingAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(pingPoint) - val endAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(endPoint) + val renderEndPoint = getRenderVector(endPoint, event.partialTicks, renderData.lastEndPoint) + val renderPingPoint = getRenderVector(pingPoint, event.partialTicks, renderData.lastPingPoint) - val time = data.time ?: return@forEach + renderData.lastEndPoint = endPoint + renderData.lastPingPoint = pingPoint + + val boxOffset = Vec3((boxSize/2).unaryMinus(),1.5,(boxSize/2).unaryMinus()) + val pingAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(renderPingPoint) + val endAABB = AxisAlignedBB(boxSize,boxSize,boxSize, 0.0, 0.0, 0.0).offset(boxOffset).offset(renderEndPoint)
you should be able to just do .offset(boxOffset + renderEndPoint), there is an operator function in vecutils for it
Odin
github_2023
others
72
odtheking
freebonsai
@@ -205,11 +206,17 @@ object BloodCamp : Module( currVector.zCoord + speedVectors.zCoord * ping )
cant you use your new function for the endPoint Vec3?
Odin
github_2023
others
60
odtheking
odtheking
@@ -94,4 +135,65 @@ object ChocolateFactory : Module( if (!cancelSound) return if (event.name == "random.eat") event.result = null // This should cancel the sound event } + + + private var currentDetectedEggs = arrayOfNulls<Egg>(3) + + private enum class ChocolateEggs( + val texture: String, val type: String, val color: Color, val index: Int + ) { + Breakfast(BunnyEggTextures.breakfastEggTexture, "§6Breakfast Egg", Color.ORANGE, 0), + Lunch(BunnyEggTextures.lunchEggTexture, "§9Lunch Egg ", Color.BLUE, 1), + Dinner(BunnyEggTextures.dinnerEggTexture, "§aDinner Egg", Color.GREEN, 2), + } + + data class Egg(val entity: EntityArmorStand, val renderName: String, val color: Color, var isFound: Boolean = false) + + private fun getEggType(entity: EntityArmorStand): ChocolateEggs? { + val texture = getSkullValue(entity) + return ChocolateEggs.entries.find { it.texture == texture } + } + + fun scanForEggs() { + for (entity in mc.theWorld.loadedEntityList.filterIsInstance<EntityArmorStand>()) { + val eggType = getEggType(entity) ?: continue + if(currentDetectedEggs[eggType.index] != null) continue + currentDetectedEggs[eggType.index] = Egg(entity, eggType.type, eggType.color) + } + } + + @SubscribeEvent + fun onRenderWorld(event: RenderWorldLastEvent) { + if (currentDetectedEggs.isEmpty()) return + for (egg in currentDetectedEggs) { + if (egg == null || egg.isFound) continue + val eggLocation = Vec3(egg.entity.posX - 0.5, egg.entity.posY + 1.47, egg.entity.posZ - 0.5) + Renderer.drawCustomBeacon(egg.renderName, eggLocation, egg.color, increase = true, beacon = false) + } + } + + // HOPPITY'S HUNT A Chocolate Breakfast Egg has appeared! + // HOPPITY'S HUNT A Chocolate Lunch Egg has appeared! + // HOPPITY'S HUNT A Chocolate Dinner Egg has appeared! + + // HOPPITY'S HUNT You found a Chocolate Breakfast Egg in front of the Iron Forger! + // HOPPITY'S HUNT You found a Chocolate Lunch Egg in the Blacksmith’s forge! + // HOPPITY'S HUNT You found a Chocolate Dinner Egg next to the Lazy Miner’s pickaxe! + @SubscribeEvent + fun onChat(event: ChatPacketEvent) {
Use odin's onMessage system instead
Odin
github_2023
others
60
odtheking
odtheking
@@ -94,4 +135,65 @@ object ChocolateFactory : Module( if (!cancelSound) return if (event.name == "random.eat") event.result = null // This should cancel the sound event } + + + private var currentDetectedEggs = arrayOfNulls<Egg>(3) + + private enum class ChocolateEggs( + val texture: String, val type: String, val color: Color, val index: Int + ) { + Breakfast(BunnyEggTextures.breakfastEggTexture, "§6Breakfast Egg", Color.ORANGE, 0), + Lunch(BunnyEggTextures.lunchEggTexture, "§9Lunch Egg ", Color.BLUE, 1), + Dinner(BunnyEggTextures.dinnerEggTexture, "§aDinner Egg", Color.GREEN, 2), + } + + data class Egg(val entity: EntityArmorStand, val renderName: String, val color: Color, var isFound: Boolean = false) + + private fun getEggType(entity: EntityArmorStand): ChocolateEggs? { + val texture = getSkullValue(entity) + return ChocolateEggs.entries.find { it.texture == texture } + } + + fun scanForEggs() {
You should filter the list instead of checking it while iterating over it Also switch to foreach should look nicer
Odin
github_2023
others
60
odtheking
odtheking
@@ -94,4 +135,65 @@ object ChocolateFactory : Module( if (!cancelSound) return if (event.name == "random.eat") event.result = null // This should cancel the sound event } + + + private var currentDetectedEggs = arrayOfNulls<Egg>(3) + + private enum class ChocolateEggs( + val texture: String, val type: String, val color: Color, val index: Int + ) { + Breakfast(BunnyEggTextures.breakfastEggTexture, "§6Breakfast Egg", Color.ORANGE, 0), + Lunch(BunnyEggTextures.lunchEggTexture, "§9Lunch Egg ", Color.BLUE, 1), + Dinner(BunnyEggTextures.dinnerEggTexture, "§aDinner Egg", Color.GREEN, 2), + } + + data class Egg(val entity: EntityArmorStand, val renderName: String, val color: Color, var isFound: Boolean = false) + + private fun getEggType(entity: EntityArmorStand): ChocolateEggs? { + val texture = getSkullValue(entity) + return ChocolateEggs.entries.find { it.texture == texture } + } + + fun scanForEggs() { + for (entity in mc.theWorld.loadedEntityList.filterIsInstance<EntityArmorStand>()) { + val eggType = getEggType(entity) ?: continue + if(currentDetectedEggs[eggType.index] != null) continue + currentDetectedEggs[eggType.index] = Egg(entity, eggType.type, eggType.color) + } + } + + @SubscribeEvent + fun onRenderWorld(event: RenderWorldLastEvent) { + if (currentDetectedEggs.isEmpty()) return + for (egg in currentDetectedEggs) {
Using foreach should look nicer
Odin
github_2023
others
60
odtheking
odtheking
@@ -94,4 +135,65 @@ object ChocolateFactory : Module( if (!cancelSound) return if (event.name == "random.eat") event.result = null // This should cancel the sound event } + + + private var currentDetectedEggs = arrayOfNulls<Egg>(3) + + private enum class ChocolateEggs( + val texture: String, val type: String, val color: Color, val index: Int + ) { + Breakfast(BunnyEggTextures.breakfastEggTexture, "§6Breakfast Egg", Color.ORANGE, 0), + Lunch(BunnyEggTextures.lunchEggTexture, "§9Lunch Egg ", Color.BLUE, 1), + Dinner(BunnyEggTextures.dinnerEggTexture, "§aDinner Egg", Color.GREEN, 2), + } + + data class Egg(val entity: EntityArmorStand, val renderName: String, val color: Color, var isFound: Boolean = false) + + private fun getEggType(entity: EntityArmorStand): ChocolateEggs? { + val texture = getSkullValue(entity) + return ChocolateEggs.entries.find { it.texture == texture } + } + + fun scanForEggs() { + for (entity in mc.theWorld.loadedEntityList.filterIsInstance<EntityArmorStand>()) { + val eggType = getEggType(entity) ?: continue + if(currentDetectedEggs[eggType.index] != null) continue + currentDetectedEggs[eggType.index] = Egg(entity, eggType.type, eggType.color) + } + } + + @SubscribeEvent + fun onRenderWorld(event: RenderWorldLastEvent) { + if (currentDetectedEggs.isEmpty()) return + for (egg in currentDetectedEggs) { + if (egg == null || egg.isFound) continue + val eggLocation = Vec3(egg.entity.posX - 0.5, egg.entity.posY + 1.47, egg.entity.posZ - 0.5) + Renderer.drawCustomBeacon(egg.renderName, eggLocation, egg.color, increase = true, beacon = false) + } + } + + // HOPPITY'S HUNT A Chocolate Breakfast Egg has appeared! + // HOPPITY'S HUNT A Chocolate Lunch Egg has appeared! + // HOPPITY'S HUNT A Chocolate Dinner Egg has appeared! + + // HOPPITY'S HUNT You found a Chocolate Breakfast Egg in front of the Iron Forger! + // HOPPITY'S HUNT You found a Chocolate Lunch Egg in the Blacksmith’s forge! + // HOPPITY'S HUNT You found a Chocolate Dinner Egg next to the Lazy Miner’s pickaxe! + @SubscribeEvent + fun onChat(event: ChatPacketEvent) { + if(!eggEsp) return + val match = Regex(".*(A|found|collected).+Chocolate (Lunch|Dinner|Breakfast).*").find(event.message) ?: return + val egg = ChocolateEggs.entries.find { it.type.contains(match.groupValues[2]) } ?: return + when(match.groupValues[1]) { + "A" -> {
you can lose the brackets here and have each outcome a oneliner
Odin
github_2023
others
60
odtheking
odtheking
@@ -256,6 +256,12 @@ data object FlareTextures { val sosFlareTexture = "ewogICJ0aW1lc3RhbXAiIDogMTY0NjY4NzM0NzQ4OSwKICAicHJvZmlsZUlkIiA6ICI0MWQzYWJjMmQ3NDk0MDBjOTA5MGQ1NDM0ZDAzODMxYiIsCiAgInByb2ZpbGVOYW1lIiA6ICJNZWdha2xvb24iLAogICJzaWduYXR1cmVSZXF1aXJlZCIgOiB0cnVlLAogICJ0ZXh0dXJlcyIgOiB7CiAgICAiU0tJTiIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYzAwNjJjYzk4ZWJkYTcyYTZhNGI4OTc4M2FkY2VmMjgxNWI0ODNhMDFkNzNlYTg3YjNkZjc2MDcyYTg5ZDEzYiIKICAgIH0KICB9Cn0=" } +data object BunnyEggTextures {
Should mention where these values are used
Odin
github_2023
others
60
odtheking
odtheking
@@ -1,62 +1,103 @@ package me.odinclient.features.impl.skyblock +import me.odinmain.events.impl.ChatPacketEvent import me.odinmain.events.impl.GuiEvent import me.odinmain.features.Category import me.odinmain.features.Module import me.odinmain.features.settings.impl.BooleanSetting import me.odinmain.features.settings.impl.NumberSetting +import me.odinmain.utils.BunnyEggTextures import me.odinmain.utils.name import me.odinmain.utils.noControlCodes +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.Renderer +import me.odinmain.utils.skyblock.* import me.odinmain.utils.skyblock.PlayerUtils.windowClick -import me.odinmain.utils.skyblock.lore -import me.odinmain.utils.skyblock.modMessage +import net.minecraft.entity.item.EntityArmorStand import net.minecraft.inventory.Container import net.minecraft.inventory.ContainerChest +import net.minecraft.util.Vec3 +import net.minecraftforge.client.event.RenderWorldLastEvent import net.minecraftforge.client.event.sound.PlaySoundEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + object ChocolateFactory : Module( "Chocolate Factory", description = "Automatically clicks the cookie in the Chocolate Factory menu.", category = Category.SKYBLOCK ) { - private val clickFactory: Boolean by BooleanSetting("Click Factory", false, description = "Click the cookie in the Chocolate Factory menu.") - private val autoUpgrade: Boolean by BooleanSetting("Auto Upgrade", false, description = "Automatically upgrade the worker.") + private val clickFactory: Boolean by BooleanSetting( + "Click Factory", + false, + description = "Click the cookie in the Chocolate Factory menu." + ) + private val autoUpgrade: Boolean by BooleanSetting( + "Auto Upgrade", + false, + description = "Automatically upgrade the worker." + ) private val delay: Long by NumberSetting("Delay", 150, 50, 300, 5) private val upgradeDelay: Long by NumberSetting("Upgrade delay", 500, 300, 2000, 100) private val cancelSound: Boolean by BooleanSetting("Cancel Sound") - private val upgradeMessage: Boolean by BooleanSetting("Odin Upgrade Message", false, description = "Prints a message when upgrading.") + private val upgradeMessage: Boolean by BooleanSetting( + "Odin Upgrade Message", + false, + description = "Prints a message when upgrading." + ) + private val eggEsp: Boolean by BooleanSetting("Egg ESP", false, description = "Shows the location of the egg.") private var chocolate = 0 private var chocoProduction = 0f val indexToName = mapOf(29 to "Bro", 30 to "Cousin", 31 to "Sis", 32 to "Daddy", 33 to "Granny") + private val possibleLocations = arrayOf( + Island.SpiderDen, + Island.CrimsonIsle, + Island.TheEnd, + Island.GoldMine, + Island.DeepCaverns, + Island.DwarvenMines, + Island.CrystalHollows, + Island.FarmingIsland, + Island.ThePark, + Island.DungeonHub, + Island.Hub + ) init { + onWorldLoad { currentDetectedEggs = arrayOfNulls(3) } execute(delay = { delay }) { val container = mc.thePlayer?.openContainer as? ContainerChest ?: return@execute if (container.name != "Chocolate Factory") return@execute - if (clickFactory) windowClick(13, 1,0) + if (clickFactory) windowClick(13, 1, 0)
Should use ClickType from PlayerUtils insTead
Odin
github_2023
others
46
odtheking
freebonsai
@@ -0,0 +1,39 @@ +package me.odinmain.features.impl.skyblock + +import me.odinmain.OdinMain.onLegitVersion +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.Setting.Companion.withDependency +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.NumberSetting +import me.odinmain.utils.ServerUtils.getPing +import net.minecraftforge.client.event.RenderPlayerEvent +import net.minecraftforge.event.entity.living.LivingEvent +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object HidePlayers : Module( + name = "Hide Players", + description = "Hides players", + category = Category.SKYBLOCK +) { + private val hideAll: Boolean by BooleanSetting("Hide all", default = false, false, "Hides all players, regardless of distance") + private val distance: Double by NumberSetting("distance", 3.0, 0.0, 32.0, .5, false, "The number of blocks away to hide players.").withDependency { !hideAll } + private val clickThrough: Boolean by BooleanSetting("Click Through", default = false, false, "Allows clicking through players.").withDependency { !onLegitVersion } + + @SubscribeEvent + fun onRenderEntity(event: RenderPlayerEvent.Pre) { + if (event.entity.getPing() != 1 || clickThrough || event.entity == mc.thePlayer) return + val distanceTo = event.entity.getDistanceToEntity(mc.thePlayer)
doesnt need to be a variable
Odin
github_2023
others
46
odtheking
freebonsai
@@ -0,0 +1,39 @@ +package me.odinmain.features.impl.skyblock + +import me.odinmain.OdinMain.onLegitVersion +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.Setting.Companion.withDependency +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.NumberSetting +import me.odinmain.utils.ServerUtils.getPing +import net.minecraftforge.client.event.RenderPlayerEvent +import net.minecraftforge.event.entity.living.LivingEvent +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object HidePlayers : Module( + name = "Hide Players", + description = "Hides players", + category = Category.SKYBLOCK +) { + private val hideAll: Boolean by BooleanSetting("Hide all", default = false, false, "Hides all players, regardless of distance") + private val distance: Double by NumberSetting("distance", 3.0, 0.0, 32.0, .5, false, "The number of blocks away to hide players.").withDependency { !hideAll } + private val clickThrough: Boolean by BooleanSetting("Click Through", default = false, false, "Allows clicking through players.").withDependency { !onLegitVersion } + + @SubscribeEvent + fun onRenderEntity(event: RenderPlayerEvent.Pre) { + if (event.entity.getPing() != 1 || clickThrough || event.entity == mc.thePlayer) return + val distanceTo = event.entity.getDistanceToEntity(mc.thePlayer) + if (distanceTo <= distance || hideAll) { event.isCanceled = true }
dont need {}
Odin
github_2023
others
46
odtheking
freebonsai
@@ -0,0 +1,39 @@ +package me.odinmain.features.impl.skyblock + +import me.odinmain.OdinMain.onLegitVersion +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.Setting.Companion.withDependency +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.NumberSetting +import me.odinmain.utils.ServerUtils.getPing +import net.minecraftforge.client.event.RenderPlayerEvent +import net.minecraftforge.event.entity.living.LivingEvent +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object HidePlayers : Module( + name = "Hide Players", + description = "Hides players", + category = Category.SKYBLOCK +) { + private val hideAll: Boolean by BooleanSetting("Hide all", default = false, false, "Hides all players, regardless of distance") + private val distance: Double by NumberSetting("distance", 3.0, 0.0, 32.0, .5, false, "The number of blocks away to hide players.").withDependency { !hideAll } + private val clickThrough: Boolean by BooleanSetting("Click Through", default = false, false, "Allows clicking through players.").withDependency { !onLegitVersion } + + @SubscribeEvent + fun onRenderEntity(event: RenderPlayerEvent.Pre) { + if (event.entity.getPing() != 1 || clickThrough || event.entity == mc.thePlayer) return + val distanceTo = event.entity.getDistanceToEntity(mc.thePlayer) + if (distanceTo <= distance || hideAll) { event.isCanceled = true } + } + + @SubscribeEvent + fun onPosUpdate(event: LivingEvent.LivingUpdateEvent) { + if (event.entity.getPing() != 1 || !clickThrough || event.entity == mc.thePlayer) return + val distanceTo = event.entity.getDistanceToEntity(mc.thePlayer)
again no need for variable
Odin
github_2023
others
41
odtheking
freebonsai
@@ -0,0 +1,86 @@ +package me.odinmain.features.impl.floor7.p3 + +import me.odinmain.events.impl.ChatPacketEvent +import me.odinmain.events.impl.RealServerTick +import me.odinmain.events.impl.ServerTickEvent +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.HudSetting +import me.odinmain.font.OdinFont +import me.odinmain.ui.hud.HudElement +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.getTextWidth +import me.odinmain.utils.render.text +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.world.World +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object GoldorTickTimer : Module( + name = "Goldor Tick Timer", + category = Category.FLOOR7, + description = "Tick Timer for when goldor kills players" +) { + private val startTimer: Boolean by BooleanSetting("Start Timer", default = true, description = "4.5 second countdown until terms/devices are able to be completed") + private val hud: HudElement by HudSetting("Timer Hud", 10f, 10f, 1f, true) { + if (it) { + text("§7Tick: §a59t", 1f, 9f, Color.RED, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Tick: 119t", 12f) + 2f to 16f + } else { + val colorCode = when { + tickTime.time >= 40 -> "§a" + tickTime.time in 20..40 -> "§6" + tickTime.time in 0..20 -> "§c" + else -> return@HudSetting 0f to 0f + } + val text = if(isStarting)
make one line if its this short, also if needs a space after it.
Odin
github_2023
others
41
odtheking
freebonsai
@@ -0,0 +1,86 @@ +package me.odinmain.features.impl.floor7.p3 + +import me.odinmain.events.impl.ChatPacketEvent +import me.odinmain.events.impl.RealServerTick +import me.odinmain.events.impl.ServerTickEvent +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.HudSetting +import me.odinmain.font.OdinFont +import me.odinmain.ui.hud.HudElement +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.getTextWidth +import me.odinmain.utils.render.text +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.world.World +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object GoldorTickTimer : Module( + name = "Goldor Tick Timer", + category = Category.FLOOR7, + description = "Tick Timer for when goldor kills players" +) { + private val startTimer: Boolean by BooleanSetting("Start Timer", default = true, description = "4.5 second countdown until terms/devices are able to be completed") + private val hud: HudElement by HudSetting("Timer Hud", 10f, 10f, 1f, true) { + if (it) { + text("§7Tick: §a59t", 1f, 9f, Color.RED, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Tick: 119t", 12f) + 2f to 16f + } else { + val colorCode = when { + tickTime.time >= 40 -> "§a" + tickTime.time in 20..40 -> "§6" + tickTime.time in 0..20 -> "§c" + else -> return@HudSetting 0f to 0f + } + val text = if(isStarting) + "§aStart" + else "§8Tick" + + text("${text}: ${colorCode}${tickTime.time}t", 1f, 9f, Color.WHITE, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Start: 119t", 12f) + 2f to 12f + } + } + + data class Timer(var time: Int) + private var tickTime = Timer(0) + private var isStarting = false + private var shouldLoad = false + private val preStartRegex = Regex("\\[BOSS] Storm: I should have known that I stood no chance\\.") + private val startRegex = Regex("\\[BOSS] Goldor: Who dares trespass into my domain\\?") + private val endRegex = Regex("The Core entrance is opening!") + + @SubscribeEvent + fun onChat(event: ChatPacketEvent) { + val msg = event.message + if (!msg.matches(preStartRegex) && !msg.matches(startRegex) && !msg.matches(endRegex) || msg.contains("Storm") && !startTimer) return + isStarting = msg.contains("Storm") + shouldLoad = !msg.contains("Core") + if (!shouldLoad) return + + + tickTime = if (isStarting)
again, one line
Odin
github_2023
others
41
odtheking
freebonsai
@@ -0,0 +1,86 @@ +package me.odinmain.features.impl.floor7.p3 + +import me.odinmain.events.impl.ChatPacketEvent +import me.odinmain.events.impl.RealServerTick +import me.odinmain.events.impl.ServerTickEvent +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.HudSetting +import me.odinmain.font.OdinFont +import me.odinmain.ui.hud.HudElement +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.getTextWidth +import me.odinmain.utils.render.text +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.world.World +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object GoldorTickTimer : Module( + name = "Goldor Tick Timer", + category = Category.FLOOR7, + description = "Tick Timer for when goldor kills players" +) { + private val startTimer: Boolean by BooleanSetting("Start Timer", default = true, description = "4.5 second countdown until terms/devices are able to be completed") + private val hud: HudElement by HudSetting("Timer Hud", 10f, 10f, 1f, true) { + if (it) { + text("§7Tick: §a59t", 1f, 9f, Color.RED, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Tick: 119t", 12f) + 2f to 16f + } else { + val colorCode = when { + tickTime.time >= 40 -> "§a" + tickTime.time in 20..40 -> "§6" + tickTime.time in 0..20 -> "§c" + else -> return@HudSetting 0f to 0f + } + val text = if(isStarting) + "§aStart" + else "§8Tick" + + text("${text}: ${colorCode}${tickTime.time}t", 1f, 9f, Color.WHITE, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Start: 119t", 12f) + 2f to 12f + } + } + + data class Timer(var time: Int) + private var tickTime = Timer(0) + private var isStarting = false + private var shouldLoad = false + private val preStartRegex = Regex("\\[BOSS] Storm: I should have known that I stood no chance\\.") + private val startRegex = Regex("\\[BOSS] Goldor: Who dares trespass into my domain\\?") + private val endRegex = Regex("The Core entrance is opening!") + + @SubscribeEvent + fun onChat(event: ChatPacketEvent) { + val msg = event.message + if (!msg.matches(preStartRegex) && !msg.matches(startRegex) && !msg.matches(endRegex) || msg.contains("Storm") && !startTimer) return + isStarting = msg.contains("Storm") + shouldLoad = !msg.contains("Core") + if (!shouldLoad) return + + + tickTime = if (isStarting) + Timer(104) + else Timer(60) + } + @SubscribeEvent + fun onServerTick(event: RealServerTick) { + if(!shouldLoad) {
space after if
Odin
github_2023
others
41
odtheking
freebonsai
@@ -0,0 +1,86 @@ +package me.odinmain.features.impl.floor7.p3 + +import me.odinmain.events.impl.ChatPacketEvent +import me.odinmain.events.impl.RealServerTick +import me.odinmain.events.impl.ServerTickEvent +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.impl.BooleanSetting +import me.odinmain.features.settings.impl.HudSetting +import me.odinmain.font.OdinFont +import me.odinmain.ui.hud.HudElement +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.getTextWidth +import me.odinmain.utils.render.text +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.world.World +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object GoldorTickTimer : Module( + name = "Goldor Tick Timer", + category = Category.FLOOR7, + description = "Tick Timer for when goldor kills players" +) { + private val startTimer: Boolean by BooleanSetting("Start Timer", default = true, description = "4.5 second countdown until terms/devices are able to be completed") + private val hud: HudElement by HudSetting("Timer Hud", 10f, 10f, 1f, true) { + if (it) { + text("§7Tick: §a59t", 1f, 9f, Color.RED, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Tick: 119t", 12f) + 2f to 16f + } else { + val colorCode = when { + tickTime.time >= 40 -> "§a" + tickTime.time in 20..40 -> "§6" + tickTime.time in 0..20 -> "§c" + else -> return@HudSetting 0f to 0f + } + val text = if(isStarting) + "§aStart" + else "§8Tick" + + text("${text}: ${colorCode}${tickTime.time}t", 1f, 9f, Color.WHITE, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Start: 119t", 12f) + 2f to 12f + } + } + + data class Timer(var time: Int) + private var tickTime = Timer(0) + private var isStarting = false + private var shouldLoad = false + private val preStartRegex = Regex("\\[BOSS] Storm: I should have known that I stood no chance\\.") + private val startRegex = Regex("\\[BOSS] Goldor: Who dares trespass into my domain\\?") + private val endRegex = Regex("The Core entrance is opening!") + + @SubscribeEvent + fun onChat(event: ChatPacketEvent) { + val msg = event.message + if (!msg.matches(preStartRegex) && !msg.matches(startRegex) && !msg.matches(endRegex) || msg.contains("Storm") && !startTimer) return + isStarting = msg.contains("Storm") + shouldLoad = !msg.contains("Core") + if (!shouldLoad) return + + + tickTime = if (isStarting) + Timer(104) + else Timer(60) + } + @SubscribeEvent + fun onServerTick(event: RealServerTick) { + if(!shouldLoad) { + tickTime = Timer(-1)
editing the value of the current timer is cleaner than making a new object, if you did this every where you could make tickTime a val instead of a var too, which is cleaner imo. tickTime.time = -1
Odin
github_2023
others
39
odtheking
freebonsai
@@ -0,0 +1,57 @@ +package me.odinmain.features.impl.skyblock + +import me.odinmain.events.impl.ServerTickEvent +import me.odinmain.features.Category +import me.odinmain.features.Module +import me.odinmain.features.settings.impl.HudSetting +import me.odinmain.font.OdinFont +import me.odinmain.ui.hud.HudElement +import me.odinmain.utils.render.Color +import me.odinmain.utils.render.getTextWidth +import me.odinmain.utils.render.text +import me.odinmain.utils.skyblock.itemID +import me.odinmain.utils.skyblock.modMessage +import net.minecraft.network.play.server.S29PacketSoundEffect +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +object EnrageDisplay : Module ( + name = "Enrage Display", + description = "Timer for cooldown of reaper armor enrage", + category = Category.SKYBLOCK +) { + private val hud: HudElement by HudSetting("Enrage Timer Hud", 10f, 10f, 1f, true) { + if (it) { + text("§4Enrage: §a119t", 1f, 9f, Color.RED, 12f, OdinFont.REGULAR, shadow = true) + getTextWidth("Enrage: 119t", 12f) + 2f to 16f + } else { + if (enrageTime.time >= 60) { + text("§4Enrage: §a${enrageTime.time}t", 1f, 9f, Color.WHITE, 12f, OdinFont.REGULAR, shadow = true) + } + if (enrageTime.time in 30..60) {
Make these into else if's just because its cleaner, and that is the functionality you want from the code.
Odin
github_2023
others
35
odtheking
freebonsai
@@ -28,7 +34,19 @@ object DragonPriority { PlayerUtils.alert("§${dragon.colorCode} ${dragon.name}") } - private fun sortPriority(spawningDragon: MutableList<WitherDragonsEnum>): WitherDragonsEnum { + /** fun tracerDragonPriority() {
Having the function here would be cleaner.
Odin
github_2023
others
35
odtheking
freebonsai
@@ -101,7 +101,8 @@ val devCommand = commodore("oddev") { MinecraftForge.EVENT_BUS.post(ChatPacketEvent(str.string)) } - literal("roomdata").runs { + /**
Not sure why this is commented out, add it back before merge.
Odin
github_2023
others
37
odtheking
freebonsai
@@ -108,7 +108,7 @@ val devCommand = commodore("oddev") { val xPos = -185 + x * 32 val zPos = -185 + z * 32 val core = ScanUtils.getCore(xPos, zPos) - val northPos = DungeonUtils.Vec2(xPos, zPos - 4) + val northPos = Vec2(xPos, zPos - 4)
Just remove this from the message, it's redundant as the scanning no longer uses rotation cores.
Odin
github_2023
others
37
odtheking
freebonsai
@@ -71,6 +71,7 @@ object DungeonWaypoints : Module( fun onRender(event: RenderWorldLastEvent) { DungeonUtils.currentRoom?.waypoints?.forEach { Renderer.drawBox(it.toAABB(it.size), it.color, fillAlpha = if (it.filled) .8 else 0, depth = it.depth) + Renderer.drawStringInWorld(it.title.toString(), Vec3(it.x+0.5,it.y+0.5,it.z+0.5))
Replace ´it.title.toString()" with "it.title ?: "" ´ This removes the need for the function to replace "null"
Odin
github_2023
others
37
odtheking
freebonsai
@@ -102,9 +102,9 @@ object Renderer { scale: Float = 0.03f, shadow: Boolean = true ) { - RenderUtils.drawStringInWorld(text, vec3, color, renderBlackBox, depth, scale, shadow) + RenderUtils.drawStringInWorld(text.replace("null"," "), vec3, color, renderBlackBox, depth, scale, shadow) } - + //Edited to make null value not crash the game, as if config doesn't have a title it will crash game otherwise.
Do my suggestion in DungeonWaypoints.kt and remove this change.
Odin
github_2023
others
37
odtheking
freebonsai
@@ -60,7 +85,68 @@ object DungeonWaypoints : Module( } private val debugWaypoint: Boolean by BooleanSetting("Debug Waypoint", false).withDependency { DevPlayers.isDev } - data class DungeonWaypoint(val x: Double, val y: Double, val z: Double, val color: Color, val filled: Boolean, val depth: Boolean, val size: Double) + data class DungeonWaypoint( + val x: Double, + val y: Double, + val z: Double, + val color: Color, + val filled: Boolean, + val depth: Boolean, + val size: Double, + val title: String? + ) + + class GuiSign : GuiScreen() {
Make this an object instead of a class, you can still achieve the same result, look at TermSim objects if you need.
Odin
github_2023
others
37
odtheking
freebonsai
@@ -37,10 +41,30 @@ object DungeonWaypoints : Module( tag = TagType.NEW ) { private var allowEdits: Boolean by BooleanSetting("Allow Edits", false) - private val color: Color by ColorSetting("Color", default = Color.GREEN, description = "The color of the next waypoint you place.", allowAlpha = true) - private val filled: Boolean by BooleanSetting("Filled", false, description = "If the next waypoint you place should be 'filled'.") - private val throughWalls: Boolean by BooleanSetting("Through walls", false, description = "If the next waypoint you place should be visible through walls.") - private val size: Double by NumberSetting<Double>("Size", 1.0, .125, 1.0, increment = 0.125, description = "The size of the next waypoint you place.") + private val color: Color by ColorSetting(
I see no need to expand these, it makes the code longer for no reason.
Odin
github_2023
others
37
odtheking
freebonsai
@@ -92,13 +179,42 @@ object DungeonWaypoints : Module( DungeonWaypointConfig.waypoints.getOrPut(room.data.name) { mutableListOf() } else DungeonWaypointConfig.waypoints.getOrPut(room.core.toString()) { mutableListOf() } - - if (!waypoints.any { it.toVec3().equal(vec) }) { - waypoints.add(DungeonWaypoint(vec.xCoord, vec.yCoord, vec.zCoord, color.copy(), filled, !throughWalls, size)) - devMessage("Added waypoint at $vec") - } else { - waypoints.removeIf { it.toVec3().equal(vec) } + if (mc.thePlayer.isSneaking) { + val gui = GuiSign() + gui.setCallback { enteredText -> + waypoints.removeIf { it.toVec3().equal(vec) } + waypoints.add(
Do this in one line
Odin
github_2023
others
37
odtheking
freebonsai
@@ -107,5 +223,12 @@ object DungeonWaypoints : Module( fun DungeonWaypoint.toVec3() = Vec3(x, y, z) fun DungeonWaypoint.toBlockPos() = BlockPos(x, y, z) - fun DungeonWaypoint.toAABB(size: Double) = AxisAlignedBB(x + .5 - (size/2), y + .5 - (size/2), z + .5 - (size/2), x + .5 + (size/2), y + .5 + (size/2), z + .5 + (size/2)).expand(.01, .01, .01) + fun DungeonWaypoint.toAABB(size: Double) = AxisAlignedBB(
The expansion is fine here as they all line up and are very similar
Odin
github_2023
others
165
odtheking
gemini-code-assist[bot]
@@ -13,9 +13,11 @@ import me.odinmain.utils.render.Renderer import me.odinmain.utils.skyblock.LocationUtils.currentDungeon import me.odinmain.utils.skyblock.dungeon.DungeonUtils import me.odinmain.utils.skyblock.getSkullValue +import me.odinmain.utils.skyblock.modMessage
![medium](https://img.shields.io/badge/priority-medium-yellow) This import is not used. Consider removing it to keep the code clean.
Odin
github_2023
others
165
odtheking
gemini-code-assist[bot]
@@ -36,7 +38,7 @@ object Mimic : Module( @SubscribeEvent fun onEntityLeaveWorld(event: EntityLeaveWorldEvent) { - if (DungeonUtils.inDungeons && event.entity is EntityZombie && event.entity.isChild && getSkullValue(event.entity).equals(MIMIC_TEXTURE)) mimicKilled() + if (DungeonUtils.inDungeons && event.entity is EntityZombie && event.entity.isChild && !event.entity.isEntityAlive && getSkullValue(event.entity).equals(MIMIC_TEXTURE)) mimicKilled()
![medium](https://img.shields.io/badge/priority-medium-yellow) The `!event.entity.isEntityAlive` check seems redundant here. Since this is an `EntityLeaveWorldEvent` and the `LivingDeathEvent` already handles the death, the entity should already be considered dead. Consider removing this check for clarity and efficiency. ```suggestion if (DungeonUtils.inDungeons && event.entity is EntityZombie && event.entity.isChild && getSkullValue(event.entity).equals(MIMIC_TEXTURE)) mimicKilled() ```
quackpipe
github_2023
go
40
metrico
github-advanced-security[bot]
@@ -0,0 +1,147 @@ +package repository + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "quackpipe/config" + "quackpipe/merge/service" + "quackpipe/model" + "quackpipe/service/db" + "sync" + "time" +) + +var conn *sql.DB + +var registry = make(map[string]*service.MergeTreeService) +var mergeTicker *time.Ticker +var registryMtx sync.Mutex + +func InitRegistry(_conn *sql.DB) error { + var err error + if _conn == nil { + _conn, err = db.ConnectDuckDB(config.Config.QuackPipe.Root + "/ddb.db") + if err != nil { + return err + } + } + conn = _conn + err = CreateDuckDBTablesTable(conn) + if err != nil { + return err + } + err = PopulateRegistry() + if err != nil { + return err + } + go RunMerge() + return nil +} + +func GetTable(name string) (*service.MergeTreeService, error) { + table, ok := registry[name] + if !ok { + return nil, fmt.Errorf("table %q not found", name) + } + return table, nil +} + +func RunMerge() { + mergeTicker = time.NewTicker(time.Second * 10) + for range mergeTicker.C { + _registry := make(map[string]*service.MergeTreeService, len(registry)) + func() { + registryMtx.Lock() + defer registryMtx.Unlock() + for k, v := range registry { + _registry[k] = v + } + }() + for _, table := range _registry { + err := table.Merge() + if err != nil { + fmt.Println(err) + } + } + } +} + +func RegisterNewTable(table *model.Table) error { + if _, ok := registry[table.Name]; ok { + return nil + } + fieldNames := make([]string, len(table.Fields)) + fieldTypes := make([]string, len(table.Fields)) + for i, field := range table.Fields { + fieldNames[i] = field[0] + fieldTypes[i] = field[1] + } + err := createTableFolders(table) + if err != nil { + return err + } + err = InsertTableMetadata( + conn, table.Name, table.Path, + fieldNames, fieldTypes, table.OrderBy, + table.Engine, table.TimestampField, table.TimestampPrecision, table.PartitionBy) + if err != nil { + return err + } + registryMtx.Lock() + registry[table.Name] = service.NewMergeTreeService(table) + registry[table.Name].Run() + registryMtx.Unlock() + return nil +} + +func PopulateRegistry() error { + res, err := conn.Query(` +SELECT name,path, field_names, field_types, order_by, engine, timestamp_field, timestamp_precision, partition_by +FROM tables +`) + if err != nil { + return err + } + defer res.Close() + + for res.Next() { + var table model.Table + var ( + fieldNames []any + fieldTypes []any + orderBy []any + ) + err = res.Scan( + &table.Name, &table.Path, + &fieldNames, &fieldTypes, &orderBy, + &table.Engine, &table.TimestampField, &table.TimestampPrecision, &table.PartitionBy, + ) + if err != nil { + return err + } + for i, n := range fieldNames { + table.Fields = append(table.Fields, [2]string{n.(string), fieldTypes[i].(string)}) + } + for _, n := range orderBy { + table.OrderBy = append(table.OrderBy, n.(string)) + } + func() { + registryMtx.Lock() + defer registryMtx.Unlock() + registry[table.Name] = service.NewMergeTreeService(&table) + registry[table.Name].Run() + }() + } + return nil + +} + +func createTableFolders(table *model.Table) error { + err := os.MkdirAll(filepath.Join(table.Path, "tmp"), 0755)
## Uncontrolled data used in path expression This path depends on a [user-provided value](1). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/5)
quackpipe
github_2023
go
40
metrico
github-advanced-security[bot]
@@ -0,0 +1,147 @@ +package repository + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "quackpipe/config" + "quackpipe/merge/service" + "quackpipe/model" + "quackpipe/service/db" + "sync" + "time" +) + +var conn *sql.DB + +var registry = make(map[string]*service.MergeTreeService) +var mergeTicker *time.Ticker +var registryMtx sync.Mutex + +func InitRegistry(_conn *sql.DB) error { + var err error + if _conn == nil { + _conn, err = db.ConnectDuckDB(config.Config.QuackPipe.Root + "/ddb.db") + if err != nil { + return err + } + } + conn = _conn + err = CreateDuckDBTablesTable(conn) + if err != nil { + return err + } + err = PopulateRegistry() + if err != nil { + return err + } + go RunMerge() + return nil +} + +func GetTable(name string) (*service.MergeTreeService, error) { + table, ok := registry[name] + if !ok { + return nil, fmt.Errorf("table %q not found", name) + } + return table, nil +} + +func RunMerge() { + mergeTicker = time.NewTicker(time.Second * 10) + for range mergeTicker.C { + _registry := make(map[string]*service.MergeTreeService, len(registry)) + func() { + registryMtx.Lock() + defer registryMtx.Unlock() + for k, v := range registry { + _registry[k] = v + } + }() + for _, table := range _registry { + err := table.Merge() + if err != nil { + fmt.Println(err) + } + } + } +} + +func RegisterNewTable(table *model.Table) error { + if _, ok := registry[table.Name]; ok { + return nil + } + fieldNames := make([]string, len(table.Fields)) + fieldTypes := make([]string, len(table.Fields)) + for i, field := range table.Fields { + fieldNames[i] = field[0] + fieldTypes[i] = field[1] + } + err := createTableFolders(table) + if err != nil { + return err + } + err = InsertTableMetadata( + conn, table.Name, table.Path, + fieldNames, fieldTypes, table.OrderBy, + table.Engine, table.TimestampField, table.TimestampPrecision, table.PartitionBy) + if err != nil { + return err + } + registryMtx.Lock() + registry[table.Name] = service.NewMergeTreeService(table) + registry[table.Name].Run() + registryMtx.Unlock() + return nil +} + +func PopulateRegistry() error { + res, err := conn.Query(` +SELECT name,path, field_names, field_types, order_by, engine, timestamp_field, timestamp_precision, partition_by +FROM tables +`) + if err != nil { + return err + } + defer res.Close() + + for res.Next() { + var table model.Table + var ( + fieldNames []any + fieldTypes []any + orderBy []any + ) + err = res.Scan( + &table.Name, &table.Path, + &fieldNames, &fieldTypes, &orderBy, + &table.Engine, &table.TimestampField, &table.TimestampPrecision, &table.PartitionBy, + ) + if err != nil { + return err + } + for i, n := range fieldNames { + table.Fields = append(table.Fields, [2]string{n.(string), fieldTypes[i].(string)}) + } + for _, n := range orderBy { + table.OrderBy = append(table.OrderBy, n.(string)) + } + func() { + registryMtx.Lock() + defer registryMtx.Unlock() + registry[table.Name] = service.NewMergeTreeService(&table) + registry[table.Name].Run() + }() + } + return nil + +} + +func createTableFolders(table *model.Table) error { + err := os.MkdirAll(filepath.Join(table.Path, "tmp"), 0755) + if err != nil { + return err + } + return os.MkdirAll(filepath.Join(table.Path, "data"), 0755)
## Uncontrolled data used in path expression This path depends on a [user-provided value](1). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/6)
quackpipe
github_2023
go
40
metrico
github-advanced-security[bot]
@@ -0,0 +1,546 @@ +package service + +import ( + "context" + "errors" + "fmt" + "github.com/apache/arrow/go/v18/arrow" + "github.com/apache/arrow/go/v18/arrow/array" + "github.com/apache/arrow/go/v18/arrow/memory" + "github.com/apache/arrow/go/v18/parquet" + "github.com/apache/arrow/go/v18/parquet/pqarrow" + "github.com/google/uuid" + _ "github.com/marcboeker/go-duckdb" + "github.com/tidwall/btree" + "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" + "os" + "path/filepath" + "quackpipe/model" + "quackpipe/service/db" + "quackpipe/utils/promise" + "sort" + "strings" + "sync" + "sync/atomic" + "time" +) + +type IMergeTree interface { + Store(columns map[string][]any) error + Merge() error + Run() + Stop() +} + +type MergeTreeService struct { + Table *model.Table + ticker *time.Ticker + working uint32 + promises []*promise.Promise[int32] + recordBatch *array.RecordBuilder + mtx sync.Mutex + schema *arrow.Schema + lastIterationTime [3]time.Time + dataIndexes *btree.BTreeG[int32] + dataStore map[string]any +} + +func NewMergeTreeService(t *model.Table) *MergeTreeService { + res := &MergeTreeService{ + Table: t, + working: 0, + promises: []*promise.Promise[int32]{}, + recordBatch: nil, + } + res.dataStore = res.createDataStore() + res.dataIndexes = btree.NewBTreeG(res.Less) + res.schema = res.createParquetSchema() + pool := memory.NewGoAllocator() + res.recordBatch = array.NewRecordBuilder(pool, res.schema) + + return res +} + +func (s *MergeTreeService) createDataStore() map[string]any { + res := make(map[string]any) + for _, f := range s.Table.Fields { + switch f[1] { + case "UInt64": + res[f[0]] = make([]uint64, 0, 1000000) + case "Int64": + res[f[0]] = make([]int64, 0, 1000000) + case "String": + res[f[0]] = make([]string, 0, 1000000) + case "Float64": + res[f[0]] = make([]float64, 0, 1000000) + } + } + return res +} + +func (s *MergeTreeService) size() int32 { + return int32(s.dataIndexes.Len()) +} + +func getFieldType(t *model.Table, fieldName string) string { + for _, field := range t.Fields { + if field[0] == fieldName { + return field[1] + } + } + return "" +} + +func (s *MergeTreeService) Less(a, b int32) bool { + for _, o := range s.Table.OrderBy { + t := getFieldType(s.Table, o) + switch t { + case "UInt64": + if s.dataStore[o].([]uint64)[a] > s.dataStore[o].([]uint64)[b] { + return false + } + case "Int64": + if s.dataStore[o].([]int64)[a] > s.dataStore[o].([]int64)[b] { + return false + } + case "String": + if s.dataStore[o].([]string)[a] > s.dataStore[o].([]string)[b] { + return false + } + case "Float64": + if s.dataStore[o].([]float64)[a] > s.dataStore[o].([]float64)[b] { + return false + } + } + } + return true +} + +func GetColumnLength(column any) int { + switch column := column.(type) { + case []string: + return len(column) + case []int64: + return len(column) + case []uint64: + return len(column) + case []float64: + return len(column) + default: + return 0 + } +} + +func validateData(table *model.Table, columns map[string]any) error { + + fieldMap := make(map[string]string) + for _, field := range table.Fields { + fieldMap[field[0]] = field[1] + } + + // Check if columns map size matches the table.Fields size + if len(columns) != len(table.Fields) { + return errors.New("columns size does not match table fields size") + } + + var ( + dataLength int + first = true + ) + for _, data := range columns { + if first { + dataLength = GetColumnLength(data) + first = false + continue + } + if GetColumnLength(data) != dataLength { + return errors.New("columns length mismatch") + } + } + for column, data := range columns { + + // Validate if the column exists in the table definition + columnType, ok := fieldMap[column] + if !ok { + return fmt.Errorf("invalid column: %s", column) + } + // Validate data types for each column + switch columnType { + case "UInt64": + if _, ok := data.([]uint64); !ok { + return fmt.Errorf("invalid data type for column %s: expected uint64", column) + } + case "Int64": + if _, ok := data.([]int64); !ok { + return fmt.Errorf("invalid data type for column %s: expected int64", column) + } + case "String": + if _, ok := data.([]string); !ok { + return fmt.Errorf("invalid data type for column %s: expected string", column) + } + case "Float64": + if _, ok := data.([]float64); !ok { + return fmt.Errorf("invalid data type for column %s: expected float64", column) + } + default: + return fmt.Errorf("unsupported column type: %s", columnType) + } + } + + return nil +} + +func (s *MergeTreeService) createParquetSchema() *arrow.Schema { + fields := make([]arrow.Field, len(s.Table.Fields)) + for i, field := range s.Table.Fields { + var fieldType arrow.DataType + switch field[1] { + case "UInt64": + fieldType = arrow.PrimitiveTypes.Uint64 + case "Int64": + fieldType = arrow.PrimitiveTypes.Int64 + case "String": + fieldType = arrow.BinaryTypes.String + case "Float64": + fieldType = arrow.PrimitiveTypes.Float64 + default: + panic(fmt.Sprintf("unsupported field type: %s", field[1])) + } + fields[i] = arrow.Field{Name: field[0], Type: fieldType} + } + return arrow.NewSchema(fields, nil) +} + +func (s *MergeTreeService) writeParquetFile(columns map[string]any) *promise.Promise[int32] { + s.mtx.Lock() + defer s.mtx.Unlock() + var oldSize, newSize int32 + for k, v := range columns { + tp := getFieldType(s.Table, k) + switch tp { + case "UInt64": + oldSize = int32(len(s.dataStore[k].([]uint64))) + s.dataStore[k] = append(s.dataStore[k].([]uint64), v.([]uint64)...) + newSize = int32(len(s.dataStore[k].([]uint64))) + case "Int64": + oldSize = int32(len(s.dataStore[k].([]int64))) + s.dataStore[k] = append(s.dataStore[k].([]int64), v.([]int64)...) + newSize = int32(len(s.dataStore[k].([]int64))) + case "String": + oldSize = int32(len(s.dataStore[k].([]string))) + s.dataStore[k] = append(s.dataStore[k].([]string), v.([]string)...) + newSize = int32(len(s.dataStore[k].([]string))) + case "Float64": + oldSize = int32(len(s.dataStore[k].([]float64))) + s.dataStore[k] = append(s.dataStore[k].([]float64), v.([]float64)...) + newSize = int32(len(s.dataStore[k].([]float64))) + } + } + for i := oldSize; i < newSize; i++ { + s.dataIndexes.Set(i) + } + + p := promise.New[int32]() + s.promises = append(s.promises, p) + return p +} + +func (s *MergeTreeService) flush() { + s.mtx.Lock() + dataStore := s.dataStore + indexes := s.dataIndexes + s.dataStore = s.createDataStore() + s.dataIndexes = btree.NewBTreeG(s.Less) + promises := s.promises + s.promises = nil + s.mtx.Unlock() + onError := func(err error) { + for _, p := range promises { + p.Done(0, err) + } + } + if indexes.Len() == 0 { + onError(nil) + return + } + for i, f := range s.Table.Fields { + it := indexes.Iter() + switch f[1] { + case "UInt64": + _data := dataStore[f[0]].([]uint64) + for it.Next() { + s.recordBatch.Field(i).(*array.Uint64Builder).Append(_data[it.Item()]) + } + case "Int64": + _data := dataStore[f[0]].([]int64) + for it.Next() { + s.recordBatch.Field(i).(*array.Int64Builder).Append(_data[it.Item()]) + } + case "String": + _data := dataStore[f[0]].([]string) + for it.Next() { + s.recordBatch.Field(i).(*array.StringBuilder).Append(_data[it.Item()]) + } + case "Float64": + _data := dataStore[f[0]].([]float64) + for it.Next() { + s.recordBatch.Field(i).(*array.Float64Builder).Append(_data[it.Item()]) + } + } + } + record := s.recordBatch.NewRecord() + defer record.Release() + if record.Column(0).Data().Len() == 0 { + onError(nil) + return + } + fileName := s.Table.Name + uuid.New().String() + ".1.parquet" + outputTmpFile := filepath.Join(s.Table.Path, "data", fileName) + outputFile := filepath.Join(s.Table.Path, "data", fileName) + file, err := os.Create(outputTmpFile)
## Uncontrolled data used in path expression This path depends on a [user-provided value](1). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/7)
quackpipe
github_2023
go
40
metrico
github-advanced-security[bot]
@@ -0,0 +1,546 @@ +package service + +import ( + "context" + "errors" + "fmt" + "github.com/apache/arrow/go/v18/arrow" + "github.com/apache/arrow/go/v18/arrow/array" + "github.com/apache/arrow/go/v18/arrow/memory" + "github.com/apache/arrow/go/v18/parquet" + "github.com/apache/arrow/go/v18/parquet/pqarrow" + "github.com/google/uuid" + _ "github.com/marcboeker/go-duckdb" + "github.com/tidwall/btree" + "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" + "os" + "path/filepath" + "quackpipe/model" + "quackpipe/service/db" + "quackpipe/utils/promise" + "sort" + "strings" + "sync" + "sync/atomic" + "time" +) + +type IMergeTree interface { + Store(columns map[string][]any) error + Merge() error + Run() + Stop() +} + +type MergeTreeService struct { + Table *model.Table + ticker *time.Ticker + working uint32 + promises []*promise.Promise[int32] + recordBatch *array.RecordBuilder + mtx sync.Mutex + schema *arrow.Schema + lastIterationTime [3]time.Time + dataIndexes *btree.BTreeG[int32] + dataStore map[string]any +} + +func NewMergeTreeService(t *model.Table) *MergeTreeService { + res := &MergeTreeService{ + Table: t, + working: 0, + promises: []*promise.Promise[int32]{}, + recordBatch: nil, + } + res.dataStore = res.createDataStore() + res.dataIndexes = btree.NewBTreeG(res.Less) + res.schema = res.createParquetSchema() + pool := memory.NewGoAllocator() + res.recordBatch = array.NewRecordBuilder(pool, res.schema) + + return res +} + +func (s *MergeTreeService) createDataStore() map[string]any { + res := make(map[string]any) + for _, f := range s.Table.Fields { + switch f[1] { + case "UInt64": + res[f[0]] = make([]uint64, 0, 1000000) + case "Int64": + res[f[0]] = make([]int64, 0, 1000000) + case "String": + res[f[0]] = make([]string, 0, 1000000) + case "Float64": + res[f[0]] = make([]float64, 0, 1000000) + } + } + return res +} + +func (s *MergeTreeService) size() int32 { + return int32(s.dataIndexes.Len()) +} + +func getFieldType(t *model.Table, fieldName string) string { + for _, field := range t.Fields { + if field[0] == fieldName { + return field[1] + } + } + return "" +} + +func (s *MergeTreeService) Less(a, b int32) bool { + for _, o := range s.Table.OrderBy { + t := getFieldType(s.Table, o) + switch t { + case "UInt64": + if s.dataStore[o].([]uint64)[a] > s.dataStore[o].([]uint64)[b] { + return false + } + case "Int64": + if s.dataStore[o].([]int64)[a] > s.dataStore[o].([]int64)[b] { + return false + } + case "String": + if s.dataStore[o].([]string)[a] > s.dataStore[o].([]string)[b] { + return false + } + case "Float64": + if s.dataStore[o].([]float64)[a] > s.dataStore[o].([]float64)[b] { + return false + } + } + } + return true +} + +func GetColumnLength(column any) int { + switch column := column.(type) { + case []string: + return len(column) + case []int64: + return len(column) + case []uint64: + return len(column) + case []float64: + return len(column) + default: + return 0 + } +} + +func validateData(table *model.Table, columns map[string]any) error { + + fieldMap := make(map[string]string) + for _, field := range table.Fields { + fieldMap[field[0]] = field[1] + } + + // Check if columns map size matches the table.Fields size + if len(columns) != len(table.Fields) { + return errors.New("columns size does not match table fields size") + } + + var ( + dataLength int + first = true + ) + for _, data := range columns { + if first { + dataLength = GetColumnLength(data) + first = false + continue + } + if GetColumnLength(data) != dataLength { + return errors.New("columns length mismatch") + } + } + for column, data := range columns { + + // Validate if the column exists in the table definition + columnType, ok := fieldMap[column] + if !ok { + return fmt.Errorf("invalid column: %s", column) + } + // Validate data types for each column + switch columnType { + case "UInt64": + if _, ok := data.([]uint64); !ok { + return fmt.Errorf("invalid data type for column %s: expected uint64", column) + } + case "Int64": + if _, ok := data.([]int64); !ok { + return fmt.Errorf("invalid data type for column %s: expected int64", column) + } + case "String": + if _, ok := data.([]string); !ok { + return fmt.Errorf("invalid data type for column %s: expected string", column) + } + case "Float64": + if _, ok := data.([]float64); !ok { + return fmt.Errorf("invalid data type for column %s: expected float64", column) + } + default: + return fmt.Errorf("unsupported column type: %s", columnType) + } + } + + return nil +} + +func (s *MergeTreeService) createParquetSchema() *arrow.Schema { + fields := make([]arrow.Field, len(s.Table.Fields)) + for i, field := range s.Table.Fields { + var fieldType arrow.DataType + switch field[1] { + case "UInt64": + fieldType = arrow.PrimitiveTypes.Uint64 + case "Int64": + fieldType = arrow.PrimitiveTypes.Int64 + case "String": + fieldType = arrow.BinaryTypes.String + case "Float64": + fieldType = arrow.PrimitiveTypes.Float64 + default: + panic(fmt.Sprintf("unsupported field type: %s", field[1])) + } + fields[i] = arrow.Field{Name: field[0], Type: fieldType} + } + return arrow.NewSchema(fields, nil) +} + +func (s *MergeTreeService) writeParquetFile(columns map[string]any) *promise.Promise[int32] { + s.mtx.Lock() + defer s.mtx.Unlock() + var oldSize, newSize int32 + for k, v := range columns { + tp := getFieldType(s.Table, k) + switch tp { + case "UInt64": + oldSize = int32(len(s.dataStore[k].([]uint64))) + s.dataStore[k] = append(s.dataStore[k].([]uint64), v.([]uint64)...) + newSize = int32(len(s.dataStore[k].([]uint64))) + case "Int64": + oldSize = int32(len(s.dataStore[k].([]int64))) + s.dataStore[k] = append(s.dataStore[k].([]int64), v.([]int64)...) + newSize = int32(len(s.dataStore[k].([]int64))) + case "String": + oldSize = int32(len(s.dataStore[k].([]string))) + s.dataStore[k] = append(s.dataStore[k].([]string), v.([]string)...) + newSize = int32(len(s.dataStore[k].([]string))) + case "Float64": + oldSize = int32(len(s.dataStore[k].([]float64))) + s.dataStore[k] = append(s.dataStore[k].([]float64), v.([]float64)...) + newSize = int32(len(s.dataStore[k].([]float64))) + } + } + for i := oldSize; i < newSize; i++ { + s.dataIndexes.Set(i) + } + + p := promise.New[int32]() + s.promises = append(s.promises, p) + return p +} + +func (s *MergeTreeService) flush() { + s.mtx.Lock() + dataStore := s.dataStore + indexes := s.dataIndexes + s.dataStore = s.createDataStore() + s.dataIndexes = btree.NewBTreeG(s.Less) + promises := s.promises + s.promises = nil + s.mtx.Unlock() + onError := func(err error) { + for _, p := range promises { + p.Done(0, err) + } + } + if indexes.Len() == 0 { + onError(nil) + return + } + for i, f := range s.Table.Fields { + it := indexes.Iter() + switch f[1] { + case "UInt64": + _data := dataStore[f[0]].([]uint64) + for it.Next() { + s.recordBatch.Field(i).(*array.Uint64Builder).Append(_data[it.Item()]) + } + case "Int64": + _data := dataStore[f[0]].([]int64) + for it.Next() { + s.recordBatch.Field(i).(*array.Int64Builder).Append(_data[it.Item()]) + } + case "String": + _data := dataStore[f[0]].([]string) + for it.Next() { + s.recordBatch.Field(i).(*array.StringBuilder).Append(_data[it.Item()]) + } + case "Float64": + _data := dataStore[f[0]].([]float64) + for it.Next() { + s.recordBatch.Field(i).(*array.Float64Builder).Append(_data[it.Item()]) + } + } + } + record := s.recordBatch.NewRecord() + defer record.Release() + if record.Column(0).Data().Len() == 0 { + onError(nil) + return + } + fileName := s.Table.Name + uuid.New().String() + ".1.parquet" + outputTmpFile := filepath.Join(s.Table.Path, "data", fileName) + outputFile := filepath.Join(s.Table.Path, "data", fileName) + file, err := os.Create(outputTmpFile) + if err != nil { + onError(err) + return + } + defer file.Close() + // Set up Parquet writer properties + writerProps := parquet.NewWriterProperties( + parquet.WithMaxRowGroupLength(100), + ) + arrprops := pqarrow.NewArrowWriterProperties() + + // Create Parquet file writer + writer, err := pqarrow.NewFileWriter(s.schema, file, writerProps, arrprops) + if err != nil { + onError(err) + return + } + defer writer.Close() + err = writer.Write(record) + if err != nil { + onError(err) + return + } + onError(os.Rename(outputTmpFile, outputFile))
## Uncontrolled data used in path expression This path depends on a [user-provided value](1). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/8)
quackpipe
github_2023
go
27
metrico
github-advanced-security[bot]
@@ -0,0 +1,53 @@ +package db + +import ( + "context" + "database/sql" + "os" + "quackpipe/model" + "time" +) + +func Quack(appFlags model.CommandLineFlags, query string, stdin bool, params string, hashdb string) (*sql.Rows, time.Duration, error) { + var err error + alias := *appFlags.Alias + motherduck, md := os.LookupEnv("motherduck_token") + + if len(hashdb) > 0 { + params = hashdb + "?" + params + } + + db, err := sql.Open("duckdb", params) + if err != nil { + return nil, 0, err + } + defer db.Close() + + if !stdin { + check(db.ExecContext(context.Background(), "LOAD httpfs; LOAD json; LOAD parquet;")) + check(db.ExecContext(context.Background(), "SET autoinstall_known_extensions=1;")) + check(db.ExecContext(context.Background(), "SET autoload_known_extensions=1;")) + } + + if alias { + check(db.ExecContext(context.Background(), "LOAD chsql;")) + } + + if (md) && (motherduck != "") { + check(db.ExecContext(context.Background(), "LOAD motherduck; ATTACH 'md:';")) + } + startTime := time.Now() + rows, err := db.QueryContext(context.Background(), query)
## Database query built from user-controlled sources This query depends on a [user-provided value](1). This query depends on a [user-provided value](2). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/4)
quackpipe
github_2023
go
27
metrico
lmangani
@@ -31,7 +31,7 @@ func QueryOperation(flagInformation *model.CommandLineFlags, query string, r *ht } if len(query) == 0 { - return "", errors.New("query length is empty")
This should be maintained. If the query parameter is provided empty an error should be returned.
quackpipe
github_2023
go
27
metrico
lmangani
@@ -0,0 +1,50 @@ +package root + +import ( + "crypto/sha256" + "errors" + "fmt" + "net/http" + "quackpipe/model" + "quackpipe/service/db" + "quackpipe/utils" +) + +func QueryOperation(flagInformation *model.CommandLineFlags, query string, r *http.Request, defaultPath string, defaultFormat string, defaultParams string) (string, error) { + // auth to hash based temp file storage + username, password, ok := r.BasicAuth() + hashdb := "" + if ok && len(password) > 0 { + hash := sha256.Sum256([]byte(username + password)) + hashdb = fmt.Sprintf("%s/%x.db", defaultPath, hash) + } + // extract FORMAT from query and override the current `default_format` + cleanQuery, format := utils.ExtractAndRemoveFormat(query) + if len(format) > 0 { + query = cleanQuery + defaultFormat = format + } + + if len(format) > 0 { + query = cleanQuery + defaultFormat = format + } + + if len(query) == 0 { + return "", errors.New("")
The error should be maintained. If the query parameter is provided empty an error should be returned.
quackpipe
github_2023
go
24
metrico
github-advanced-security[bot]
@@ -54,15 +63,17 @@ defer db.Close() if !stdin { - check(db.Exec("LOAD httpfs; LOAD json; LOAD parquet;")) + check(db.ExecContext(context.Background(),"LOAD httpfs; LOAD json; LOAD parquet;")) + check(db.ExecContext(context.Background(),"SET autoinstall_known_extensions=1;")) + check(db.ExecContext(context.Background(),"SET autoload_known_extensions=1;")) } - - if staticAliases != "" { - check(db.Exec(staticAliases)) + + if (alias) && (staticAliases != "") { + check(db.ExecContext(context.Background(), staticAliases)) } - + startTime := time.Now() - rows, err := db.Query(query) + rows, err := db.QueryContext(context.Background(), query)
## Database query built from user-controlled sources This query depends on a [user-provided value](1). This query depends on a [user-provided value](2). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/3)
quackpipe
github_2023
go
19
metrico
github-advanced-security[bot]
@@ -1,361 +1,336 @@ package main import ( - "bufio" - "database/sql" - _ "embed" - "encoding/json" - "flag" - "fmt" - "io/ioutil" - "log" - "net/http" - "os" - "regexp" - "strings" - "time" - - _ "github.com/marcboeker/go-duckdb" // load duckdb driver + "context" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/csv" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "strings" + "sync" + "time" + + _ "github.com/mattn/go-duckdb" ) -//go:embed play.html -var staticPlay string +type Session struct { + DB *sql.DB +} + +var sessionCache sync.Map -//go:embed aliases.sql -var staticAliases string +func main() { + http.HandleFunc("/query", basicAuth(queryHandler)) -// params for Flags -type CommandLineFlags struct { - Host *string `json:"host"` - Port *string `json:"port"` - Stdin *bool `json:"stdin"` - Format *string `json:"format"` - Params *string `json:"params"` + // Existing endpoints for backwards compatibility + http.HandleFunc("/start_session", startSessionHandler) + http.HandleFunc("/close_session", closeSessionHandler) + + fmt.Println("Starting server on :8080") + http.ListenAndServe(":8080", nil) } -var appFlags CommandLineFlags +func basicAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + if auth == "" { + http.Error(w, "authorization required", http.StatusUnauthorized) + return + } + + parts := strings.SplitN(auth, " ", 2) + if len(parts) != 2 || parts[0] != "Basic" { + http.Error(w, "invalid authorization header", http.StatusUnauthorized) + return + } + + payload, _ := base64.StdEncoding.DecodeString(parts[1]) + authStr := string(payload) + sessionID := hashCredentials(authStr) + + session, err := getSession(sessionID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + r.Header.Set("X-Session-ID", sessionID) + r = r.WithContext(context.WithValue(r.Context(), "session", session)) + + next.ServeHTTP(w, r) + } +} -var db *sql.DB +func hashCredentials(auth string) string { + hash := sha256.Sum256([]byte(auth)) + return hex.EncodeToString(hash[:]) +} -func check(args ...interface{}) { - err := args[len(args)-1] - if err != nil { - panic(err) - } +func getSession(sessionID string) (*Session, error) { + if session, ok := sessionCache.Load(sessionID); ok { + return session.(*Session), nil + } + + db, err := sql.Open("duckdb", "") + if err != nil { + return nil, err + } + + session := &Session{DB: db} + sessionCache.Store(sessionID, session) + + return session, nil } -func quack(query string, stdin bool, format string, params string) (string, error) { - var err error +func queryHandler(w http.ResponseWriter, r *http.Request) { + sessionID := r.Header.Get("X-Session-ID") + query := r.URL.Query().Get("query") + format := r.URL.Query().Get("format") - db, err = sql.Open("duckdb", params) - if err != nil { - log.Fatal(err) - } - defer db.Close() + if format == "" { + format = "json" + } - if !stdin { - check(db.Exec("LOAD httpfs; LOAD json; LOAD parquet;")) - } - - if staticAliases != "" { - check(db.Exec(staticAliases)) - } - - startTime := time.Now() - rows, err := db.Query(query) - if err != nil { - return "", err - } - elapsedTime := time.Since(startTime) - - switch format { - case "JSONCompact", "JSON": - return rowsToJSON(rows, elapsedTime) - case "CSVWithNames": - return rowsToCSV(rows, true) - case "TSVWithNames", "TabSeparatedWithNames": - return rowsToTSV(rows, true) - case "TSV", "TabSeparated": - return rowsToTSV(rows, false) - default: - return rowsToTSV(rows, false) - } + session := r.Context().Value("session").(*Session) + result, err := quackWithDB(session.DB, query, format) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.Write([]byte(result)) } -// initFlags initializes the command line flags -func initFlags() { - appFlags.Host = flag.String("host", "0.0.0.0", "API host. Default 0.0.0.0") - appFlags.Port = flag.String("port", "8123", "API port. Default 8123") - appFlags.Format = flag.String("format", "JSONCompact", "API port. Default JSONCompact") - appFlags.Params = flag.String("params", "", "DuckDB optional parameters. Default to none.") - appFlags.Stdin = flag.Bool("stdin", false, "STDIN query. Default false") - flag.Parse() +func quackWithDB(db *sql.DB, query string, format string) (string, error) { + startTime := time.Now() + rows, err := db.Query(query)
## Database query built from user-controlled sources This query depends on a [user-provided value](1). [Show more details](https://github.com/metrico/quackpipe/security/code-scanning/2)
obsidian-copilot
github_2023
typescript
1,315
logancyang
logancyang
@@ -80,3 +93,28 @@ export function turnOffPlus(): void { new CopilotPlusExpiredModal(app).open(); } } + +export async function getComposerSystemPrompt(): Promise<string> { + // Get the current system prompt + const currentSystemPrompt = getSystemPrompt(); + + // If we already have a cached composer prompt, use it + if (cachedComposerPrompt) { + return `${currentSystemPrompt}\n${cachedComposerPrompt}`; + } + + // Otherwise, fetch it from the API + const brevilabsClient = BrevilabsClient.getInstance(); + try { + // Get the composer prompt from the API + const composerPromptResponse = await brevilabsClient.composerPrompt(); + cachedComposerPrompt = composerPromptResponse.prompt;
Should we persist this on disk just like how `/pdf4llm` cache works? Just need the simplest invalidation mechanism for now. Ideally we need every way possible to make it faster.
obsidian-copilot
github_2023
others
1,315
logancyang
zeroliu
@@ -98,12 +98,14 @@ "@radix-ui/react-switch": "^1.1.1", "@radix-ui/react-tooltip": "^1.1.6", "@tabler/icons-react": "^2.14.0", + "@types/diff": "^7.0.1",
this should be a dev dependency
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -194,4 +215,12 @@ export class BrevilabsClient { async youtube4llm(url: string): Promise<Youtube4llmResponse> { return this.makeRequest<Youtube4llmResponse>("/youtube4llm", { url }); } + + async composerPrompt(): Promise<ComposerPromptResponse> { + return this.makeRequest<ComposerPromptResponse>("/composer/prompt", {}, "GET"); + } + + async composerApply(request: ComposerApplyRequest): Promise<ComposerApplyResponse> { + return this.makeRequest<ComposerApplyResponse>("/composer/apply", request); + }
The latest brevilabs client changed makeRequest to return both data and error. The wrapper functions here need to handle the error too
obsidian-copilot
github_2023
others
1,315
logancyang
zeroliu
@@ -872,3 +896,125 @@ If your plugin does not need CSS, delete this file. color: var(--text-error); opacity: 1; } + +/* Apply View Styles */ +.apply-view-container {
We already standardized styling to tailwindcss. All existing CSS class names only exist for legacy reasons. No changes should be introduced to tailwind.css in this PR.
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -203,6 +296,85 @@ const ChatSingleMessage: React.FC<ChatSingleMessageProps> = ({ "", // Empty string for sourcePath as we don't have a specific source file componentRef.current ); + + // Function to add apply buttons to code blocks + const addApplyButtonsToCodeBlocks = () => { + if (!contentRef.current) return; + + // Find all pre elements (code blocks) in the rendered content + const codeBlocks = contentRef.current.querySelectorAll("pre");
interacting with the raw DOM element in the react component can be very error-prone. Is there any reason why it needed to be implemented this instead of relying on React functions?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,351 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container"); + + const rootEl = container.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} /> + ); + } +} + +interface ApplyViewRootProps { + app: App; + state: ApplyViewState; + close: () => void; +} + +const ApplyViewRoot: React.FC<ApplyViewRootProps> = ({ app, state, close }) => { + // Initialize diff with extended properties + const [diff, setDiff] = useState<ExtendedChange[]>(() => { + const initialDiff = diffLines(state.originalContent, state.newContent); + return initialDiff.map((change) => ({ + ...change, + accepted: false, + rejected: false, + })); + }); + + // Group changes into blocks for better UI presentation + const [changeBlocks, setChangeBlocks] = useState<ExtendedChange[][]>([]); + + // Calculate summary statistics + const [summary, setSummary] = useState({ + totalChanges: 0, + additions: 0, + deletions: 0, + accepted: 0, + rejected: 0, + }); + + // Update summary when diff changes + useEffect(() => { + const additions = diff.filter((change) => change.added).length; + const deletions = diff.filter((change) => change.removed).length; + const accepted = diff.filter((change) => change.accepted).length; + const rejected = diff.filter((change) => change.rejected).length; + + setSummary({ + totalChanges: additions + deletions, + additions, + deletions, + accepted, + rejected, + }); + }, [diff]); + + // Process diff into blocks of related changes + useEffect(() => { + const blocks: ExtendedChange[][] = []; + let currentBlock: ExtendedChange[] = []; + let inChangeBlock = false; + + diff.forEach((change) => { + if (change.added || change.removed) { + if (!inChangeBlock) { + inChangeBlock = true; + currentBlock = []; + } + currentBlock.push(change); + } else { + if (inChangeBlock) { + blocks.push([...currentBlock]); + currentBlock = []; + inChangeBlock = false; + } + blocks.push([change]); + } + }); + + if (currentBlock.length > 0) { + blocks.push(currentBlock); + } + + setChangeBlocks(blocks); + }, [diff]); + + // Handle accepting all changes that have been marked as accepted + const handleAccept = async () => { + try { + // Filter out rejected changes and properly handle accepted removals + const newContent = diff + .filter((change) => { + // Keep changes that are not rejected + if (change.rejected) return false; + + // For removed changes, we want to exclude them when accepted + // (since accepting a removal means we want to remove that content) + if (change.removed) return !change.accepted; + + // For added changes, we want to include them when accepted + if (change.added) return change.accepted; + + // Keep unchanged content + return true; + }) + .map((change) => change.value) + .join(""); + + await app.vault.modify(state.file, newContent); + new Notice("Changes applied successfully"); + close(); + } catch (error) { + console.error("Error applying changes:", error); + new Notice(`Error applying changes: ${error.message}`); + } + }; + + // Handle rejecting all changes + const handleReject = () => { + close(); + }; + + // Accept a block of changes + const acceptBlock = (blockIndex: number) => { + setDiff((prevDiff) => { + const newDiff = [...prevDiff]; + const block = changeBlocks[blockIndex]; + + // Find the indices of the changes in this block + block.forEach((blockChange) => { + const index = newDiff.findIndex((change) => change === blockChange); + if (index !== -1) { + newDiff[index] = { + ...newDiff[index], + accepted: true, + rejected: false, + }; + } + }); + + return newDiff; + }); + }; + + // Reject a block of changes + const rejectBlock = (blockIndex: number) => { + setDiff((prevDiff) => { + const newDiff = [...prevDiff]; + const block = changeBlocks[blockIndex]; + + // Find the indices of the changes in this block + block.forEach((blockChange) => { + const index = newDiff.findIndex((change) => change === blockChange); + if (index !== -1) { + newDiff[index] = { + ...newDiff[index], + accepted: false, + rejected: true, + }; + } + }); + + return newDiff; + }); + }; + + return ( + <div className="apply-view flex flex-col h-full"> + <div className="apply-view-header flex justify-between items-center p-2 border-b border-border"> + <div className="flex items-center"> + <h3 className="m-0 text-lg font-medium"> + Apply Changes to {state.path || state.file.path} + </h3> + </div> + <div className="flex gap-2"> + <Button variant="secondary" onClick={handleReject}> + <XIcon className="mr-1 h-4 w-4" /> + Reject All + </Button> + <Button onClick={handleAccept}> + <Check className="mr-1 h-4 w-4" /> + Apply Accepted Changes + </Button> + </div> + </div> + + {/* Summary section */} + <div className="apply-view-summary p-2 border-b border-border bg-background-secondary-alt"> + <div className="flex flex-wrap gap-4 text-sm"> + <div className="flex items-center"> + <span className="font-medium mr-1">Changes:</span> {summary.totalChanges} + </div> + <div className="flex items-center"> + <span className="text-green-600 mr-1">+{summary.additions}</span> additions + </div> + <div className="flex items-center"> + <span className="text-red-600 mr-1">-{summary.deletions}</span> deletions + </div> + <div className="flex items-center"> + <span className="font-medium mr-1">Status:</span> + <span className="text-green-600 mr-1">{summary.accepted}</span> accepted, + <span className="text-red-600 ml-1 mr-1">{summary.rejected}</span> rejected + </div> + </div> + </div> + + <div className="apply-view-content flex-1 overflow-auto p-2"> + {changeBlocks.map((block, blockIndex) => { + // Check if this block contains any changes (added or removed) + const hasChanges = block.some((change) => change.added || change.removed); + + // Check if all changes in this block are accepted or rejected + const isAccepted = hasChanges && block.every((change) => change.accepted); + const isRejected = hasChanges && block.every((change) => change.rejected); + + return ( + <div + key={blockIndex} + className={cn("diff-block mb-4 border rounded-md overflow-hidden", { + "border-green-500 accepted": isAccepted, + "border-red-500 rejected": isRejected, + "border-gray-300": !isAccepted && !isRejected,
tokens like green-500, red-500, gray-300 are not valid tokens in our design system. We should use the ones configured in the design system.
obsidian-copilot
github_2023
others
1,315
logancyang
zeroliu
@@ -872,3 +896,125 @@ If your plugin does not need CSS, delete this file. color: var(--text-error); opacity: 1; } + +/* Apply View Styles */ +.apply-view-container { + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; +} + +.apply-view { + font-size: var(--font-text-size); + line-height: var(--line-height-normal); +} + +.diff-block { + background-color: var(--background-primary); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + margin-bottom: 12px; + transition: border-color 0.2s ease; +} + +.diff-block.accepted { + border: 1px solid var(--color-green); + box-shadow: 0 0 5px rgba(0, 128, 0, 0.2); +} + +.diff-block.rejected { + border: 1px solid var(--color-red); + box-shadow: 0 0 5px rgba(255, 0, 0, 0.2); +} + +.diff-line { + padding: 0; + position: relative; + border-left: 3px solid transparent; +} + +.diff-line.added { + background-color: rgba(0, 128, 0, 0.15); + border-left-color: var(--color-green); +} + +.diff-line.removed { + background-color: rgba(255, 0, 0, 0.15); + border-left-color: var(--color-red); +} + +.diff-line-indicator { + color: var(--text-normal); + font-weight: bold; + background-color: rgba(0, 0, 0, 0.05); + width: 24px; + text-align: center; +} + +.diff-line.added .diff-line-indicator { + color: var(--color-green); + background-color: rgba(0, 128, 0, 0.1); +} + +.diff-line.removed .diff-line-indicator { + color: var(--color-red); + background-color: rgba(255, 0, 0, 0.1); +} + +.diff-content { + font-family: var(--font-monospace); + font-size: 0.9em; +} + +.diff-block-actions { + background-color: var(--background-secondary-alt); + padding: 4px 8px; + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.apply-code-button { + position: absolute; + top: 0; + right: 0; + background-color: var(--interactive-accent); + color: var(--text-on-accent); + border: none; + border-radius: 0 4px 0 4px; + padding: 2px 8px; + font-size: 12px; + cursor: pointer; + z-index: 10; +} + +.apply-code-button:hover { + background-color: var(--interactive-accent-hover); +} + +pre { + position: relative; +} + +.code-path-indicator { + background-color: var(--background-secondary); + border-radius: 4px 4px 0 0; +} + +/* Add styles for the summary section */ +.apply-view-summary { + background-color: var(--background-secondary-alt); + padding: 8px 12px; + border-bottom: 1px solid var(--background-modifier-border); + margin-bottom: 12px; +} + +.apply-view-summary .text-green-600 {
We do not allow adding classnames like this. This breaks how we work with tailwindcss. There are existing tokens that work for the color that you need. I highly recommend take a close look at tailwind.config.js and follow tailwindcss styles.
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + }
is this function used somewhere?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container");
do we need this class?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1];
why `this.containerEl.children[1];`? Is this deterministic? what other children does the container element have?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container"); + + const rootEl = container.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} />
I don't see how this.state is set. `setState` is not called in this PR and it's not coming from constructor.
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container"); + + const rootEl = container.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} /> + ); + } +} + +interface ApplyViewRootProps { + app: App; + state: ApplyViewState; + close: () => void; +} + +const ApplyViewRoot: React.FC<ApplyViewRootProps> = ({ app, state, close }) => { + // Initialize diff with extended properties - moved before conditional + const [diff, setDiff] = useState<ExtendedChange[]>(() => { + if (!state?.originalContent || !state?.newContent) { + return []; + } + const initialDiff = diffLines(state.originalContent, state.newContent); + return initialDiff.map((change) => ({ + ...change, + accepted: true, + rejected: false, + })); + }); + + // Group changes into blocks for better UI presentation + const [changeBlocks, setChangeBlocks] = useState<ExtendedChange[][]>([]); + + // Process diff into blocks of related changes + useEffect(() => { + if (!diff.length) return; + + const blocks: ExtendedChange[][] = []; + let currentBlock: ExtendedChange[] = []; + let inChangeBlock = false; + + diff.forEach((change) => { + if (change.added || change.removed) { + if (!inChangeBlock) { + inChangeBlock = true; + currentBlock = []; + } + currentBlock.push(change); + } else { + if (inChangeBlock) { + blocks.push([...currentBlock]); + currentBlock = []; + inChangeBlock = false; + } + blocks.push([change]); + } + }); + + if (currentBlock.length > 0) { + blocks.push(currentBlock); + } + + setChangeBlocks(blocks); + }, [diff]); + + // Add defensive check for state after hooks
How would the UI enter this state?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container"); + + const rootEl = container.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} /> + ); + } +} + +interface ApplyViewRootProps { + app: App; + state: ApplyViewState; + close: () => void; +} + +const ApplyViewRoot: React.FC<ApplyViewRootProps> = ({ app, state, close }) => { + // Initialize diff with extended properties - moved before conditional + const [diff, setDiff] = useState<ExtendedChange[]>(() => { + if (!state?.originalContent || !state?.newContent) { + return []; + } + const initialDiff = diffLines(state.originalContent, state.newContent); + return initialDiff.map((change) => ({ + ...change, + accepted: true, + rejected: false, + })); + }); + + // Group changes into blocks for better UI presentation + const [changeBlocks, setChangeBlocks] = useState<ExtendedChange[][]>([]); + + // Process diff into blocks of related changes + useEffect(() => { + if (!diff.length) return; + + const blocks: ExtendedChange[][] = []; + let currentBlock: ExtendedChange[] = []; + let inChangeBlock = false; + + diff.forEach((change) => { + if (change.added || change.removed) { + if (!inChangeBlock) { + inChangeBlock = true; + currentBlock = []; + } + currentBlock.push(change); + } else { + if (inChangeBlock) { + blocks.push([...currentBlock]); + currentBlock = []; + inChangeBlock = false; + } + blocks.push([change]); + } + }); + + if (currentBlock.length > 0) { + blocks.push(currentBlock); + } + + setChangeBlocks(blocks); + }, [diff]); + + // Add defensive check for state after hooks + if (!state || !state.originalContent || !state.newContent) { + console.error("Invalid state:", state); + return ( + <div className="flex flex-col h-full items-center justify-center"> + <div className="text-error">Error: Invalid state - missing content</div> + <Button onClick={close} className="mt-4"> + Close + </Button> + </div> + ); + } + + // Handle accepting all changes that have been marked as accepted + const handleAccept = async () => { + try { + // Filter out rejected changes and include both accepted and unselected changes + const newContent = diff + .filter((change) => { + // Handle rejected changes + if (change.rejected) { + if (change.added) return false; + else if (change.removed) return true; + } + // Handle accepted or unselected changes + if (change.removed) return false; + return true; + }) + .map((change) => change.value) + .join(""); + + await app.vault.modify(state.file, newContent); + new Notice("Changes applied successfully"); + close(); + } catch (error) { + console.error("Error applying changes:", error); + new Notice(`Error applying changes: ${error.message}`); + } + }; + + // Handle rejecting all changes + const handleReject = () => { + close(); + }; + + // Accept a block of changes + const acceptBlock = (blockIndex: number) => { + setDiff((prevDiff) => { + const newDiff = [...prevDiff]; + const block = changeBlocks[blockIndex]; + + // Find the indices of the changes in this block + block.forEach((blockChange) => { + const index = newDiff.findIndex((change) => change === blockChange); + if (index !== -1) { + newDiff[index] = { + ...newDiff[index], + accepted: true, + rejected: false,
why do we need two flags to represent this value? is there a case where accepted and rejected can be same values?
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -0,0 +1,297 @@ +import React, { useState, useEffect } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "./ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted?: boolean; + rejected?: boolean; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + const container = this.containerEl.children[1]; + container.empty(); + container.addClass("apply-view-container"); + + const rootEl = container.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} /> + ); + } +} + +interface ApplyViewRootProps { + app: App; + state: ApplyViewState; + close: () => void; +} + +const ApplyViewRoot: React.FC<ApplyViewRootProps> = ({ app, state, close }) => { + // Initialize diff with extended properties - moved before conditional + const [diff, setDiff] = useState<ExtendedChange[]>(() => { + if (!state?.originalContent || !state?.newContent) { + return []; + } + const initialDiff = diffLines(state.originalContent, state.newContent); + return initialDiff.map((change) => ({ + ...change, + accepted: true, + rejected: false, + })); + }); + + // Group changes into blocks for better UI presentation + const [changeBlocks, setChangeBlocks] = useState<ExtendedChange[][]>([]); + + // Process diff into blocks of related changes + useEffect(() => { + if (!diff.length) return; + + const blocks: ExtendedChange[][] = []; + let currentBlock: ExtendedChange[] = []; + let inChangeBlock = false; + + diff.forEach((change) => { + if (change.added || change.removed) { + if (!inChangeBlock) { + inChangeBlock = true; + currentBlock = []; + } + currentBlock.push(change); + } else { + if (inChangeBlock) { + blocks.push([...currentBlock]); + currentBlock = []; + inChangeBlock = false; + } + blocks.push([change]); + } + }); + + if (currentBlock.length > 0) { + blocks.push(currentBlock); + } + + setChangeBlocks(blocks); + }, [diff]); + + // Add defensive check for state after hooks + if (!state || !state.originalContent || !state.newContent) { + console.error("Invalid state:", state); + return ( + <div className="flex flex-col h-full items-center justify-center"> + <div className="text-error">Error: Invalid state - missing content</div> + <Button onClick={close} className="mt-4"> + Close + </Button> + </div> + ); + } + + // Handle accepting all changes that have been marked as accepted + const handleAccept = async () => { + try { + // Filter out rejected changes and include both accepted and unselected changes + const newContent = diff + .filter((change) => { + // Handle rejected changes + if (change.rejected) { + if (change.added) return false; + else if (change.removed) return true; + } + // Handle accepted or unselected changes + if (change.removed) return false; + return true; + }) + .map((change) => change.value) + .join(""); + + await app.vault.modify(state.file, newContent); + new Notice("Changes applied successfully"); + close(); + } catch (error) { + console.error("Error applying changes:", error); + new Notice(`Error applying changes: ${error.message}`); + } + }; + + // Handle rejecting all changes + const handleReject = () => { + close(); + }; + + // Accept a block of changes + const acceptBlock = (blockIndex: number) => { + setDiff((prevDiff) => { + const newDiff = [...prevDiff]; + const block = changeBlocks[blockIndex]; + + // Find the indices of the changes in this block + block.forEach((blockChange) => { + const index = newDiff.findIndex((change) => change === blockChange); + if (index !== -1) { + newDiff[index] = { + ...newDiff[index], + accepted: true, + rejected: false, + }; + } + }); + + return newDiff; + }); + }; + + // Reject a block of changes + const rejectBlock = (blockIndex: number) => { + setDiff((prevDiff) => { + const newDiff = [...prevDiff]; + const block = changeBlocks[blockIndex]; + + // Find the indices of the changes in this block + block.forEach((blockChange) => { + const index = newDiff.findIndex((change) => change === blockChange); + if (index !== -1) { + newDiff[index] = { + ...newDiff[index], + accepted: false, + rejected: true, + }; + } + }); + + return newDiff; + }); + }; + + return ( + <div className="flex flex-col h-full"> + <div className="flex justify-between items-center p-2 border-b border-border"> + <div className="flex items-center"> + <h3 className="m-0 text-sm font-medium"> + Apply Changes to {state.path || state.file.path} + </h3> + </div> + <div className="flex gap-2"> + <Button variant="secondary" size="sm" onClick={handleReject}> + <XIcon className="mr-1 h-3 w-3" /> + Reject All + </Button> + <Button size="sm" onClick={handleAccept}> + <Check className="mr-1 h-3 w-3" /> + Apply Changes + </Button> + </div> + </div> + + <div className="flex-1 overflow-auto p-2"> + {changeBlocks.map((block, blockIndex) => { + // Check if this block contains any changes (added or removed) + const hasChanges = block.some((change) => change.added || change.removed); + + // Check if all changes in this block are accepted or rejected + const isAccepted = hasChanges && block.every((change) => change.accepted); + const isRejected = hasChanges && block.every((change) => change.rejected); + + return ( + <div + key={blockIndex} + className={cn( + "mb-4 border rounded-md overflow-hidden transition-colors duration-200", + { + "border-green shadow-[0_0_5px_rgba(var(--color-green-rgb),0.2)]": isAccepted, + "border-red shadow-[0_0_5px_rgba(var(--color-red-rgb),0.2)]": isRejected, + } + )} + > + {block.map((change, changeIndex) => ( + <div + key={`${blockIndex}-${changeIndex}`} + className={cn("flex relative border-l-3", { + "bg-modifier-success border-l-green": change.added, + "bg-modifier-error border-l-red": change.removed, + "opacity-50": + (change.added && change.rejected) || (change.removed && !change.accepted), + })} + > + <div className="w-6 flex-shrink-0 flex items-center justify-center text-sm font-bold bg-background-secondary-alt"> + {change.added && "+"} + {change.removed && "-"} + </div> + <div className="flex-1 font-mono text-sm whitespace-pre-wrap py-1 px-2 text-text-normal"> + {change.value} + </div> + </div> + ))} + + {/* Only show accept/reject buttons for blocks with changes */} + {hasChanges && ( + <div className="flex justify-end p-2 bg-background-secondary-alt border-t border-border gap-2"> + <Button variant="secondary" size="sm" onClick={() => rejectBlock(blockIndex)}> + <XIcon className="h-4 w-4" /> + Reject + </Button> + <Button size="sm" onClick={() => acceptBlock(blockIndex)}> + <Check className="h-4 w-4" /> + Accept + </Button> + </div> + )} + </div>
can we apply the change directly in this view when a user accept or reject a block? It's not very clear after a user accepts and rejects the change and what's going to happen
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -80,3 +93,28 @@ export function turnOffPlus(): void { new CopilotPlusExpiredModal(app).open(); } } + +export async function getComposerSystemPrompt(): Promise<string> {
I suggest move anything composer related to its own file. `plusUtil` should only take care of plus user status checks
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -79,6 +85,100 @@ const ChatSingleMessage: React.FC<ChatSingleMessageProps> = ({ }); }; + const handleApplyCode = useCallback(
I would also suggest create a custom hook and move this chunk of code to a separate module under composer. Making composer code more isolated from the core chat.
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -79,6 +85,100 @@ const ChatSingleMessage: React.FC<ChatSingleMessageProps> = ({ }); }; + const handleApplyCode = useCallback( + async (path: string, code: string) => { + try { + // Get the file from the path + const file = app.vault.getAbstractFileByPath(path); + + if (!file || !(file instanceof TFile)) { + new Notice(`File not found: ${path}`); + return; + } + + // Get the original content + const originalContent = await app.vault.read(file); + + // Check if the current active note is the same as the target note + const activeFile = app.workspace.getActiveFile(); + if (!activeFile || activeFile.path !== file.path) { + // If not, open the target file in the current leaf + await app.workspace.getLeaf().openFile(file); + new Notice(`Switched to ${file.name}`); + } + + try { + // Call the composer apply endpoint + const brevilabsClient = BrevilabsClient.getInstance(); + + // Convert chat history to the format expected by the API + const formattedChatHistory = chatHistory + .filter((msg) => msg.isVisible) + .map((msg) => ({ + role: msg.sender === USER_SENDER ? "user" : "assistant", + content: msg.message, + })); + + // Create the request object + const request: ComposerApplyRequest = { + target_note: { + title: file.basename, + content: originalContent, + }, + chat_history: formattedChatHistory, + markdown_block: code, + }; + + // Call the composer apply endpoint + + console.log("==== Composer Request ====\n", request); + const response = await brevilabsClient.composerApply(request); + + // Use the content from the response + let newContent = response.content; + + //TODO: Remove this once the issue is fixed in the backend + // Remove trailing newline from newContent if originalContent doesn't end with one + if (!originalContent.endsWith("\n") && newContent.endsWith("\n")) { + newContent = newContent.slice(0, -1); + } + // Open the Apply View in a new leaf with the processed content + const leaf = app.workspace.getLeaf(true); + await leaf.setViewState({ + type: "obsidian-copilot-apply-view", + active: true, + state: { + file: file, + originalContent: originalContent, + newContent: newContent, + path: path,
```suggestion file, originalContent, newContent, path, ```
obsidian-copilot
github_2023
typescript
1,315
logancyang
zeroliu
@@ -203,6 +303,32 @@ const ChatSingleMessage: React.FC<ChatSingleMessageProps> = ({ "", // Empty string for sourcePath as we don't have a specific source file componentRef.current ); + + // Process code blocks after rendering + const codeBlocks = contentRef.current.querySelectorAll("pre");
is there any reason why we need to escape from react component tree here?
obsidian-copilot
github_2023
others
1,315
logancyang
zeroliu
@@ -432,26 +432,50 @@ If your plugin does not need CSS, delete this file. .message-content pre .copy-code-button {
can you please help me understand why we need the changes in this file still?
obsidian-copilot
github_2023
typescript
1,315
logancyang
logancyang
@@ -0,0 +1,437 @@ +import React, { useState, useMemo, useRef } from "react"; +import { App, ItemView, TFile, WorkspaceLeaf, Notice } from "obsidian"; +import { createRoot } from "react-dom/client"; +import { diffLines, Change } from "diff"; +import { Button } from "../ui/button"; +import { Check, X as XIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { ApplyChangesConfirmModal } from "@/components/modals/ApplyChangesConfirmModal"; +import { logError } from "@/logger"; + +export const APPLY_VIEW_TYPE = "obsidian-copilot-apply-view"; + +export interface ApplyViewState { + file: TFile; + originalContent: string; + newContent: string; + path?: string; +} + +// Extended Change interface to track user decisions +interface ExtendedChange extends Change { + accepted: boolean | null; +} + +export class ApplyView extends ItemView { + private root: ReturnType<typeof createRoot> | null = null; + private state: ApplyViewState | null = null; + + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType(): string { + return APPLY_VIEW_TYPE; + } + + getDisplayText(): string { + return "Apply Changes"; + } + + async setState(state: ApplyViewState) { + this.state = state; + this.render(); + } + + async onOpen() { + this.render(); + } + + async onClose() { + if (this.root) { + this.root.unmount(); + this.root = null; + } + } + + private render() { + if (!this.state) return; + + // The second child is the actual content of the view, and the first child is the title of the view + // NOTE: While no official documentation is found, this seems like a standard pattern across community plugins. + const contentEl = this.containerEl.children[1]; + contentEl.empty(); + + const rootEl = contentEl.createDiv(); + if (!this.root) { + this.root = createRoot(rootEl); + } + + this.root.render( + <ApplyViewRoot app={this.app} state={this.state} close={() => this.leaf.detach()} /> + ); + } +} + +interface ApplyViewRootProps { + app: App; + state: ApplyViewState; + close: () => void; +} + +const ApplyViewRoot: React.FC<ApplyViewRootProps> = ({ app, state, close }) => { + // Initialize diff with extended properties - moved before conditional + const [diff, setDiff] = useState<ExtendedChange[]>(() => { + if (!state?.originalContent || !state?.newContent) { + return []; + } + const initialDiff = diffLines(state.originalContent, state.newContent); + return initialDiff.map((change) => ({ + ...change, + accepted: null, // Start with null (undecided) + })); + }); + + const undecidedChanges = diff.filter( + (change) => (change.added || change.removed) && change.accepted === null + ); + const hasAnyDecidedChanges = diff.some((change) => change.accepted !== null); + + // Group changes into blocks for better UI presentation + const changeBlocks = useMemo(() => { + if (!diff.length) return; + + const blocks: ExtendedChange[][] = []; + let currentBlock: ExtendedChange[] = []; + let inChangeBlock = false; + + diff.forEach((change) => { + if (change.added || change.removed) { + if (!inChangeBlock) { + inChangeBlock = true; + currentBlock = []; + } + currentBlock.push(change); + } else { + if (inChangeBlock) { + blocks.push([...currentBlock]); + currentBlock = []; + inChangeBlock = false; + } + blocks.push([change]); + } + }); + + if (currentBlock.length > 0) { + blocks.push(currentBlock); + } + + return blocks; + }, [diff]); + + // Add refs to track change blocks + const blockRefs = useRef<(HTMLDivElement | null)[]>([]); + console.log(changeBlocks);
Should this be removed
obsidian-copilot
github_2023
typescript
1,145
logancyang
logancyang
@@ -25,255 +40,189 @@ describe("Time Expression Tests", () => { }); describe("Relative Time Ranges", () => { - test("last X days", async () => { - const result = await getTimeRangeMs("last 3 days"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - expect(startDate.toISODate()).toBe("2024-01-12"); - expect(endDate.toISODate()).toBe("2024-01-15"); - }); - - test("past X weeks", async () => { - const result = await getTimeRangeMs("past 2 weeks"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - expect(startDate.toISODate()).toBe("2024-01-01"); - expect(endDate.toISODate()).toBe("2024-01-15"); + test.each([ + // Last X units + { + expression: "last week", + expected: { startDate: "2024-01-08", endDate: "2024-01-14" }, + }, + { + expression: "last month", + expected: { startDate: "2023-12-01", endDate: "2023-12-31" }, + }, + { + expression: "last year", + expected: { startDate: "2023-01-01", endDate: "2023-12-31" }, + }, + { + expression: "last 3 days", + expected: { startDate: "2024-01-12", endDate: "2024-01-15" }, + }, + { + expression: "last 2 weeks", + expected: { startDate: "2024-01-01", endDate: "2024-01-15" }, + }, + { + expression: "last 6 months", + expected: { startDate: "2023-07-15", endDate: "2024-01-15" }, + }, + + // This units + { + expression: "this week", + expected: { startDate: "2024-01-15", endDate: "2024-01-21" }, + }, + { + expression: "this month", + expected: { startDate: "2024-01-01", endDate: "2024-01-31" }, + }, + { + expression: "this year", + expected: { startDate: "2024-01-01", endDate: "2024-12-31" }, + }, + + // Next X units + { + expression: "next week", + expected: { startDate: "2024-01-22", endDate: "2024-01-28" }, + }, + { + expression: "next month", + expected: { startDate: "2024-02-01", endDate: "2024-02-29" }, + }, + ])("$expression", async ({ expression, expected }) => { + await verifyDateRange(expression, expected); }); }); - describe("Special Time Ranges", () => { - test("yesterday", async () => { - const result = await getTimeRangeMs("yesterday"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - expect(startDate.toISODate()).toBe("2024-01-14"); - expect(endDate.toISODate()).toBe("2024-01-14"); - }); - - test("last week", async () => { - const result = await getTimeRangeMs("last week"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - expect(startDate.weekday).toBe(1); // Monday - expect(endDate.weekday).toBe(7); // Sunday - expect(startDate.weekNumber).toBe(endDate.weekNumber); - }); - - test("this month", async () => { - const result = await getTimeRangeMs("this month"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - expect(startDate.toISODate()).toBe("2024-01-01"); - expect(endDate.toISODate()).toBe("2024-01-31"); + describe("Week Patterns", () => { + test.each([ + { + expression: "week of 2024-01-10", + expected: { startDate: "2024-01-08", endDate: "2024-01-14" }, + }, + { + expression: "week of last monday", + expected: { startDate: "2024-01-08", endDate: "2024-01-14" }, + }, + { + expression: "week of january 10", + expected: { startDate: "2024-01-08", endDate: "2024-01-14" }, + }, + ])("$expression", async ({ expression, expected }) => { + await verifyDateRange(expression, expected); }); }); - describe("Week of Expressions", () => { - test("week of specific date", async () => { - const result = await getTimeRangeMs("week of July 1st"); - expect(result).toBeDefined(); - const startDate = DateTime.fromMillis(result!.startTime.epoch); - const endDate = DateTime.fromMillis(result!.endTime.epoch); - - // A full week is 7 days when including both start and end dates - expect(Math.round(endDate.diff(startDate, "days").days)).toBe(7); // 8 days total (inclusive) - expect(startDate.hour).toBe(0); // Start of day - expect(endDate.hour).toBe(23); // End of day - - // Verify it's in July - expect(startDate.month).toBe(7); // July + describe("Month Patterns", () => { + test.each([ + { + expression: "january", + expected: { startDate: "2024-01-01", endDate: "2024-01-31" }, + }, + { + expression: "december 2023", + expected: { startDate: "2023-12-01", endDate: "2023-12-31" }, + }, + ])("$expression", async ({ expression, expected }) => { + await verifyDateRange(expression, expected); }); }); - describe("Month Names", () => {
Why is this removed? Seems no new tests are covering every month name like this. We must make sure all the month names and their abbr are working.
obsidian-copilot
github_2023
typescript
1,316
logancyang
logancyang
@@ -0,0 +1,137 @@ +import { InlineEditCommandSettings } from "@/settings/model"; + +export const SELECTED_TEXT_PLACEHOLDER = "{copilot-selection}"; +export const COMMAND_NAME_MAX_LENGTH = 50; + +export const DEFAULT_INLINE_EDIT_COMMANDS: InlineEditCommandSettings[] = [ + { + name: "Fix grammar and spelling", + prompt: + `<instruction>Fix the grammar and spelling of the text below. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.</instruction>\n\n` + + `<text>${SELECTED_TEXT_PLACEHOLDER}</text>`, + showInContextMenu: true, + }, + { + name: "Translate to Chinese",
This is great. However, any default settings change must make sure it gets reflected without a setting reset. Right now, the prev setting didn't have this entry in the `inlineEditCommands`, so any change here won't show up without a setting reset. <img width="366" alt="SCR-20250303-kvum" src="https://github.com/user-attachments/assets/32664386-eb00-4225-814a-484d11113cae" /> Should we add a refresh button in the Commands setting tab to perform the necessary merging? It could be reused in the Model tab too.
obsidian-copilot
github_2023
typescript
1,303
logancyang
logancyang
@@ -119,7 +119,7 @@ export default class ChatModelManager { customModel.azureOpenAIApiDeploymentName || settings.azureOpenAIApiDeploymentName, openAIApiKey: await getDecryptedKey(customModel.apiKey || settings.azureOpenAIApiKey), configuration: { - baseURL: `https://copilot-experimental.openai.azure.com/openai/deployments/${customModel.azureOpenAIApiDeploymentName || settings.azureOpenAIApiDeploymentName}`,
lol, what did i do
obsidian-copilot
github_2023
typescript
1,261
logancyang
logancyang
@@ -75,86 +89,209 @@ function getInclusionPatterns(): string[] { if (!getSettings().qaInclusions) { return []; } - const inclusions: string[] = []; - inclusions.push( - ...getSettings() - .qaInclusions.split(",") - .map((item) => item.trim()) - ); - return inclusions; + return getDecodedPatterns(getSettings().qaInclusions); } /** * Get the inclusion and exclusion patterns from the settings. * @returns An object containing the inclusions and exclusions patterns strings. */ -export function getMatchingPatterns(): { inclusions: string[]; exclusions: string[] } { +export function getMatchingPatterns(): { + inclusions: PatternCategory | null; + exclusions: PatternCategory | null; +} { const inclusions = getInclusionPatterns(); const exclusions = getExclusionPatterns(); - return { inclusions, exclusions }; + return { + inclusions: inclusions ? categorizePatterns(inclusions) : null, + exclusions: exclusions ? categorizePatterns(exclusions) : null, + }; } -export function shouldIndexFile(file: TFile, inclusions: string[], exclusions: string[]): boolean { - if (exclusions.length > 0 && matchFilePathWithPatterns(file.path, exclusions)) { +/** + * Should index the file based on the inclusions and exclusions patterns. + * @param file - The file to check. + * @param inclusions - The inclusions patterns. + * @param exclusions - The exclusions patterns. + * @returns True if the file should be indexed, false otherwise. + */ +export function shouldIndexFile( + file: TFile, + inclusions: PatternCategory | null, + exclusions: PatternCategory | null +): boolean { + if (exclusions && matchFilePathWithPatterns(file.path, exclusions)) { return false; } - if (inclusions.length > 0 && !matchFilePathWithPatterns(file.path, inclusions)) { + if (inclusions && !matchFilePathWithPatterns(file.path, inclusions)) {
Is this check correct? `exclusions` and `inclusions` now exist even when the properties are all empty arrays. Now running "force re-index" with nothing in inclusion shows "0 file to index".
obsidian-copilot
github_2023
typescript
1,243
logancyang
logancyang
@@ -165,8 +165,6 @@ export const ModelAddDialog: React.FC<ModelAddDialogProps> = ({ if (!isEmbeddingModel) { return { ...baseModel, - temperature: 0.1, - context: 1000,
What is this "context" that was added in the new settings UI in aiParams? Missed it before.
obsidian-copilot
github_2023
typescript
1,225
logancyang
logancyang
@@ -52,46 +63,152 @@ export const ModelEditDialog: React.FC<ModelEditDialogProps> = ({ </DialogHeader> <div className="space-y-6"> - <div className="space-y-3"> - <div className="flex items-center justify-between"> - <div className="flex items-center gap-2"> - Temperature - <HelpCircle className="h-4 w-4 text-muted" /> - </div> - </div> - <SettingSlider - value={localModel.temperature ?? 0.1} - onChange={(value) => handleUpdate("temperature", value)} - max={2} - min={0} - step={0.1} + <FormField label="Model Name" required> + <Input + type="text" + disabled={localModel.core} + value={localModel.name} + onChange={(e) => handleUpdate("name", e.target.value)} + placeholder="Enter model name" /> - </div> + </FormField> - <div className="space-y-3"> - <div className="flex items-center justify-between"> - <div className="flex items-center gap-2"> - Context - <HelpCircle className="h-4 w-4 text-muted" /> + <FormField + label={ + <div className="flex items-center gap-1.5"> + <span className="leading-none">Display Name</span> + <TooltipProvider delayDuration={0}> + <Tooltip> + <TooltipTrigger asChild> + <HelpCircle className="size-4" /> + </TooltipTrigger> + <TooltipContent align="start" className="max-w-96" side="bottom"> + <div className="text-sm text-muted flex flex-col gap-0.5"> + <div className="text-[12px] font-bold">Suggested format:</div> + <div className="text-accent">[Source]-[Payment]:[Pretty Model Name]</div> + <div className="text-[12px]"> + Example: + <li>Direct-Paid:Ds-r1</li> + <li>OpenRouter-Paid:Ds-r1</li> + <li>Perplexity-Paid:lg</li> + </div> + </div> + </TooltipContent> + </Tooltip> + </TooltipProvider> </div> - </div> - <SettingSlider - value={localModel.context ?? 1000} - onChange={(value) => handleUpdate("context", value)} - max={16000} - min={0} - step={100} + } + > + <Input + type="text" + placeholder="Custom display name (optional)" + value={localModel.displayName || ""} + onChange={(e) => handleUpdate("displayName", e.target.value)} /> - </div> + </FormField> - <div className="py-2 border-b"> - <div className="flex items-center justify-between"> - <div className="flex items-center gap-2">Stream output</div> - <SettingSwitch - checked={localModel.stream ?? true} - onCheckedChange={(checked) => handleUpdate("stream", checked)} + <FormField label="Model Capabilities"> + <div className="flex gap-4 items-center"> + {capabilityOptions.map(({ id, label, description }) => ( + <div key={id} className="flex items-center gap-2"> + <Checkbox + id={id} + checked={localModel.capabilities?.includes(id)} + onCheckedChange={(checked) => { + const newCapabilities = localModel.capabilities || []; + handleUpdate( + "capabilities", + checked + ? [...newCapabilities, id] + : newCapabilities.filter((cap) => cap !== id) + ); + }} + /> + <Label htmlFor={id} className="text-sm"> + <TooltipProvider delayDuration={0}> + <Tooltip> + <TooltipTrigger asChild> + <span>{label}</span> + </TooltipTrigger> + <TooltipContent side="bottom">{description}</TooltipContent> + </Tooltip> + </TooltipProvider> + </Label> + </div> + ))} + </div> + </FormField> + + {/* <FormField
Should these be removed?
obsidian-copilot
github_2023
typescript
1,225
logancyang
logancyang
@@ -338,6 +340,12 @@ export const ProviderSettingsKeyMap: Record<DisplayKeyProviders, keyof CopilotSe "copilot-plus": "plusLicenseKey", }; +export const MODEL_CAPABILITIES: Record<ModelCapability, string> = { + reasoning: "This model supports general reasoning tasks.", + vision: "This model supports visual recognition.",
Just say it supports "image inputs"
obsidian-copilot
github_2023
typescript
1,225
logancyang
logancyang
@@ -77,6 +77,7 @@ export const BUILTIN_CHAT_MODELS: CustomModel[] = [ enabled: true, isBuiltIn: true, core: true, + capabilities: ["vision"],
The other builtin models should also be updated accordingly.
obsidian-copilot
github_2023
typescript
1,225
logancyang
logancyang
@@ -121,6 +134,7 @@ export const BUILTIN_CHAT_MODELS: CustomModel[] = [ provider: ChatModelProviders.ANTHROPIC, enabled: true, isBuiltIn: true, + capabilities: [ModelCapability.VISION],
Haiku doesn't support image, does it?
obsidian-copilot
github_2023
typescript
1,207
logancyang
logancyang
@@ -483,24 +486,59 @@ const ChatInput = forwardRef<{ focus: () => void }, ChatInputProps>( <DropdownMenu open={isModelDropdownOpen} onOpenChange={setIsModelDropdownOpen}> <DropdownMenuTrigger asChild> <Button variant="ghost2" size="fit"> - {settings.activeModels.find( - (model) => getModelKeyFromModel(model) === currentModelKey - )?.name || "Select Model"} + {modelError ? ( + <span className="text-error">Model Load Failed</span> + ) : ( + settings.activeModels.find( + (model) => model.enabled && getModelKeyFromModel(model) === currentModelKey + )?.name || "Select Model" + )} <ChevronDown className="size-5 mt-0.5" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="start"> {settings.activeModels .filter((model) => model.enabled) - .map((model) => ( - <DropdownMenuItem - key={getModelKeyFromModel(model)} - onSelect={() => setCurrentModelKey(getModelKeyFromModel(model))} - > - {model.name} - </DropdownMenuItem> - ))} + .map((model) => { + const providerKeyName = + ProviderSettingsKeyMap[model.provider as DisplayKeyProviders]; + const hasNoApiKey = !model.apiKey && !settings[providerKeyName]; + return ( + <DropdownMenuItem + key={getModelKeyFromModel(model)} + onSelect={async (event) => { + if (hasNoApiKey) { + event.preventDefault(); + const notice = + `Please configure API Key for ${model.name} in settings first.` + + "\nPath: Settings > copilot plugin > Basic Tab > Set Keys"; + new Notice(notice); + return; + } + + try { + setModelError(null); + setCurrentModelKey(getModelKeyFromModel(model)); + } catch (error) { + const msg = `Model switch failed: ` + err2String(error); + setModelError(msg); + new Notice(msg); + // Restore to the last valid model + const lastValidModel = settings.activeModels.find( + (m) => getModelKeyFromModel(m) === currentModelKey + ); + if (lastValidModel) {
Can there be a case where there's no lastValidModel?
obsidian-copilot
github_2023
typescript
1,207
logancyang
logancyang
@@ -158,6 +160,21 @@ const BasicSettings: React.FC<BasicSettingsProps> = ({ indexVaultToVectorStore } description="Select the Chat model to use" value={settings.defaultModelKey} onChange={(value) => { + const selectedModel = settings.activeModels.find( + (m) => m.enabled && getModelKeyFromModel(m) === value + ); + if (selectedModel) { + const providerKeyName = + ProviderSettingsKeyMap[selectedModel.provider as DisplayKeyProviders]; + const hasNoApiKey = !selectedModel.apiKey && !settings[providerKeyName]; + if (hasNoApiKey) { + const notice =
This code is duplicated as in the other file. Can be reused as a util. Something to follow up on.
obsidian-copilot
github_2023
typescript
1,153
logancyang
logancyang
@@ -13,7 +13,7 @@ export const DEFAULT_SYSTEM_PROMPT = `You are Obsidian Copilot, a helpful assist 4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context. If there's no relevant information in the vault, just say so. 5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query. 6. Always use $'s instead of \\[ etc. for LaTeX equations. - 7. When showing note titles, use [[title]] format and do not wrap them in \` \`. + 7. When showing note titles, use [title](url) format and do not wrap them in \` \`.
Have you tested this? Does it work for you? I don't see how the model can get the `url` from anywhere.
obsidian-copilot
github_2023
typescript
1,153
logancyang
logancyang
@@ -13,7 +13,7 @@ export const DEFAULT_SYSTEM_PROMPT = `You are Obsidian Copilot, a helpful assist 4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context. If there's no relevant information in the vault, just say so. 5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query. 6. Always use $'s instead of \\[ etc. for LaTeX equations. - 7. When showing note titles, use [[title]] format and do not wrap them in \` \`. + 7. When showing note titles, use [title](obsidian://open?file=FILENAME) format and do not wrap them in \` \`.
Again, have you tested this? Can you please show an example with this system prompt, what does it really return in the response.
obsidian-copilot
github_2023
typescript
1,059
logancyang
logancyang
@@ -502,6 +502,7 @@ export const DEFAULT_SETTINGS: CopilotSettings = { numPartitions: 1, enabledCommands: {}, promptUsageTimestamps: {}, + defaultConversationNoteName: "{$date}_{$time}__{$topic}",
We should use a backward-compatible pattern, right now it is `{$topic}@{$date}_{$time}`.
obsidian-copilot
github_2023
typescript
1,160
logancyang
logancyang
@@ -0,0 +1,102 @@ +import { ChainType } from "@/chainFactory"; +import { + ChatModelProviders, + ChatModels, + DEFAULT_SETTINGS, + EmbeddingModelProviders, + EmbeddingModels, + PlusUtmMedium, +} from "@/constants"; +import { BrevilabsClient } from "@/LLMProviders/brevilabsClient"; +import { getSettings, setSettings, updateSetting, useSettingsValue } from "@/settings/model"; +import { setChainType, setModelKey } from "@/aiParams"; +import { CopilotPlusWelcomeModal } from "@/components/modals/CopilotPlusWelcomeModal"; +import { CopilotPlusExpiredModal } from "@/components/modals/CopilotPlusExpiredModal"; +import VectorStoreManager from "@/search/vectorStoreManager"; + +export const DEFAULT_COPILOT_PLUS_CHAT_MODEL = ChatModels.COPILOT_PLUS_FLASH; +export const DEFAULT_COPILOT_PLUS_CHAT_MODEL_KEY = + DEFAULT_COPILOT_PLUS_CHAT_MODEL + "|" + ChatModelProviders.COPILOT_PLUS; +export const DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL = EmbeddingModels.COPILOT_PLUS_SMALL; +export const DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL_KEY = + DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL + "|" + EmbeddingModelProviders.COPILOT_PLUS; + +/** Check if the model key is a Copilot Plus model. */ +export function isPlusModel(modelKey: string): boolean { + return modelKey.split("|")[1] === EmbeddingModelProviders.COPILOT_PLUS; +} + +/** Hook to get the isPlusUser setting. */ +export function useIsPlusUser(): boolean | undefined { + const settings = useSettingsValue(); + return settings.isPlusUser; +} + +/** Check if the user is a Plus user. */ +export async function checkIsPlusUser(): Promise<boolean | undefined> { + if (!getSettings().plusLicenseKey) { + turnOffPlus(); + return false; + } + const brevilabsClient = BrevilabsClient.getInstance(); + return await brevilabsClient.validateLicenseKey(); +} + +/** + * Switch to the Copilot Plus chat and embedding models. + * WARNING! If the embedding model is changed, the vault will be indexed. Use it + * with caution. + */ +export function switchToPlusModels(): void { + const defaultModelKey = DEFAULT_COPILOT_PLUS_CHAT_MODEL_KEY; + const embeddingModelKey = DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL_KEY; + const previousEmbeddingModelKey = getSettings().embeddingModelKey; + setModelKey(defaultModelKey); + setSettings({ + defaultModelKey, + embeddingModelKey, + }); + if (previousEmbeddingModelKey !== embeddingModelKey) { + VectorStoreManager.getInstance().indexVaultToVectorStore(true); + } +} + +export function createPlusPageUrl(medium: PlusUtmMedium): string { + return `https://www.obsidiancopilot.com?utm_source=obsidian&utm_medium=${medium}`; +} + +export function navigateToPlusPage(medium: PlusUtmMedium): void { + window.open(createPlusPageUrl(medium), "_blank"); +} + +export function updatePlusUserSettings(isPlusUser: boolean): void { + updateSetting("isPlusUser", isPlusUser); + if (isPlusUser) { + setChainType(ChainType.COPILOT_PLUS_CHAIN); + setSettings({ + defaultChainType: ChainType.COPILOT_PLUS_CHAIN, + }); + // Do not set models here because it needs user confirmation. + } else { + setModelKey(DEFAULT_SETTINGS.defaultModelKey); + setChainType(DEFAULT_SETTINGS.defaultChainType); + } +} + +export function turnOnPlus(): void { + const isPlusUser = getSettings().isPlusUser; + updatePlusUserSettings(true); + // Do not show the welcome modal if the user is already a plus user before + // 2024/02/04 (isPlusUser === undefined) + if (isPlusUser === false) {
Should this be `isPlusUser !== true`? Right now this welcome modal is not showing up for new users (undefined).
obsidian-copilot
github_2023
typescript
1,148
logancyang
logancyang
@@ -82,49 +82,60 @@ export const getNotesFromPath = async (vault: Vault, path: string): Promise<TFil }); }; -export async function getTagsFromNote(file: TFile, vault: Vault): Promise<string[]> { - const fileContent = await vault.cachedRead(file); - // Check if the file starts with frontmatter delimiter - if (fileContent.startsWith("---")) { - const frontMatterBlock = fileContent.split("---", 3); - // Ensure there's a closing delimiter for frontmatter - if (frontMatterBlock.length >= 3) { - const frontMatterContent = frontMatterBlock[1]; - try { - const frontMatter = parseYaml(frontMatterContent) || {}; - const tags = frontMatter.tags || []; - // Handle both array and string formats of tags - const normalizedTags = Array.isArray(tags) ? tags : [tags]; - // Strip any '#' from the frontmatter tags and convert to lowercase - return normalizedTags - .map((tag: string) => tag.toString().replace(/^#/, "")) - .map((tag: string) => tag.toLowerCase()); - } catch (error) { - console.error("Error parsing YAML frontmatter:", error); - return []; - } +/** + * @param tag - The tag to strip the hash symbol from. + * @returns The tag without the hash symbol in lowercase. + */ +export function stripHash(tag: string): string { + return tag.replace(/^#/, "").trim().toLowerCase(); +} + +/** + * @param file - The note file to get tags from. + * @param vault - The vault to get tags from. + * @returns An array of lowercase tags without the hash symbol. + */ +export function getTagsFromNote(file: TFile): string[] {
This is now returning both inline and frontmatter tags, while before it only returns frontmatter tags. The reason I only get frontmatter tags is to 1. Limit the number of notes from tags for custom prompt templating {#tag1, #tags2...} and avoiding overcrowding the context window 2. Have a differentiation between frontmatter tags and inline tags. Consider frontmatter tags a "note-level" property and inline tags as "line/block-level" property. So this change will affect not only index filtering but also custom prompt processing. Currently, inline tags are used via salient terms during vault search. Should we put a parameter here to control what tags to return? Such as `frontmatterOnly = true`
obsidian-copilot
github_2023
typescript
904
logancyang
logancyang
@@ -73,6 +67,7 @@ export interface CustomModel { isBuiltIn?: boolean; enableCors?: boolean; core?: boolean; + azureOpenAIApiDeploymentName?: string; // Added for Azure OpenAI models
Isn't this the same as the one above?
obsidian-copilot
github_2023
typescript
955
logancyang
logancyang
@@ -337,8 +339,13 @@ export default class ChatModelManager { ); return true; } catch (error) { - console.error("Chat model ping failed:", error); - throw error; + const msg = + "\nwithout CORS Error: " + + err2String(firstError) + + "\nwith CORS Error: " + + err2String(error); + // console.error("Chat model ping failed:", error);
Nit: keep or remove?
obsidian-copilot
github_2023
typescript
955
logancyang
logancyang
@@ -73,6 +73,17 @@ export interface CustomModel { isBuiltIn?: boolean; enableCors?: boolean; core?: boolean; + stream?: boolean; + temperature?: number; + context?: number;
What is `context`? I assume you mean `maxToken`?
obsidian-copilot
github_2023
typescript
955
logancyang
logancyang
@@ -44,6 +45,10 @@ export class CopilotSettingTab extends PluginSettingTab { const div = containerEl.createDiv("div"); const sections = createRoot(div); + if (!Platform.isMobile) { + sections.render(<SettingsMainV2 plugin={this.plugin} />); + return; + }
Does this mean mobile is still using the old settings? Do we plan to update mobile too in the future?
obsidian-copilot
github_2023
typescript
955
logancyang
zeroliu
@@ -0,0 +1,36 @@ +import React, { createContext, useContext, useEffect, useState } from "react"; + +interface TabContextType { + selectedTab: string; + setSelectedTab: (tab: string) => void; + modalContainer: HTMLElement | null; +} + +const TabContext = createContext<TabContextType | undefined>(undefined); + +export const TabProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const [selectedTab, setSelectedTab] = useState("basic"); + const [modalContainer, setModalContainer] = useState<HTMLElement | null>(null); + + useEffect(() => { + // fix + if (!modalContainer) { + const modal = document.querySelector(".modal-container") as HTMLElement; + setModalContainer(modal); + } + }, []);
there is an eslint error here. Also what's the reason for this effect?
obsidian-copilot
github_2023
typescript
955
logancyang
zeroliu
@@ -0,0 +1,211 @@ +import React, { useState, useEffect } from "react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Loader2 } from "lucide-react"; +import { PasswordInput } from "@/components/ui/password-input"; +import { err2String, getProviderInfo, getProviderLabel } from "@/utils"; +import { + ChatModelProviders, + DisplayKeyProviders, + EmbeddingModelProviders, + Provider, + ProviderInfo, + ProviderSettingsKeyMap, +} from "@/constants"; +import { Notice } from "obsidian"; +import ChatModelManager from "@/LLMProviders/chatModelManager"; +import { CustomModel } from "@/aiParams"; +import { CopilotSettings } from "@/settings/model"; + +interface ApiKeyDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + settings: Readonly<CopilotSettings>; + updateSetting: (key: string, value: any) => void; + modalContainer: HTMLElement | null; +} + +interface ProviderKeyItem { + provider: DisplayKeyProviders; + apiKey: string; + isVerified: boolean; +} + +const ApiKeyDialog: React.FC<ApiKeyDialogProps> = ({ + open, + onOpenChange, + settings, + updateSetting, + modalContainer, +}) => { + const [verifyingProviders, setVerifyingProviders] = useState<Set<DisplayKeyProviders>>(new Set()); + const [unverifiedKeys, setUnverifiedKeys] = useState<Set<DisplayKeyProviders>>(new Set()); + + // 在 dialog 打开时重置未验证的 keys 集合 + useEffect(() => { + if (open) { + setUnverifiedKeys(new Set()); + } + }, [open]); + + // 在 dialog 关闭时清空未验证的 keys + useEffect(() => { + if (!open) { + unverifiedKeys.forEach((provider) => { + const settingKey = ProviderSettingsKeyMap[provider]; + updateSetting(settingKey, ""); + }); + } + }, [open]);
please fix the dependency
obsidian-copilot
github_2023
typescript
955
logancyang
zeroliu
@@ -0,0 +1,211 @@ +import React, { useState, useEffect } from "react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Loader2 } from "lucide-react"; +import { PasswordInput } from "@/components/ui/password-input"; +import { err2String, getProviderInfo, getProviderLabel } from "@/utils"; +import { + ChatModelProviders, + DisplayKeyProviders, + EmbeddingModelProviders, + Provider, + ProviderInfo, + ProviderSettingsKeyMap, +} from "@/constants"; +import { Notice } from "obsidian"; +import ChatModelManager from "@/LLMProviders/chatModelManager"; +import { CustomModel } from "@/aiParams"; +import { CopilotSettings } from "@/settings/model"; + +interface ApiKeyDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + settings: Readonly<CopilotSettings>; + updateSetting: (key: string, value: any) => void; + modalContainer: HTMLElement | null; +} + +interface ProviderKeyItem { + provider: DisplayKeyProviders; + apiKey: string; + isVerified: boolean; +} + +const ApiKeyDialog: React.FC<ApiKeyDialogProps> = ({ + open, + onOpenChange, + settings, + updateSetting, + modalContainer, +}) => { + const [verifyingProviders, setVerifyingProviders] = useState<Set<DisplayKeyProviders>>(new Set()); + const [unverifiedKeys, setUnverifiedKeys] = useState<Set<DisplayKeyProviders>>(new Set()); + + // 在 dialog 打开时重置未验证的 keys 集合 + useEffect(() => { + if (open) { + setUnverifiedKeys(new Set()); + } + }, [open]);
why can't this happen when the dialog closes too?